38
38
DATA_TYPES = (VISIBLE_STRING , OCTET_STRING , UNICODE_STRING , DOMAIN )
39
39
40
40
41
- class UnsignedN :
41
+ class UnsignedN ( struct . Struct ) :
42
42
"""Packing and unpacking unsigned integers of arbitrary width, like struct.Struct.
43
43
44
44
The width must be a multiple of 8 and must be between 8 and 64.
@@ -50,26 +50,27 @@ def __init__(self, width: int):
50
50
if width <= 0 or width > 64 :
51
51
raise ValueError ("Invalid width for UnsignedN" )
52
52
elif width <= 8 :
53
- self . struct = struct . Struct ( "B" )
53
+ fmt = "B"
54
54
elif width <= 16 :
55
- self . struct = struct . Struct ( "<H" )
55
+ fmt = "<H"
56
56
elif width <= 32 :
57
- self . struct = struct . Struct ( "<L" )
57
+ fmt = "<L"
58
58
else :
59
- self .struct = struct .Struct ("<Q" )
59
+ fmt = "<Q"
60
+ super ().__init__ (fmt )
60
61
61
62
def unpack (self , buffer ):
62
- return self . struct . unpack (buffer + b'\x00 ' * (self . struct .size - self .size ))
63
+ return super (). unpack (buffer + b'\x00 ' * (super () .size - self .size ))
63
64
64
65
def pack (self , * v ):
65
- return self . struct .pack (* v )[:self .size ]
66
+ return super () .pack (* v )[:self .size ]
66
67
67
68
@property
68
- def size (self ):
69
+ def size (self ) -> int :
69
70
return self .width // 8
70
71
71
72
72
- class IntegerN :
73
+ class IntegerN ( struct . Struct ) :
73
74
"""Packing and unpacking integers of arbitrary width, like struct.Struct.
74
75
75
76
The width must be a multiple of 8 and must be between 8 and 64.
@@ -81,22 +82,23 @@ def __init__(self, width: int):
81
82
if width <= 0 or width > 64 :
82
83
raise ValueError ("Invalid width for IntegerN" )
83
84
elif width <= 8 :
84
- self . struct = struct . Struct ( "b" )
85
+ fmt = "b"
85
86
elif width <= 16 :
86
- self . struct = struct . Struct ( "<h" )
87
+ fmt = "<h"
87
88
elif width <= 32 :
88
- self . struct = struct . Struct ( "<l" )
89
+ fmt = "<l"
89
90
else :
90
- self .struct = struct .Struct ("<q" )
91
+ fmt = "<q"
92
+ super ().__init__ (fmt )
91
93
92
94
def unpack (self , buffer ):
93
95
mask = 0x80
94
96
neg = (buffer [self .size - 1 ] & mask ) > 0
95
- return self . struct . unpack (buffer + (b'\xff ' if neg else b'\x00 ' ) * (self . struct .size - self .size ))
97
+ return super (). unpack (buffer + (b'\xff ' if neg else b'\x00 ' ) * (super () .size - self .size ))
96
98
97
99
def pack (self , * v ):
98
- return self . struct .pack (* v )[:self .size ]
100
+ return super () .pack (* v )[:self .size ]
99
101
100
102
@property
101
- def size (self ):
103
+ def size (self ) -> int :
102
104
return self .width // 8
0 commit comments