Skip to content

Commit 55edcd2

Browse files
authored
Fix smallest and largest CBOR integer roundtrip (#58)
1 parent 0da9f9b commit 55edcd2

2 files changed

Lines changed: 21 additions & 3 deletions

File tree

pytests/test_dag_cbor.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,6 +137,25 @@ def test_recursion_limit_exceed_on_nested_maps() -> None:
137137
assert 'in DAG-CBOR decoding' in str(exc_info.value)
138138

139139

140+
def test_dag_cbor_decode_largest_unsigned_int_roundtrip() -> None:
141+
data = bytes.fromhex('1bffffffffffffffff')
142+
143+
decoded_result = libipld.decode_dag_cbor(data)
144+
assert decoded_result == 2**64 - 1
145+
146+
encoded_result = libipld.encode_dag_cbor(decoded_result)
147+
assert encoded_result == data
148+
149+
150+
def test_dag_cbor_decode_smallest_negative_int_roundtrip() -> None:
151+
data = bytes.fromhex('3bffffffffffffffff')
152+
153+
decoded_result = libipld.decode_dag_cbor(data)
154+
assert decoded_result == -(2**64)
155+
156+
encoded_result = libipld.encode_dag_cbor(decoded_result)
157+
assert encoded_result == data
158+
140159

141160
def test_dag_cbor_decode_invalid_utf8() -> None:
142161
with pytest.raises(ValueError) as exc_info:
@@ -160,4 +179,3 @@ def test_dab_cbor_encode_map_int_key() -> None:
160179
libipld.encode_dag_cbor(obj)
161180

162181
assert 'Map keys must be strings' in str(exc_info.value)
163-

src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ fn decode_dag_cbor_to_pyobject<R: Read + Seek>(
130130
let major = decode::read_major(r)?;
131131
Ok(match major.kind() {
132132
MajorKind::UnsignedInt => decode::read_uint(r, major)?.into_pyobject(py)?.into(),
133-
MajorKind::NegativeInt => (-1 - decode::read_uint(r, major)? as i64).into_pyobject(py)?.into(),
133+
MajorKind::NegativeInt => (-1 - decode::read_uint(r, major)? as i128).into_pyobject(py)?.into(),
134134
MajorKind::ByteString => {
135135
let len = decode::read_uint(r, major)?;
136136
PyBytes::new(py, &decode::read_bytes(r, len)?).into_pyobject(py)?.into()
@@ -239,7 +239,7 @@ fn encode_dag_cbor_from_pyobject<'py, W: Write>(
239239

240240
Ok(())
241241
} else if obj.is_instance_of::<PyInt>() {
242-
let i: i64 = obj.extract()?;
242+
let i: i128 = obj.extract()?;
243243

244244
if i.is_negative() {
245245
encode::write_u64(w, MajorKind::NegativeInt, -(i + 1) as u64)?

0 commit comments

Comments
 (0)