Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 1 | from construct import * |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 2 | from pySim.utils import b2h, h2b, swap_nibbles |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 3 | |
| 4 | """Utility code related to the integration of the 'construct' declarative parser.""" |
| 5 | |
| 6 | # (C) 2021 by Harald Welte <laforge@osmocom.org> |
| 7 | # |
| 8 | # This program is free software: you can redistribute it and/or modify |
| 9 | # it under the terms of the GNU General Public License as published by |
| 10 | # the Free Software Foundation, either version 2 of the License, or |
| 11 | # (at your option) any later version. |
| 12 | # |
| 13 | # This program is distributed in the hope that it will be useful, |
| 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 | # GNU General Public License for more details. |
| 17 | # |
| 18 | # You should have received a copy of the GNU General Public License |
| 19 | # along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 20 | |
| 21 | |
| 22 | class HexAdapter(Adapter): |
| 23 | """convert a bytes() type to a string of hex nibbles.""" |
| 24 | def _decode(self, obj, context, path): |
| 25 | return b2h(obj) |
| 26 | def _encode(self, obj, context, path): |
| 27 | return h2b(obj) |
| 28 | |
Harald Welte | 2db5cfb | 2021-04-10 19:05:37 +0200 | [diff] [blame] | 29 | class BcdAdapter(Adapter): |
| 30 | """convert a bytes() type to a string of BCD nibbles.""" |
| 31 | def _decode(self, obj, context, path): |
| 32 | return swap_nibbles(b2h(obj)) |
| 33 | def _encode(self, obj, context, path): |
| 34 | return h2b(swap_nibbles(obj)) |
| 35 | |
Harald Welte | e0f9ef1 | 2021-04-10 17:22:35 +0200 | [diff] [blame] | 36 | def filter_dict(d, exclude_prefix='_'): |
| 37 | """filter the input dict to ensure no keys starting with 'exclude_prefix' remain.""" |
| 38 | res = {} |
| 39 | for (key, value) in d.items(): |
| 40 | if key.startswith(exclude_prefix): |
| 41 | continue |
| 42 | if type(value) is dict: |
| 43 | res[key] = filter_dict(value) |
| 44 | else: |
| 45 | res[key] = value |
| 46 | return res |
| 47 | |
| 48 | # here we collect some shared / common definitions of data types |
| 49 | LV = Prefixed(Int8ub, HexAdapter(GreedyBytes)) |