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
This commit is contained in:
Harald Welte 2021-10-21 10:02:10 +02:00
parent 0bc5326b76
commit 04c1302b68
1 changed files with 6 additions and 2 deletions

View File

@ -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)