Skip to content

Commit f1f19a9

Browse files
authored
Optimize CAR decoding by reducing allocations (#90)
1 parent b0a757b commit f1f19a9

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/lib.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::io::{self, Write};
1+
use std::io::{self, Cursor, Write};
22

33
use anyhow::{anyhow, Result};
44
use cbor4ii::core::{
@@ -499,7 +499,10 @@ pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(Py<PyAny>, Bou
499499
break;
500500
}
501501

502-
let cid_result = Cid::read_bytes(&mut buf.buf);
502+
let cid_bytes_before = buf.buf;
503+
let mut cursor = Cursor::new(cid_bytes_before);
504+
505+
let cid_result = Cid::read_bytes(&mut cursor);
503506
let Ok(cid) = cid_result else {
504507
return Err(get_err(
505508
"Failed to read CID of block",
@@ -514,6 +517,10 @@ pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(Py<PyAny>, Bou
514517
));
515518
}
516519

520+
let consumed = cursor.position() as usize;
521+
buf.advance(consumed);
522+
let cid_raw = &cid_bytes_before[..consumed];
523+
517524
let block_result = decode_dag_cbor_to_pyobject(py, buf, 0);
518525
let Ok(block) = block_result else {
519526
return Err(get_err(
@@ -522,8 +529,7 @@ pub fn decode_car<'py>(py: Python<'py>, data: &[u8]) -> PyResult<(Py<PyAny>, Bou
522529
));
523530
};
524531

525-
// FIXME(MarshalX): to_bytes allocates
526-
let key = PyBytes::new(py, &cid.to_bytes()).into_pyobject(py)?;
532+
let key = PyBytes::new(py, cid_raw).into_pyobject(py)?;
527533
parsed_blocks.set_item(key, block)?;
528534
}
529535

0 commit comments

Comments
 (0)