Coverage for d7a/alp/operands/length.py: 90%
41 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-24 08:03 +0200
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-24 08:03 +0200
1#
2# Copyright (c) 2015-2021 University of Antwerp, Aloxy NV.
3#
4# This file is part of pyd7a.
5# See https://github.com/Sub-IoT/pyd7a for further info.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19import struct
21from d7a.support.schema import Validatable, Types
24class Length(Validatable):
26 SCHEMA = [
27 {
28 "value": Types.INTEGER(min=0, max=0x3FFFFFFF)
29 }
30 ]
32 def __init__(self, value=0):
33 self.value = value
34 super(Length, self).__init__()
36 @staticmethod
37 def parse(s):
38 size = s.read("uint:2") # + 1 = already read
39 value = s.read("uint:" + str(6 + (size * 8)))
40 return Length(value=value)
42 def __iter__(self):
43 byte = 0
44 size = 1
45 if self.value > 0x3F:
46 size = 2
47 if self.value > 0x3FFF:
48 size = 3
49 if self.value > 0x3FFFFF:
50 size = 4
52 byte += (size - 1) << 6
54 if size == 1:
55 byte += self.value
56 yield byte
57 else:
58 length_bytes = bytearray(struct.pack(">I", self.value))
59 if size == 2: length_bytes = length_bytes[2:]
60 elif size == 3: length_bytes = length_bytes[1:]
62 byte += length_bytes[0]
63 yield byte
64 for byte in length_bytes[1:]: yield byte
66 def __str__(self):
67 return str(self.value)
69 def __eq__(self, other):
70 if isinstance(other, self.__class__):
71 return self.value == other.value
72 elif isinstance(other, int):
73 return self.value == other
74 else:
75 return False
77 def __ne__(self, other):
78 return not self.__eq__(other)