From 04c1302b68fa81221b6fb76968f296baadfcdeea Mon Sep 17 00:00:00 2001 From: Harald Welte Date: Thu, 21 Oct 2021 10:02:10 +0200 Subject: [PATCH] tlv: Don't require encoder/decoder methods for TLV without value There are instances where a TLV IE is used as just a flag, i.e. length zero and no value part. In those situations, it would require a lot of boilerplate code to require the TLV_IE class definitions to have _to_bytes/_from_bytes methods that do nothing. So instead, add a shortcut: If we want to encode 'None', then return b'', and if we want to decode b'' return None. Change-Id: Ie8eb2830e8eefa81e94b8b8b157062c085aeb777 --- pySim/tlv.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pySim/tlv.py b/pySim/tlv.py index 05f824eb..0dc746b3 100644 --- a/pySim/tlv.py +++ b/pySim/tlv.py @@ -80,7 +80,9 @@ class Transcodable(abc.ABC): def to_bytes(self) -> bytes: """Convert from internal representation to binary bytes. Store the binary result in the internal state and return it.""" - if self._construct: + if not self.decoded: + do = b'' + elif self._construct: do = self._construct.build(self.decoded, total_len=None) elif self.__class__._construct: do = self.__class__._construct.build(self.decoded, total_len=None) @@ -97,7 +99,9 @@ class Transcodable(abc.ABC): """Convert from binary bytes to internal representation. Store the decoded result in the internal state and return it.""" self.encoded = do - if self._construct: + if self.encoded == b'': + self.decoded = None + elif self._construct: self.decoded = parse_construct(self._construct, do) elif self.__class__._construct: self.decoded = parse_construct(self.__class__._construct, do)