cjc_runtime/buffer.rs
1//! COW (Copy-on-Write) buffer -- the fundamental memory primitive under [`Tensor`].
2//!
3//! [`Buffer<T>`] provides reference-counted storage with lazy deep-copy
4//! semantics. Cloning a buffer increments the refcount (O(1)); mutation
5//! via [`Buffer::set`] or [`Buffer::make_unique`] triggers a deep copy
6//! only when the buffer is shared (`refcount > 1`).
7//!
8//! # Determinism
9//!
10//! Buffer operations are fully deterministic. No randomized hashing,
11//! no platform-dependent allocation strategies. The COW mechanism
12//! ensures that mutation of shared data always produces a fresh,
13//! independent copy.
14//!
15//! [`Tensor`]: crate::tensor::Tensor
16
17use std::cell::{Ref, RefCell};
18use std::rc::Rc;
19
20use crate::error::RuntimeError;
21
22// ---------------------------------------------------------------------------
23// 1. Buffer<T> -- Deterministic memory allocation with COW semantics
24// ---------------------------------------------------------------------------
25
26/// A reference-counted buffer with copy-on-write semantics.
27///
28/// Internally backed by `Rc<RefCell<Vec<T>>>`. When multiple `Buffer`s share
29/// the same underlying storage, a mutation via [`Buffer::set`] or
30/// [`Buffer::make_unique`] triggers a deep copy so that other holders are
31/// unaffected.
32#[derive(Debug)]
33pub struct Buffer<T: Clone> {
34 inner: Rc<RefCell<Vec<T>>>,
35}
36
37impl<T: Clone> Buffer<T> {
38 /// Allocate a buffer of `len` elements, each initialized to `default`.
39 pub fn alloc(len: usize, default: T) -> Self {
40 Buffer {
41 inner: Rc::new(RefCell::new(vec![default; len])),
42 }
43 }
44
45 /// Create a buffer from an existing `Vec<T>`.
46 pub fn from_vec(data: Vec<T>) -> Self {
47 Buffer {
48 inner: Rc::new(RefCell::new(data)),
49 }
50 }
51
52 /// Number of elements in the buffer.
53 pub fn len(&self) -> usize {
54 self.inner.borrow().len()
55 }
56
57 /// Whether the buffer is empty.
58 pub fn is_empty(&self) -> bool {
59 self.inner.borrow().is_empty()
60 }
61
62 /// Read the value at `idx`. Returns `None` if out of bounds.
63 pub fn get(&self, idx: usize) -> Option<T> {
64 self.inner.borrow().get(idx).cloned()
65 }
66
67 /// Write `val` at `idx`. If the buffer is shared (refcount > 1), a deep
68 /// copy is performed first (COW). Returns `Err` if `idx` is out of bounds.
69 pub fn set(&mut self, idx: usize, val: T) -> Result<(), RuntimeError> {
70 self.make_unique();
71 let mut vec = self.inner.borrow_mut();
72 if idx >= vec.len() {
73 return Err(RuntimeError::IndexOutOfBounds {
74 index: idx,
75 length: vec.len(),
76 });
77 }
78 vec[idx] = val;
79 Ok(())
80 }
81
82 /// Return a snapshot of the data as a `Vec<T>`.
83 pub fn as_slice(&self) -> Vec<T> {
84 self.inner.borrow().clone()
85 }
86
87 /// Borrow the underlying Vec without cloning.
88 /// The returned `Ref` guard keeps the borrow alive.
89 pub fn borrow_data(&self) -> Ref<Vec<T>> {
90 self.inner.borrow()
91 }
92
93 /// Force a deep copy, returning a new `Buffer` that does not share
94 /// storage with `self`.
95 pub fn clone_buffer(&self) -> Buffer<T> {
96 Buffer {
97 inner: Rc::new(RefCell::new(self.inner.borrow().clone())),
98 }
99 }
100
101 /// Ensure this `Buffer` has exclusive ownership of the underlying data.
102 /// If the refcount is > 1, the data is deep-copied and this `Buffer` is
103 /// re-pointed to the fresh copy.
104 pub fn make_unique(&mut self) {
105 if Rc::strong_count(&self.inner) > 1 {
106 let data = self.inner.borrow().clone();
107 self.inner = Rc::new(RefCell::new(data));
108 }
109 }
110
111 /// Number of live references to the underlying storage.
112 pub fn refcount(&self) -> usize {
113 Rc::strong_count(&self.inner)
114 }
115}
116
117impl<T: Clone> Clone for Buffer<T> {
118 /// Cloning a `Buffer` increments the refcount — it does NOT copy data.
119 fn clone(&self) -> Self {
120 Buffer {
121 inner: Rc::clone(&self.inner),
122 }
123 }
124}
125