|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Generator |
| 3 | + |
| 4 | +from starknet_py.cairo.felt import decode_shortstring, encode_shortstring |
| 5 | +from starknet_py.serialization._context import ( |
| 6 | + DeserializationContext, |
| 7 | + SerializationContext, |
| 8 | +) |
| 9 | +from starknet_py.serialization.data_serializers._common import ( |
| 10 | + deserialize_to_list, |
| 11 | + serialize_from_list, |
| 12 | +) |
| 13 | +from starknet_py.serialization.data_serializers.cairo_data_serializer import ( |
| 14 | + CairoDataSerializer, |
| 15 | +) |
| 16 | +from starknet_py.serialization.data_serializers.felt_serializer import FeltSerializer |
| 17 | + |
| 18 | +BYTES_31_SIZE = 31 |
| 19 | + |
| 20 | + |
| 21 | +@dataclass |
| 22 | +class ByteArraySerializer(CairoDataSerializer[str, str]): |
| 23 | + """ |
| 24 | + Serializer for ByteArrays. Serializes to and deserializes from str values. |
| 25 | +
|
| 26 | + Examples: |
| 27 | + "" => [0,0,0] |
| 28 | + "hello" => [0,448378203247,5] |
| 29 | + """ |
| 30 | + |
| 31 | + def deserialize_with_context(self, context: DeserializationContext) -> str: |
| 32 | + with context.push_entity("data_array_len"): |
| 33 | + [size] = context.reader.read(1) |
| 34 | + |
| 35 | + data = deserialize_to_list([FeltSerializer()] * size, context) |
| 36 | + |
| 37 | + with context.push_entity("pending_word"): |
| 38 | + [pending_word] = context.reader.read(1) |
| 39 | + |
| 40 | + with context.push_entity("pending_word_len"): |
| 41 | + [pending_word_len] = context.reader.read(1) |
| 42 | + |
| 43 | + pending_word = decode_shortstring(pending_word) |
| 44 | + context.ensure_valid_value( |
| 45 | + len(pending_word) == pending_word_len, |
| 46 | + f"Invalid length {pending_word_len} for pending word {pending_word}", |
| 47 | + ) |
| 48 | + |
| 49 | + data_joined = "".join(map(decode_shortstring, data)) |
| 50 | + return data_joined + pending_word |
| 51 | + |
| 52 | + def serialize_with_context( |
| 53 | + self, context: SerializationContext, value: str |
| 54 | + ) -> Generator[int, None, None]: |
| 55 | + context.ensure_valid_type(value, isinstance(value, str), "str") |
| 56 | + data = [ |
| 57 | + value[i : i + BYTES_31_SIZE] for i in range(0, len(value), BYTES_31_SIZE) |
| 58 | + ] |
| 59 | + pending_word = ( |
| 60 | + "" if len(data) == 0 or len(data[-1]) == BYTES_31_SIZE else data.pop(-1) |
| 61 | + ) |
| 62 | + |
| 63 | + yield len(data) |
| 64 | + yield from serialize_from_list([FeltSerializer()] * len(data), context, data) |
| 65 | + yield encode_shortstring(pending_word) |
| 66 | + yield len(pending_word) |
0 commit comments