Skip to main content

ncnn_rust/
reader.rs

1use crate::{sys, Error, Result};
2use std::{io::Read, marker::PhantomData, rc::Rc};
3
4/// An owned, bounded binary reader for advanced native loading.
5pub struct DataReader {
6    raw: sys::ncnn_datareader_t,
7    _thread: PhantomData<Rc<()>>,
8}
9impl DataReader {
10    /// Copies the buffer into a native reader that outlives it and supports both
11    /// formatted scanning and raw reads, so parameter text and weight streams load
12    /// through the same handle.
13    pub fn from_bytes(data: &[u8]) -> Result<Self> {
14        let raw = unsafe { sys::ncnn_rs_reader_memory(data.as_ptr(), data.len()) };
15        if raw.is_null() {
16            return Err(Error::Native(-100));
17        }
18        Ok(Self {
19            raw,
20            _thread: PhantomData,
21        })
22    }
23    /// Reads the whole stream into an owned buffer.
24    pub fn from_reader(mut reader: impl Read) -> Result<Self> {
25        let mut data = Vec::new();
26        reader.read_to_end(&mut data)?;
27        Self::from_bytes(&data)
28    }
29    /// Opens a file as a native stdio reader.
30    ///
31    /// The reader owns the file handle and closes it on drop, so a stream that does not fit a Rust
32    /// buffer loads without an intermediate copy. The path must be valid UTF-8.
33    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
34        let path = path.as_ref();
35        let text = path
36            .to_str()
37            .ok_or_else(|| Error::invalid("The native reader needs a UTF-8 path"))?;
38        let path = std::ffi::CString::new(text)?;
39        let raw = unsafe { sys::ncnn_rs_reader_file(path.as_ptr()) };
40        if raw.is_null() {
41            return Err(Error::Native(-100));
42        }
43        Ok(Self {
44            raw,
45            _thread: PhantomData,
46        })
47    }
48    /// Borrows the native reader handle.
49    pub fn as_raw(&self) -> sys::ncnn_datareader_t {
50        self.raw
51    }
52}
53impl Drop for DataReader {
54    fn drop(&mut self) {
55        unsafe {
56            sys::ncnn_datareader_destroy(self.raw);
57        }
58    }
59}