Skip to content

Commit 2dfa498

Browse files
authored
Bug: Take signed bit into account (#677)
```python >>> (32768).bit_length() 16 ``` From https://docs.python.org/3/library/stdtypes.html#int.bit_length > Return the number of bits necessary to represent an integer in binary, excluding the sign and leading zeros Fixes #669
1 parent 88a26e1 commit 2dfa498

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

pyiceberg/utils/decimal.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,9 +59,9 @@ def bytes_required(value: Union[int, Decimal]) -> int:
5959
int: the minimum number of bytes needed to serialize the value.
6060
"""
6161
if isinstance(value, int):
62-
return (value.bit_length() + 7) // 8
62+
return (value.bit_length() + 8) // 8
6363
elif isinstance(value, Decimal):
64-
return (decimal_to_unscaled(value).bit_length() + 7) // 8
64+
return (decimal_to_unscaled(value).bit_length() + 8) // 8
6565

6666
raise ValueError(f"Unsupported value: {value}")
6767

tests/utils/test_decimal.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@
1414
# KIND, either express or implied. See the License for the
1515
# specific language governing permissions and limitations
1616
# under the License.
17+
from decimal import Decimal
18+
1719
import pytest
1820

19-
from pyiceberg.utils.decimal import decimal_required_bytes
21+
from pyiceberg.utils.decimal import decimal_required_bytes, decimal_to_bytes
2022

2123

2224
def test_decimal_required_bytes() -> None:
@@ -38,3 +40,10 @@ def test_decimal_required_bytes() -> None:
3840
with pytest.raises(ValueError) as exc_info:
3941
decimal_required_bytes(precision=-1)
4042
assert "(0, 40]" in str(exc_info.value)
43+
44+
45+
def test_decimal_to_bytes() -> None:
46+
# Check the boundary between 2 and 3 bytes.
47+
# 2 bytes has a minimum of -32,768 and a maximum value of 32,767 (inclusive).
48+
assert decimal_to_bytes(Decimal('32767.')) == b'\x7f\xff'
49+
assert decimal_to_bytes(Decimal('32768.')) == b'\x00\x80\x00'

0 commit comments

Comments
 (0)