pyosmocom 0.0.2__tar.gz → 0.0.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyosmocom
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Python implementation of core osmocom utilities / protocols
5
5
  Maintainer-email: openbsc@lists.osmocom.org
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyosmocom"
7
- version = "0.0.2"
7
+ version = "0.0.4"
8
8
  dependencies = [
9
9
  "gsm0338",
10
10
  "construct >= 2.9.51"
@@ -341,7 +341,7 @@ class Rpad(Adapter):
341
341
  return obj.rstrip(self.pattern)
342
342
 
343
343
  def _encode(self, obj, context, path):
344
- target_size = self.sizeof() * self.num_per_byte
344
+ target_size = self.sizeof(**context) * self.num_per_byte
345
345
  if len(obj) > target_size:
346
346
  raise SizeofError("Input ({}) exceeds target size ({})".format(
347
347
  len(obj), target_size))
@@ -492,7 +492,8 @@ def parse_construct(c, raw_bin_data: bytes, length: typing.Optional[int] = None,
492
492
 
493
493
  def build_construct(c, decoded_data, context: dict = {}):
494
494
  """Helper function to handle total_len."""
495
- return c.build(decoded_data, total_len=None, **context)
495
+ context.setdefault('total_len', None)
496
+ return c.build(decoded_data, **context)
496
497
 
497
498
  # here we collect some shared / common definitions of data types
498
499
  LV = Prefixed(Int8ub, HexAdapter(GreedyBytes))
@@ -27,7 +27,43 @@ from typing import Optional, List, NewType
27
27
  # along with this program. If not, see <http://www.gnu.org/licenses/>.
28
28
  #
29
29
 
30
- # just to differentiate strings of hex nibbles from everything else
30
+ class hexstr(str):
31
+ """Class derived from 'str', represeting a string of hexadecimal digits. It differs in that
32
+ comparisons are case-insensitive, and it offers encoding-free conversion from hexstr to bytes
33
+ and vice-versa."""
34
+ def __new__(cls, s: str):
35
+ if not all(c in string.hexdigits for c in s):
36
+ raise ValueError('Input must be hexadecimal digits only')
37
+ # store as lower case digits
38
+ return super().__new__(cls, s.lower())
39
+
40
+ def __eq__(self, other: str) -> bool:
41
+ # make sure comparison is done case-insensitive
42
+ return str(self) == other.lower()
43
+
44
+ def __hash__(self):
45
+ # having a custom __eq__ method will make the type unhashable by default, lets fix that
46
+ return hash(str(self))
47
+
48
+ def __getitem__(self, val) -> 'hexstr':
49
+ # make sure slicing a hexstr will return a hexstr
50
+ return hexstr(super().__getitem__(val))
51
+
52
+ def to_bytes(self) -> bytes:
53
+ """return hex-string converted to bytes"""
54
+ s = str(self)
55
+ if len(s) & 1:
56
+ raise ValueError('Cannot convert hex string with odd number of digits')
57
+ return h2b(s)
58
+
59
+ @classmethod
60
+ def from_bytes(cls, bt: bytes) -> 'hexstr':
61
+ """instantiate hex-string from bytes"""
62
+ return cls(b2h(bt))
63
+
64
+ # just to differentiate strings of hex nibbles from everything else; only used for typing
65
+ # hints. New code should typically use the 'class hexstr' type above to get the benefit
66
+ # of case-insensitive comparison.
31
67
  Hexstr = NewType('Hexstr', str)
32
68
 
33
69
  def h2b(s: Hexstr) -> bytearray:
@@ -35,9 +71,9 @@ def h2b(s: Hexstr) -> bytearray:
35
71
  return bytearray.fromhex(s)
36
72
 
37
73
 
38
- def b2h(b: bytearray) -> Hexstr:
74
+ def b2h(b: bytearray) -> hexstr:
39
75
  """convert from a sequence of bytes to a string of hex nibbles"""
40
- return ''.join(['%02x' % (x) for x in b])
76
+ return hexstr(''.join(['%02x' % (x) for x in b]))
41
77
 
42
78
 
43
79
  def h2i(s: Hexstr) -> List[int]:
@@ -45,9 +81,9 @@ def h2i(s: Hexstr) -> List[int]:
45
81
  return [(int(x, 16) << 4)+int(y, 16) for x, y in zip(s[0::2], s[1::2])]
46
82
 
47
83
 
48
- def i2h(s: List[int]) -> Hexstr:
84
+ def i2h(s: List[int]) -> hexstr:
49
85
  """convert from a list of integers to a string of hex nibbles"""
50
- return ''.join(['%02x' % (x) for x in s])
86
+ return hexstr(''.join(['%02x' % (x) for x in s]))
51
87
 
52
88
 
53
89
  def h2s(s: Hexstr) -> str:
@@ -56,7 +92,7 @@ def h2s(s: Hexstr) -> str:
56
92
  if int(x + y, 16) != 0xff])
57
93
 
58
94
 
59
- def s2h(s: str) -> Hexstr:
95
+ def s2h(s: str) -> hexstr:
60
96
  """convert from an ASCII string to a string of hex nibbles"""
61
97
  b = bytearray()
62
98
  b.extend(map(ord, s))
@@ -68,9 +104,9 @@ def i2s(s: List[int]) -> str:
68
104
  return ''.join([chr(x) for x in s])
69
105
 
70
106
 
71
- def swap_nibbles(s: Hexstr) -> Hexstr:
107
+ def swap_nibbles(s: Hexstr) -> hexstr:
72
108
  """swap the nibbles in a hex string"""
73
- return ''.join([x+y for x, y in zip(s[1::2], s[0::2])])
109
+ return hexstr(''.join([x+y for x, y in zip(s[1::2], s[0::2])]))
74
110
 
75
111
 
76
112
  def rpad(s: str, l: int, c='f') -> str:
@@ -171,16 +207,16 @@ def is_hexstr_or_decimal(instr: str) -> str:
171
207
  raise ValueError('Input must be [hexa]decimal')
172
208
  if len(instr) & 1:
173
209
  raise ValueError('Input has un-even number of hex digits')
174
- return instr
210
+ return hexstr(instr)
175
211
 
176
- def is_hexstr(instr: str) -> str:
212
+ def is_hexstr(instr: str) -> hexstr:
177
213
  """Method that can be used as 'type' in argparse.add_argument() to validate the value consists of
178
214
  an even sequence of hexadecimal digits only."""
179
215
  if not all(c in string.hexdigits for c in instr):
180
216
  raise ValueError('Input must be hexadecimal')
181
217
  if len(instr) & 1:
182
218
  raise ValueError('Input has un-even number of hex digits')
183
- return instr
219
+ return hexstr(instr)
184
220
 
185
221
  def is_decimal(instr: str) -> str:
186
222
  """Method that can be used as 'type' in argparse.add_argument() to validate the value consists of
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: pyosmocom
3
- Version: 0.0.2
3
+ Version: 0.0.4
4
4
  Summary: Python implementation of core osmocom utilities / protocols
5
5
  Maintainer-email: openbsc@lists.osmocom.org
6
6
  License: GNU GENERAL PUBLIC LICENSE
@@ -15,4 +15,5 @@ src/pyosmocom.egg-info/requires.txt
15
15
  src/pyosmocom.egg-info/top_level.txt
16
16
  tests/test_construct.py
17
17
  tests/test_gsup.py
18
- tests/test_tlv.py
18
+ tests/test_tlv.py
19
+ tests/test_utils.py
@@ -58,7 +58,6 @@ class Test_GSUP(unittest.TestCase):
58
58
  'desc': 'Purge MS Res',
59
59
  'encoded': h2b('0e010862424201495149f50700'),
60
60
  }, {
61
- 'desc': 'ePDG tunnel request',
62
61
  'desc': 'ePDG tunnel request',
63
62
  'encoded': h2b('50010862424201495149f5280101150780000d00000c000a0105'),
64
63
  }, {
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python3
2
+
3
+ # (C) 2022 by Harald Welte <laforge@osmocom.org>
4
+ # All Rights Reserved
5
+ #
6
+ # This program is free software: you can redistribute it and/or modify
7
+ # it under the terms of the GNU General Public License as published by
8
+ # the Free Software Foundation, either version 2 of the License, or
9
+ # (at your option) any later version.
10
+ #
11
+ # This program is distributed in the hope that it will be useful,
12
+ # but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14
+ # GNU General Public License for more details.
15
+ #
16
+ # You should have received a copy of the GNU General Public License
17
+ # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
+
19
+ import unittest
20
+
21
+ from osmocom.utils import *
22
+
23
+ class TestHexstr(unittest.TestCase):
24
+ def test_cmp(self):
25
+ s = hexstr('aBcD')
26
+ self.assertEqual(s, 'abcd')
27
+ self.assertEqual(s, 'ABCD')
28
+ self.assertEqual(s, 'AbCd')
29
+ self.assertEqual(s, hexstr('AbCd'))
30
+
31
+ def test_tobytes(self):
32
+ s = hexstr('aBcDeF')
33
+ self.assertEqual(s.to_bytes(), b'\xab\xcd\xef')
34
+
35
+ def test_tobytes_odd(self):
36
+ s2 = hexstr('aBc')
37
+ with self.assertRaises(ValueError):
38
+ s2.to_bytes()
39
+
40
+ def test_frombytes(self):
41
+ s = hexstr.from_bytes(b'\x01\x02\xaa')
42
+ self.assertEqual(s, '0102aa')
43
+
44
+ def test_slice(self):
45
+ s = hexstr('abcdef')
46
+ slice1 = s[-2:]
47
+ self.assertTrue(isinstance(slice1, hexstr))
48
+ self.assertEqual(slice1, 'ef')
49
+ slice2 = s[1]
50
+ self.assertTrue(isinstance(slice2, hexstr))
51
+ self.assertEqual(slice2, 'b')
52
+
53
+ def test_str_lower(self):
54
+ self.assertEqual(str(hexstr('ABCD')), 'abcd')
55
+
56
+
57
+ if __name__ == "__main__":
58
+ unittest.main()
File without changes
File without changes
File without changes
File without changes
File without changes