Skip to content

Commit fefab07

Browse files
committed
Avoid unsafe casts from float to unsigned int
Fixes #9815
1 parent 70997ef commit fefab07

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

xarray/coding/variables.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,10 @@ def encode(self, variable: Variable, name: T_Name = None):
426426
if fill_value is not None and has_unsigned:
427427
pop_to(encoding, attrs, "_Unsigned")
428428
# XXX: Is this actually needed? Doesn't the backend handle this?
429-
data = duck_array_ops.astype(duck_array_ops.around(data), dtype)
429+
signed_dtype = np.dtype(f"i{dtype.itemsize}")
430+
data = duck_array_ops.view(
431+
duck_array_ops.astype(duck_array_ops.around(data), signed_dtype), dtype
432+
)
430433
attrs["_FillValue"] = fill_value
431434

432435
return Variable(dims, data, attrs, encoding, fastpath=True)

xarray/core/duck_array_ops.py

+10
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,16 @@ def astype(data, dtype, **kwargs):
236236
return data.astype(dtype, **kwargs)
237237

238238

239+
def view(data, *args, **kwargs):
240+
if hasattr(data, "__array_namespace__"):
241+
xp = get_array_namespace(data)
242+
if xp == np:
243+
# numpy currently doesn't have a view:
244+
return data.view(*args, **kwargs)
245+
return xp.view(data, *args, **kwargs)
246+
return data.view(*args, **kwargs)
247+
248+
239249
def asarray(data, xp=np, dtype=None):
240250
converted = data if is_duck_array(data) else xp.asarray(data)
241251

0 commit comments

Comments
 (0)