|
20 | 20 | from chip.tlv import uint, float32
|
21 | 21 | import enum
|
22 | 22 | from chip.yaml.errors import ValidationError
|
23 |
| -from binascii import unhexlify |
24 |
| -import re |
| 23 | +import binascii |
25 | 24 |
|
26 | 25 |
|
27 | 26 | def convert_yaml_octet_string_to_bytes(s: str) -> bytes:
|
28 | 27 | """Convert YAML octet string body to bytes, handling any c-style hex escapes (e.g. \x5a) and hex: prefix"""
|
29 |
| - is_hex_string_re = r"^hex:(?P<hex_content>[A-Fa-f0-9]*)$" |
30 |
| - |
31 |
| - hex_prefixed_match = re.match(is_hex_string_re, s) |
32 |
| - |
33 | 28 | # Step 1: handle explicit "hex:" prefix
|
34 |
| - if hex_prefixed_match: |
35 |
| - hex_content = hex_prefixed_match.group("hex_content") |
36 |
| - if (len(hex_content) % 2) != 0: |
37 |
| - raise ValueError("Hex literal is not even length!") |
38 |
| - return unhexlify(hex_content) |
| 29 | + if s.startswith('hex:'): |
| 30 | + return binascii.unhexlify(s[4:]) |
39 | 31 |
|
40 | 32 | # Step 2: convert non-hex-prefixed to bytes
|
41 | 33 | # TODO(#23669): This does not properly support utf8 octet strings. We mimic
|
42 | 34 | # javascript codegen behavior. Behavior or javascript is:
|
43 | 35 | # * Octet string character >= u+0200 errors out.
|
44 | 36 | # * Any character greater than 0xFF has the upper bytes chopped off.
|
45 |
| - known_javascript_max_char_value = 0x200 |
46 |
| - accumulated_hex = "" |
47 |
| - for char in s: |
48 |
| - char_value = ord(char) |
49 |
| - if char_value >= known_javascript_max_char_value: |
50 |
| - # If you got here see TODO #23669 mentioned above. |
51 |
| - raise ValueError("Unsupport char in octet string") |
52 |
| - char_value_lsb = char_value & 0xFF |
53 |
| - hex_with_leading_0x = '{0:02x}'.format(char_value_lsb) |
54 |
| - accumulated_hex += hex_with_leading_0x |
55 |
| - return unhexlify(accumulated_hex) |
| 37 | + as_bytes = [ord(c) for c in s] |
| 38 | + |
| 39 | + if any([value > 0x200 for value in as_bytes]): |
| 40 | + raise ValueError('Unsupported char in octet string %r' % as_bytes) |
| 41 | + accumulated_hex = ''.join([f"{(v & 0xFF):02x}" for v in as_bytes]) |
| 42 | + return binascii.unhexlify(accumulated_hex) |
56 | 43 |
|
57 | 44 |
|
58 | 45 | def convert_name_value_pair_to_dict(arg_values):
|
|
0 commit comments