aboutsummaryrefslogtreecommitdiffstats
path: root/pySim/tlv.py
diff options
context:
space:
mode:
authorHarald Welte <laforge@osmocom.org>2021-10-21 10:02:10 +0200
committerHarald Welte <laforge@osmocom.org>2021-10-21 14:12:13 +0200
commit04c1302b68fa81221b6fb76968f296baadfcdeea (patch)
treeba04158c66024b007baef4d92e7d218ef82aeccc /pySim/tlv.py
parent0bc5326b767eef5fd308c99f44aee0b04d6e87cb (diff)
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
Diffstat (limited to 'pySim/tlv.py')
-rw-r--r--pySim/tlv.py8
1 files changed, 6 insertions, 2 deletions
diff --git a/pySim/tlv.py b/pySim/tlv.py
index 05f824e..0dc746b 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)