Skip to content

Commit 42842b0

Browse files
committed
Use Rust's BufWriter
Rust's BufWriter is highly optimized. Use it instead of a custom one. Wrap it in a newtype so that we can implement `cbor4ii`s `enc::Write`.
1 parent d8be9fa commit 42842b0

1 file changed

Lines changed: 32 additions & 2 deletions

File tree

src/lib.rs

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1+
use std::io::{self, Write};
2+
13
use anyhow::{anyhow, Result};
24
use cbor4ii::core::{
35
dec::{self, Decode, Read},
46
enc::{self, Encode},
57
major, types,
6-
utils::BufWriter,
78
};
89
use cid::{multibase, Cid};
910
use pyo3::pybacked::PyBackedStr;
@@ -18,6 +19,32 @@ mod marker {
1819
pub const F64: u8 = 0xfb;
1920
}
2021

22+
struct BufWriter<W: io::Write>(io::BufWriter<W>);
23+
24+
impl<W: Write> BufWriter<W> {
25+
pub fn new(inner: W) -> Self {
26+
BufWriter(io::BufWriter::new(inner))
27+
}
28+
29+
pub fn flush(&mut self) -> io::Result<()> {
30+
self.0.flush()
31+
}
32+
33+
pub fn get_ref(&self) -> &W {
34+
self.0.get_ref()
35+
}
36+
}
37+
38+
impl<W: Write> enc::Write for BufWriter<W> {
39+
type Error = io::Error;
40+
41+
#[inline]
42+
fn push(&mut self, input: &[u8]) -> Result<(), Self::Error> {
43+
self.0.write_all(input)?;
44+
Ok(())
45+
}
46+
}
47+
2148
// Based on cbor4ii/src/utils.rs.
2249
/// An in-memory reader.
2350
struct SliceReader<'a> {
@@ -557,7 +584,10 @@ pub fn encode_dag_cbor<'py>(
557584
if let Err(e) = encode_dag_cbor_from_pyobject(py, data, &mut buf) {
558585
return Err(get_err("Failed to encode DAG-CBOR", e.to_string()));
559586
}
560-
Ok(PyBytes::new(py, buf.buffer()))
587+
if let Err(e) = buf.flush() {
588+
return Err(get_err("Failed to flush buffer", e.to_string()));
589+
}
590+
Ok(PyBytes::new(py, buf.get_ref()))
561591
}
562592

563593
fn get_cid_from_py_any(data: &Bound<PyAny>) -> PyResult<Cid> {

0 commit comments

Comments
 (0)