Skip to content

Commit

Permalink
Avoid unsafe casts from float to unsigned int
Browse files Browse the repository at this point in the history
Fixes #9815
  • Loading branch information
QuLogic committed Jan 19, 2025
1 parent 70997ef commit fefab07
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
5 changes: 4 additions & 1 deletion xarray/coding/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,10 @@ def encode(self, variable: Variable, name: T_Name = None):
if fill_value is not None and has_unsigned:
pop_to(encoding, attrs, "_Unsigned")
# XXX: Is this actually needed? Doesn't the backend handle this?
data = duck_array_ops.astype(duck_array_ops.around(data), dtype)
signed_dtype = np.dtype(f"i{dtype.itemsize}")
data = duck_array_ops.view(
duck_array_ops.astype(duck_array_ops.around(data), signed_dtype), dtype
)
attrs["_FillValue"] = fill_value

return Variable(dims, data, attrs, encoding, fastpath=True)
Expand Down
10 changes: 10 additions & 0 deletions xarray/core/duck_array_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,16 @@ def astype(data, dtype, **kwargs):
return data.astype(dtype, **kwargs)


def view(data, *args, **kwargs):
if hasattr(data, "__array_namespace__"):
xp = get_array_namespace(data)
if xp == np:
# numpy currently doesn't have a view:
return data.view(*args, **kwargs)
return xp.view(data, *args, **kwargs)
return data.view(*args, **kwargs)


def asarray(data, xp=np, dtype=None):
converted = data if is_duck_array(data) else xp.asarray(data)

Expand Down

0 comments on commit fefab07

Please sign in to comment.