| 100 | |
| 101 | |
| 102 | class TupleEncoder(BaseEncoder): |
| 103 | encoders = None |
| 104 | |
| 105 | def __init__(self, **kwargs): |
| 106 | super().__init__(**kwargs) |
| 107 | |
| 108 | self.is_dynamic = any(getattr(e, "is_dynamic", False) for e in self.encoders) |
| 109 | |
| 110 | def validate(self): |
| 111 | super().validate() |
| 112 | |
| 113 | if self.encoders is None: |
| 114 | raise ValueError("`encoders` may not be none") |
| 115 | |
| 116 | def validate_value(self, value): |
| 117 | if not is_list_like(value): |
| 118 | self.invalidate_value( |
| 119 | value, |
| 120 | msg="must be list-like object such as array or tuple", |
| 121 | ) |
| 122 | |
| 123 | if len(value) != len(self.encoders): |
| 124 | self.invalidate_value( |
| 125 | value, |
| 126 | exc=ValueOutOfBounds, |
| 127 | msg="value has {} items when {} were expected".format( |
| 128 | len(value), |
| 129 | len(self.encoders), |
| 130 | ), |
| 131 | ) |
| 132 | |
| 133 | for item, encoder in zip(value, self.encoders): |
| 134 | try: |
| 135 | encoder.validate_value(item) |
| 136 | except AttributeError: |
| 137 | encoder(item) |
| 138 | |
| 139 | def encode(self, values): |
| 140 | self.validate_value(values) |
| 141 | |
| 142 | raw_head_chunks = [] |
| 143 | tail_chunks = [] |
| 144 | for value, encoder in zip(values, self.encoders): |
| 145 | if getattr(encoder, "is_dynamic", False): |
| 146 | raw_head_chunks.append(None) |
| 147 | tail_chunks.append(encoder(value)) |
| 148 | else: |
| 149 | raw_head_chunks.append(encoder(value)) |
| 150 | tail_chunks.append(b"") |
| 151 | |
| 152 | head_length = sum(32 if item is None else len(item) for item in raw_head_chunks) |
| 153 | tail_offsets = (0,) + tuple(accumulate(map(len, tail_chunks[:-1]))) |
| 154 | head_chunks = tuple( |
| 155 | encode_uint_256(head_length + offset) if chunk is None else chunk |
| 156 | for chunk, offset in zip(raw_head_chunks, tail_offsets) |
| 157 | ) |
| 158 | |
| 159 | encoded_value = b"".join(head_chunks + tuple(tail_chunks)) |
no outgoing calls
no test coverage detected
searching dependent graphs…