Skip to content

Commit be21caf

Browse files
committed
Address PR comments
1 parent f707749 commit be21caf

File tree

1 file changed

+9
-22
lines changed

1 file changed

+9
-22
lines changed

src/controller/python/chip/yaml/format_converter.py

+9-22
Original file line numberDiff line numberDiff line change
@@ -20,39 +20,26 @@
2020
from chip.tlv import uint, float32
2121
import enum
2222
from chip.yaml.errors import ValidationError
23-
from binascii import unhexlify
24-
import re
23+
import binascii
2524

2625

2726
def convert_yaml_octet_string_to_bytes(s: str) -> bytes:
2827
"""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-
3328
# 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:])
3931

4032
# Step 2: convert non-hex-prefixed to bytes
4133
# TODO(#23669): This does not properly support utf8 octet strings. We mimic
4234
# javascript codegen behavior. Behavior or javascript is:
4335
# * Octet string character >= u+0200 errors out.
4436
# * 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)
5643

5744

5845
def convert_name_value_pair_to_dict(arg_values):

0 commit comments

Comments
 (0)