Skip to main content

ncnn_rust/
alloc.rs

1//! CPU-side allocators.
2
3use crate::{sys, Error, Result};
4use std::{marker::PhantomData, rc::Rc};
5
6/// Owns a native pool allocator and releases it after its allocations.
7///
8/// A pool serves the intermediate blobs, workspace or attention KV cache that a network or an
9/// extractor allocates. [`Options`](crate::Options) and the per-extractor setters store the native
10/// handle without taking ownership, so the pool must outlive every network and extractor configured
11/// from it and must not be shared with one that runs concurrently. The type is thread-affine, like
12/// the objects that use it.
13///
14/// ```
15/// let mut pool = ncnn_rust::alloc::Pool::new()?;
16/// pool.configure(0.5, 1024 * 1024)?;
17/// let mut options = ncnn_rust::Options::new()?;
18/// // SAFETY: `pool` outlives these options and every network configured from them.
19/// unsafe { options.set_blob_allocator(&pool)? };
20/// let net = ncnn_rust::NetBuilder::with_options(options).load_bytes(
21///     "7767517\n2 2\nInput input 0 1 input\nReLU relu 1 1 input output\n",
22///     &[],
23/// )?;
24/// assert_eq!(
25///     net.infer([("input", ncnn_rust::Mat::from_f32(&[-1.0, 2.0], &[2])?)], &["output"])?[0].values,
26///     [0.0, 2.0]
27/// );
28/// # Ok::<(), ncnn_rust::Error>(())
29/// ```
30pub struct Pool {
31    raw: sys::ncnn_allocator_t,
32    _thread: PhantomData<Rc<()>>,
33}
34
35impl Pool {
36    /// Creates a pool allocator with native defaults.
37    pub fn new() -> Result<Self> {
38        let raw = unsafe { sys::ncnn_allocator_create_pool_allocator() };
39        if raw.is_null() {
40            return Err(Error::Native(-100));
41        }
42        Ok(Self {
43            raw,
44            _thread: PhantomData,
45        })
46    }
47    /// Sets the native reuse ratio and size threshold.
48    pub fn configure(&mut self, ratio: f32, threshold: usize) -> Result<()> {
49        unsafe { crate::error::status(sys::ncnn_rs_pool_configure(self.raw, 0, ratio, threshold)) }
50    }
51    /// Releases every cached block that has no outstanding allocation.
52    pub fn clear(&mut self) {
53        unsafe {
54            sys::ncnn_rs_pool_clear(self.raw, 0);
55        }
56    }
57    /// Borrows the allocator for advanced FFI allocation paths.
58    pub fn as_raw(&self) -> sys::ncnn_allocator_t {
59        self.raw
60    }
61}
62
63impl Drop for Pool {
64    fn drop(&mut self) {
65        unsafe {
66            sys::ncnn_allocator_destroy(self.raw);
67        }
68    }
69}