Skip to content

Commit 32a751d

Browse files
committed
revert IDE changes
try again clean up
1 parent 1048923 commit 32a751d

File tree

6 files changed

+65
-84
lines changed

6 files changed

+65
-84
lines changed

.gitignore

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,6 @@ test.py
2828
__pycache__
2929
.benchmarks
3030
.pytest_cache
31+
32+
# Build artifacts
33+
*.so

pyproject.toml

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,13 @@
22
name = "libipld"
33
dynamic = ["version"]
44
description = "Python binding to the Rust IPLD library"
5-
authors = [{ name = "Ilya (Marshal)", email = "ilya@marshal.dev" }]
5+
authors = [
6+
{name = "Ilya (Marshal)", email = "ilya@marshal.dev"}
7+
]
68
license = "MIT"
79
repository = "https://github.com/MarshalX/python-libipld"
810
readme = "README.md"
9-
keywords = [
10-
"library",
11-
"lib",
12-
"ipld",
13-
"cid",
14-
"multibase",
15-
"multihash",
16-
"dag",
17-
"cbor",
18-
"json",
19-
"pb",
20-
"dag-cbor",
21-
"dag-json",
22-
]
11+
keywords = ["library", "lib", "ipld", "cid", "multibase", "multihash", "dag", "cbor", "json", "pb", "dag-cbor", "dag-json"]
2312
requires-python = ">=3.8"
2413
classifiers = [
2514
"Development Status :: 5 - Production/Stable",
@@ -53,9 +42,8 @@ dev = ["maturin", "pytest", "pytest-benchmark"]
5342

5443
[tool.pytest.ini_options]
5544
addopts = [
56-
'--benchmark-columns',
57-
'min,mean,stddev,outliers,rounds,iterations',
58-
'--benchmark-disable', # use --benchmark-enable
45+
'--benchmark-columns', 'min,mean,stddev,outliers,rounds,iterations',
46+
'--benchmark-disable', # use --benchmark-enable
5947
]
6048

6149
[tool.maturin]

pytests/test_cid.py

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,31 @@
22

33

44
def test_cid_decode_multibase() -> None:
5-
cid = libipld.decode_cid(
6-
"bafyreig7jbijxpn4lfhvnvyuwf5u5jyhd7begxwyiqe7ingwxycjdqjjoa"
7-
)
8-
assert 1 == cid["version"]
9-
assert 113 == cid["codec"]
10-
assert 18 == cid["hash"]["code"]
11-
assert 32 == cid["hash"]["size"]
12-
assert cid["hash"]["size"] == len(cid["hash"]["digest"])
5+
cid = libipld.decode_cid('bafyreig7jbijxpn4lfhvnvyuwf5u5jyhd7begxwyiqe7ingwxycjdqjjoa')
6+
assert 1 == cid['version']
7+
assert 113 == cid['codec']
8+
assert 18 == cid['hash']['code']
9+
assert 32 == cid['hash']['size']
10+
assert cid['hash']['size'] == len(cid['hash']['digest'])
1311

1412

1513
def test_cid_decode_raw() -> None:
16-
cid = libipld.decode_cid(
17-
b"\x01q\x12 \xb6\x81\x1a\x1d\x7f\x8c\x17\x91\xdam\x1bO\x13m\xc0\xe2&y\xea\xfe\xaaX\xd6M~/\xaa\xd5\x89\x0e\x9d\x9c"
18-
)
19-
assert 1 == cid["version"]
20-
assert 113 == cid["codec"]
21-
assert 18 == cid["hash"]["code"]
22-
assert 32 == cid["hash"]["size"]
23-
assert cid["hash"]["size"] == len(cid["hash"]["digest"])
14+
cid = libipld.decode_cid(b'\x01q\x12 \xb6\x81\x1a\x1d\x7f\x8c\x17\x91\xdam\x1bO\x13m\xc0\xe2&y\xea\xfe\xaaX\xd6M~/\xaa\xd5\x89\x0e\x9d\x9c')
15+
assert 1 == cid['version']
16+
assert 113 == cid['codec']
17+
assert 18 == cid['hash']['code']
18+
assert 32 == cid['hash']['size']
19+
assert cid['hash']['size'] == len(cid['hash']['digest'])
2420

2521

2622
def test_cid_encode_multibase() -> None:
27-
cid = "bafyreig7jbijxpn4lfhvnvyuwf5u5jyhd7begxwyiqe7ingwxycjdqjjoa"
23+
cid = 'bafyreig7jbijxpn4lfhvnvyuwf5u5jyhd7begxwyiqe7ingwxycjdqjjoa'
2824
assert cid == libipld.encode_cid(cid) # because it's already encoded
2925

3026

3127
def test_cid_encode_raw() -> None:
32-
raw_cid = b"\x01q\x12 \xb6\x81\x1a\x1d\x7f\x8c\x17\x91\xdam\x1bO\x13m\xc0\xe2&y\xea\xfe\xaaX\xd6M~/\xaa\xd5\x89\x0e\x9d\x9c"
33-
expected_cid_multibase = (
34-
"bafyreifwqenb274mc6i5u3i3j4jw3qhcez46v7vkldle27rpvlkysdu5tq"
35-
)
28+
raw_cid = b'\x01q\x12 \xb6\x81\x1a\x1d\x7f\x8c\x17\x91\xdam\x1bO\x13m\xc0\xe2&y\xea\xfe\xaaX\xd6M~/\xaa\xd5\x89\x0e\x9d\x9c'
29+
expected_cid_multibase = 'bafyreifwqenb274mc6i5u3i3j4jw3qhcez46v7vkldle27rpvlkysdu5tq'
3630

3731
cid = libipld.decode_cid(raw_cid)
3832
cid_multibase = libipld.encode_cid(raw_cid)
@@ -44,4 +38,4 @@ def test_cid_encode_raw() -> None:
4438
assert cid == cid2
4539

4640
# manual encoding for CID v1:
47-
assert expected_cid_multibase == libipld.encode_multibase("b", raw_cid)
41+
assert expected_cid_multibase == libipld.encode_multibase('b', raw_cid)

pytests/test_decode_car.py

Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,24 @@
22

33
import libipld
44
import pytest
5-
from pytest_benchmark.fixture import BenchmarkFixture
65

76
from conftest import load_car_fixture
87

9-
_DID = os.environ.get(
10-
"CAR_REPO_DID", "did:plc:w4es6sfh43zlht3bgrzi5qzq"
11-
) # default is public bot in bsky.app
12-
_REPO_CAR_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "repo.car")
8+
_DID = os.environ.get('CAR_REPO_DID', 'did:plc:w4es6sfh43zlht3bgrzi5qzq') # default is public bot in bsky.app
9+
_REPO_CAR_PATH = os.path.join(os.path.dirname(__file__), '..', 'data', 'repo.car')
1310

1411

15-
@pytest.fixture(scope="session")
12+
@pytest.fixture(scope='session')
1613
def car() -> bytes:
1714
return load_car_fixture(_DID, _REPO_CAR_PATH)
1815

1916

20-
def test_decode_car(benchmark: BenchmarkFixture, car: bytes) -> None:
17+
def test_decode_car(benchmark, car) -> None:
2118
header, blocks = benchmark(libipld.decode_car, car)
2219

23-
assert 1 == header["version"]
24-
assert isinstance(header["roots"], list)
25-
assert 1 == len(header["roots"])
20+
assert 1 == header['version']
21+
assert isinstance(header['roots'], list)
22+
assert 1 == len(header['roots'])
2623

2724
assert isinstance(blocks, dict)
2825
assert all(isinstance(k, bytes) for k in blocks.keys())
@@ -33,71 +30,71 @@ def test_decode_car(benchmark: BenchmarkFixture, car: bytes) -> None:
3330

3431
def test_decode_car_invalid_header_len() -> None:
3532
with pytest.raises(ValueError) as exc_info:
36-
libipld.decode_car(b"")
33+
libipld.decode_car(b'')
3734

38-
assert "Invalid uvarint" in str(exc_info.value)
35+
assert 'Invalid uvarint' in str(exc_info.value)
3936

4037

4138
def test_decode_car_invalid_header_type() -> None:
4239
with pytest.raises(TypeError) as exc_info:
43-
header_len = bytes.fromhex("33") # 3
44-
header_obj = libipld.encode_dag_cbor("strInsteadOfObj")
40+
header_len = bytes.fromhex('33') # 3
41+
header_obj = libipld.encode_dag_cbor('strInsteadOfObj')
4542
libipld.decode_car(header_len + header_obj)
4643

4744
assert "cannot be converted to 'PyDict'" in str(exc_info.value)
4845

4946

5047
def test_decode_car_invalid_header_version_key() -> None:
5148
with pytest.raises(ValueError) as exc_info:
52-
header_len = bytes.fromhex("33") # 3
53-
header_obj = libipld.encode_dag_cbor({"blabla": "blabla"})
49+
header_len = bytes.fromhex('33') # 3
50+
header_obj = libipld.encode_dag_cbor({'blabla': 'blabla'})
5451
libipld.decode_car(header_len + header_obj)
5552

56-
assert "Version is None" in str(exc_info.value)
53+
assert 'Version is None' in str(exc_info.value)
5754

5855

5956
def test_decode_car_invalid_header_version_value() -> None:
6057
with pytest.raises(ValueError) as exc_info:
61-
header_len = bytes.fromhex("33") # 3
62-
header_obj = libipld.encode_dag_cbor({"version": 2})
58+
header_len = bytes.fromhex('33') # 3
59+
header_obj = libipld.encode_dag_cbor({'version': 2})
6360
libipld.decode_car(header_len + header_obj)
6461

65-
assert "Version must be 1" in str(exc_info.value)
62+
assert 'Version must be 1' in str(exc_info.value)
6663

6764

6865
def test_decode_car_invalid_header_roots_key() -> None:
6966
with pytest.raises(ValueError) as exc_info:
70-
header_len = bytes.fromhex("33") # 3
71-
header_obj = libipld.encode_dag_cbor({"version": 1})
67+
header_len = bytes.fromhex('33') # 3
68+
header_obj = libipld.encode_dag_cbor({'version': 1})
7269
libipld.decode_car(header_len + header_obj)
7370

74-
assert "Roots is None" in str(exc_info.value)
71+
assert 'Roots is None' in str(exc_info.value)
7572

7673

7774
def test_decode_car_invalid_header_roots_value_type() -> None:
7875
with pytest.raises(TypeError) as exc_info:
79-
header_len = bytes.fromhex("33") # 3
80-
header_obj = libipld.encode_dag_cbor({"version": 1, "roots": 123})
76+
header_len = bytes.fromhex('33') # 3
77+
header_obj = libipld.encode_dag_cbor({'version': 1, 'roots': 123})
8178
libipld.decode_car(header_len + header_obj)
8279

8380
assert "cannot be converted to 'PyList'" in str(exc_info.value)
8481

8582

8683
def test_decode_car_invalid_header_roots_value_empty_list() -> None:
8784
with pytest.raises(ValueError) as exc_info:
88-
header_len = bytes.fromhex("33") # 3
89-
header_obj = libipld.encode_dag_cbor({"version": 1, "roots": []})
85+
header_len = bytes.fromhex('33') # 3
86+
header_obj = libipld.encode_dag_cbor({'version': 1, 'roots': []})
9087
libipld.decode_car(header_len + header_obj)
9188

92-
assert "Roots is empty" in str(exc_info.value)
89+
assert 'Roots is empty' in str(exc_info.value)
9390

9491

9592
def test_decode_car_invalid_block_cid() -> None:
9693
with pytest.raises(ValueError) as exc_info:
97-
header_len = bytes.fromhex("33") # 3
98-
header_obj = libipld.encode_dag_cbor({"version": 1, "roots": ["blabla"]})
99-
block1 = bytes.fromhex("33") + b"invalidSid"
94+
header_len = bytes.fromhex('33') # 3
95+
header_obj = libipld.encode_dag_cbor({'version': 1, 'roots': ['blabla']})
96+
block1 = bytes.fromhex('33') + b'invalidSid'
10097

10198
libipld.decode_car(header_len + header_obj + block1)
10299

103-
assert "Failed to read CID of block" in str(exc_info.value)
100+
assert 'Failed to read CID of block' in str(exc_info.value)
-636 KB
Binary file not shown.

src/lib.rs

Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ fn cid_hash_to_pydict<'py>(py: Python<'py>, cid: &Cid) -> Bound<'py, PyDict> {
1717
dict_obj.set_item("code", hash.code()).unwrap();
1818
dict_obj.set_item("size", hash.size()).unwrap();
1919
dict_obj
20-
.set_item("digest", PyBytes::new(py, hash.digest()))
20+
.set_item("digest", PyBytes::new(py, &hash.digest()))
2121
.unwrap();
2222

2323
dict_obj
@@ -74,7 +74,7 @@ fn sort_map_keys(keys: &Bound<PyList>, len: usize) -> Vec<(PyBackedStr, usize)>
7474
if s1.len() != s2.len() {
7575
s1.len().cmp(&s2.len())
7676
} else {
77-
s1.cmp(s2)
77+
s1.cmp(&s2)
7878
}
7979
});
8080

@@ -212,7 +212,7 @@ fn decode_dag_cbor_to_pyobject<R: Read + Seek>(
212212
}
213213

214214
fn encode_dag_cbor_from_pyobject<'py, W: Write>(
215-
_py: Python<'py>,
215+
py: Python<'py>,
216216
obj: &Bound<'py, PyAny>,
217217
w: &mut W,
218218
) -> Result<()> {
@@ -259,7 +259,7 @@ fn encode_dag_cbor_from_pyobject<'py, W: Write>(
259259
encode::write_u64(w, MajorKind::Array, len as u64)?;
260260

261261
for i in 0..len {
262-
encode_dag_cbor_from_pyobject(_py, &l.get_item(i)?, w)?;
262+
encode_dag_cbor_from_pyobject(py, &l.get_item(i)?, w)?;
263263
}
264264

265265
Ok(())
@@ -275,7 +275,7 @@ fn encode_dag_cbor_from_pyobject<'py, W: Write>(
275275
encode::write_u64(w, MajorKind::TextString, key_buf.len() as u64)?;
276276
w.write_all(key_buf)?;
277277

278-
encode_dag_cbor_from_pyobject(_py, &values.get_item(i)?, w)?;
278+
encode_dag_cbor_from_pyobject(py, &values.get_item(i)?, w)?;
279279
}
280280

281281
Ok(())
@@ -293,7 +293,7 @@ fn encode_dag_cbor_from_pyobject<'py, W: Write>(
293293
} else if let Ok(b) = obj.downcast::<PyBytes>() {
294294
// FIXME (MarshalX): it's not efficient to try to parse it as CID
295295
let cid = Cid::try_from(b.as_bytes());
296-
if cid.is_ok() {
296+
if let Ok(_) = cid {
297297
let buf = b.as_bytes();
298298
let len = buf.len();
299299

@@ -345,7 +345,7 @@ fn read_u64_leb128<R: Read>(r: &mut R) -> Result<u64> {
345345

346346
loop {
347347
let mut buf = [0];
348-
if r.read_exact(&mut buf).is_err() {
348+
if let Err(_) = r.read_exact(&mut buf) {
349349
return Err(anyhow!("Unexpected EOF while reading ULEB128 number."));
350350
}
351351

@@ -390,7 +390,7 @@ fn read_cid_from_bytes<R: Read>(r: &mut R) -> CidResult<Cid> {
390390
pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(PyObject, Bound<'py, PyDict>)> {
391391
let buf = &mut BufReader::new(Cursor::new(data));
392392

393-
if read_u64_leb128(buf).is_err() {
393+
if let Err(_) = read_u64_leb128(buf) {
394394
return Err(get_err(
395395
"Failed to read CAR header",
396396
"Invalid uvarint".to_string(),
@@ -436,7 +436,7 @@ pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(PyObject, Boun
436436
let parsed_blocks = PyDict::new(py);
437437

438438
loop {
439-
if read_u64_leb128(buf).is_err() {
439+
if let Err(_) = read_u64_leb128(buf) {
440440
// FIXME (MarshalX): we are not raising an error here because of possible EOF
441441
break;
442442
}
@@ -485,7 +485,7 @@ pub fn decode_dag_cbor(py: Python, data: &[u8]) -> PyResult<PyObject> {
485485

486486
if let Some(py_err) = PyErr::take(py) {
487487
py_err.set_cause(py, Option::from(err));
488-
// in case something set global interpreter's error,
488+
// in case something set global interpreters error,
489489
// for example C FFI function, we should return it
490490
// the real case: RecursionError (set by Py_EnterRecursiveCall)
491491
Err(py_err)
@@ -507,10 +507,9 @@ pub fn encode_dag_cbor<'py>(
507507
if let Err(e) = buf.flush() {
508508
return Err(get_err("Failed to flush buffer", e.to_string()));
509509
}
510-
Ok(PyBytes::new(py, buf.get_ref()))
510+
Ok(PyBytes::new(py, &buf.get_ref()))
511511
}
512512

513-
#[allow(clippy::extra_unused_lifetimes)]
514513
fn get_cid_from_py_any<'py>(data: &Bound<PyAny>) -> PyResult<Cid> {
515514
let cid: CidResult<Cid>;
516515
if let Ok(s) = data.downcast::<PyString>() {

0 commit comments

Comments
 (0)