laforge has submitted this change. ( https://gerrit.osmocom.org/c/python/pyosmocom/+/40117?usp=email )
Change subject: osmocom.construct: Bytes + GreedyBytes with automatic hexstring-conversion ......................................................................
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(-)
Approvals: fixeria: Looks good to me, but someone else must approve Jenkins Builder: Verified osmith: Looks good to me, approved
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."""