• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 The Pigweed Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License"); you may not
4# use this file except in compliance with the License. You may obtain a copy of
5# the License at
6#
7#     https://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12# License for the specific language governing permissions and limitations under
13# the License.
14"""Provides functionality for encoding tokenized messages."""
15
16import argparse
17import base64
18import struct
19import sys
20from typing import Sequence
21
22from pw_tokenizer import tokens
23
24_INT32_MAX = 2**31 - 1
25_UINT32_MAX = 2**32 - 1
26NESTED_TOKEN_PREFIX = '$'
27NESTED_TOKEN_BASE_PREFIX = '#'
28
29
30def _zig_zag_encode(value: int) -> int:
31    """Encodes signed integers to give a compact varint encoding."""
32    return value << 1 if value >= 0 else (value << 1) ^ (~0)
33
34
35def _little_endian_base128_encode(integer: int) -> bytearray:
36    data = bytearray()
37
38    while True:
39        # Grab 7 bits; the eighth bit is set to 1 to indicate more data coming.
40        data.append((integer & 0x7F) | 0x80)
41        integer >>= 7
42
43        if not integer:
44            break
45
46    data[-1] &= 0x7F  # clear the top bit of the last byte
47    return data
48
49
50def _encode_int32(arg: int) -> bytearray:
51    # Convert large unsigned numbers into their corresponding signed values.
52    if arg > _INT32_MAX:
53        arg -= 2**32
54
55    return _little_endian_base128_encode(_zig_zag_encode(arg))
56
57
58def _encode_string(arg: bytes) -> bytes:
59    size_byte = len(arg) if len(arg) < 128 else 0xFF
60    return struct.pack('B', size_byte) + arg[:127]
61
62
63def encode_args(*args: int | float | bytes | str) -> bytes:
64    """Encodes a list of arguments to their on-wire representation."""
65
66    data = bytearray(b'')
67    for arg in args:
68        if isinstance(arg, int):
69            if arg.bit_length() > 32:
70                raise ValueError(
71                    f'Cannot encode {arg}: only 32-bit integers may be encoded'
72                )
73            data += _encode_int32(arg)
74        elif isinstance(arg, float):
75            data += struct.pack('<f', arg)
76        elif isinstance(arg, str):
77            data += _encode_string(arg.encode())
78        elif isinstance(arg, bytes):
79            data += _encode_string(arg)
80        else:
81            raise ValueError(
82                f'{arg} has type {type(arg)}, which is not supported'
83            )
84    return bytes(data)
85
86
87def encode_token_and_args(
88    token: int, *args: int | float | bytes | str
89) -> bytes:
90    """Encodes a tokenized message given its token and arguments.
91
92    This function assumes that the token represents a format string with
93    conversion specifiers that correspond with the provided argument types.
94    Currently, only 32-bit integers are supported.
95    """
96
97    if token < 0 or token > _UINT32_MAX:
98        raise ValueError(
99            f'The token ({token}) must be an unsigned 32-bit integer'
100        )
101
102    return struct.pack('<I', token) + encode_args(*args)
103
104
105def prefixed_base64(data: bytes, prefix: str = '$') -> str:
106    """Encodes a tokenized message as prefixed Base64."""
107    return prefix + base64.b64encode(data).decode()
108
109
110def _parse_user_input(string: str):
111    """Evaluates a string as Python code or returns it as a literal string."""
112    try:
113        value = eval(string, dict(__builtins__={}))  # pylint: disable=eval-used
114    except (NameError, SyntaxError):
115        return string
116
117    return value if isinstance(value, (int, float)) else string
118
119
120def _main(format_string_list: Sequence[str], raw_args: Sequence[str]) -> int:
121    (format_string,) = format_string_list
122    token = tokens.pw_tokenizer_65599_hash(format_string)
123    args = tuple(_parse_user_input(a) for a in raw_args)
124
125    data = encode_token_and_args(token, *args)
126    token = int.from_bytes(data[:4], 'little')
127    binary = ' '.join(f'{b:02x}' for b in data)
128
129    print(f'      Raw input: {format_string!r} % {args!r}')
130    print(f'Formatted input: {format_string % args}')
131    print(f'          Token: 0x{token:08x}')
132    print(f'        Encoded: {data!r} ({binary}) [{len(data)} bytes]')
133    print(f'Prefixed Base64: {prefixed_base64(data)}')
134
135    return 0
136
137
138def _parse_args() -> dict:
139    parser = argparse.ArgumentParser(
140        description=__doc__,
141        formatter_class=argparse.RawDescriptionHelpFormatter,
142    )
143    parser.add_argument(
144        'format_string_list',
145        metavar='FORMAT_STRING',
146        nargs=1,
147        help='Format string with optional %%-style arguments.',
148    )
149    parser.add_argument(
150        'raw_args',
151        metavar='ARG',
152        nargs='*',
153        help=(
154            'Arguments for the format string, if any. Arguments are parsed '
155            'as Python expressions, with no builtins (e.g. 9 is the number '
156            '9 and \'"9"\' is the string "9"). Arguments that are not valid '
157            'Python are treated as string literals.'
158        ),
159    )
160    return vars(parser.parse_args())
161
162
163if __name__ == '__main__':
164    sys.exit(_main(**_parse_args()))
165