aboutsummaryrefslogtreecommitdiffstats
path: root/pySim/construct.py
diff options
context:
space:
mode:
authorHarald Welte <laforge@osmocom.org>2021-04-10 17:22:35 +0200
committerHarald Welte <laforge@osmocom.org>2021-04-11 12:20:29 +0200
commite0f9ef16060f91d1ff36dbbac77ae44c9bac4b7a (patch)
tree5a4c0f683f849d23e7936e47dd2507dd3e13b309 /pySim/construct.py
parentd0505bdb5574257ce52404384864a596227f79bb (diff)
integrate 'construct' python library
'construct' is a declarative symmetric encoder/decoder for user specified binary formats. It should come in extremely handy in tools like pySim. We start the integration by adding transport methods for transceiving APDUs with built-in encoding of the command data and decoding of the response data. Change-Id: Ibf457aa8b9480a8db5979defcfafd67674303f6c
Diffstat (limited to 'pySim/construct.py')
-rw-r--r--pySim/construct.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/pySim/construct.py b/pySim/construct.py
new file mode 100644
index 0000000..03d284e
--- /dev/null
+++ b/pySim/construct.py
@@ -0,0 +1,42 @@
+from construct import *
+from pySim.utils import b2h, h2b
+
+"""Utility code related to the integration of the 'construct' declarative parser."""
+
+# (C) 2021 by Harald Welte <laforge@osmocom.org>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class HexAdapter(Adapter):
+ """convert a bytes() type to a string of hex nibbles."""
+ def _decode(self, obj, context, path):
+ return b2h(obj)
+ def _encode(self, obj, context, path):
+ return h2b(obj)
+
+def filter_dict(d, exclude_prefix='_'):
+ """filter the input dict to ensure no keys starting with 'exclude_prefix' remain."""
+ res = {}
+ for (key, value) in d.items():
+ if key.startswith(exclude_prefix):
+ continue
+ if type(value) is dict:
+ res[key] = filter_dict(value)
+ else:
+ res[key] = value
+ return res
+
+# here we collect some shared / common definitions of data types
+LV = Prefixed(Int8ub, HexAdapter(GreedyBytes))