(
cls, value: int | float | complex | str | bytes, dtype: np.dtype[Any]
)
| 123 | |
| 124 | @classmethod |
| 125 | def encode( |
| 126 | cls, value: int | float | complex | str | bytes, dtype: np.dtype[Any] |
| 127 | ) -> Any: |
| 128 | if dtype.kind == "S": |
| 129 | # byte string, this implies that 'value' must also be `bytes` dtype. |
| 130 | if not isinstance(value, bytes): |
| 131 | raise TypeError( |
| 132 | f"Failed to encode fill_value: expected bytes for dtype {dtype}, got {type(value).__name__}" |
| 133 | ) |
| 134 | return base64.standard_b64encode(value).decode() |
| 135 | elif dtype.kind == "b": |
| 136 | # boolean |
| 137 | return bool(value) |
| 138 | elif dtype.kind in "iu": |
| 139 | if not isinstance(value, int | float | np.integer | np.floating): |
| 140 | raise TypeError( |
| 141 | f"Failed to encode fill_value: expected int or float for dtype {dtype}, got {type(value).__name__}" |
| 142 | ) |
| 143 | return int(value) |
| 144 | elif dtype.kind == "f": |
| 145 | if not isinstance(value, int | float | np.integer | np.floating): |
| 146 | raise TypeError( |
| 147 | f"Failed to encode fill_value: expected int or float for dtype {dtype}, got {type(value).__name__}" |
| 148 | ) |
| 149 | return base64.standard_b64encode(struct.pack("<d", float(value))).decode() |
| 150 | elif dtype.kind == "c": |
| 151 | # complex - encode each component as base64, matching float encoding |
| 152 | if not isinstance(value, complex) and not np.issubdtype( |
| 153 | type(value), np.complexfloating |
| 154 | ): |
| 155 | raise TypeError( |
| 156 | f"Failed to encode fill_value: expected complex for dtype {dtype}, got {type(value).__name__}" |
| 157 | ) |
| 158 | return [ |
| 159 | base64.standard_b64encode( |
| 160 | struct.pack("<d", float(value.real)) # type: ignore[union-attr] |
| 161 | ).decode(), |
| 162 | base64.standard_b64encode( |
| 163 | struct.pack("<d", float(value.imag)) # type: ignore[union-attr] |
| 164 | ).decode(), |
| 165 | ] |
| 166 | elif dtype.kind == "U": |
| 167 | return str(value) |
| 168 | else: |
| 169 | raise ValueError(f"Failed to encode fill_value. Unsupported dtype {dtype}") |
| 170 | |
| 171 | @classmethod |
| 172 | def decode( |
no test coverage detected