laforge submitted this change.
osmocom.construct: Bytes + GreedyBytes with automatic hexstring-conversion
This is a convenience version of the Bytes / GreedyBytes construct
that accepts not only a bytes/bytearray object, but also a hex-encoded
string within the encoder.
Related: OS#6774
Change-Id: I59f500c925848872a7fa38d6dbf3d6ea72bc3a90
---
M src/osmocom/construct.py
1 file changed, 16 insertions(+), 2 deletions(-)
diff --git a/src/osmocom/construct.py b/src/osmocom/construct.py
index 7a2851a..5e062c3 100644
--- a/src/osmocom/construct.py
+++ b/src/osmocom/construct.py
@@ -10,9 +10,10 @@
# pylint: disable=import-error,no-name-in-module
from construct.lib.containers import Container, ListContainer
from construct.core import EnumIntegerString
-from construct import Adapter, Prefixed, Int8ub, GreedyBytes, Default, Flag, Byte, Construct, Enum
-from construct import BitsInteger, BitStruct, Bytes, StreamError, stream_read_entire, stream_write
+from construct import Adapter, Prefixed, Int8ub, Default, Flag, Byte, Construct, Enum
+from construct import BitsInteger, BitStruct, StreamError, stream_read_entire, stream_write
from construct import SizeofError, IntegerError, swapbytes
+import construct
from construct.core import evaluate
from construct.lib import integertypes
@@ -33,6 +34,19 @@
# 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 Bytes(construct.Bytes):
+ """Just like construct.Bytes but supporting hex-string input."""
+ def _build(self, obj, stream, context, path):
+ data = h2b(obj) if isinstance(obj, str) else obj
+ return super()._build(data, stream, context, path)
+
+@construct.core.singleton
+class GreedyBytes(construct.GreedyBytes.__class__):
+ """Just like construct.GreedyBytes but supporting hex-string input."""
+ def _build(self, obj, stream, context, path):
+ data = h2b(obj) if isinstance(obj, str) else obj
+ return super()._build(data, stream, context, path)
+
class HexAdapter(Adapter):
"""convert a bytes() type to a string of hex nibbles."""
To view, visit change 40117. To unsubscribe, or for help writing mail filters, visit settings.