Skip to main content

xgrammar/support/
compact_2d_array.rs

1//! Compressed-sparse-row (CSR) 2D array.
2
3use serde::{Deserialize, Serialize};
4use serde_json::{Value, json};
5
6/// A 2D array stored in Compressed Sparse Row (CSR) format: every row may have a
7/// different length, and all rows live contiguously in one backing buffer.
8///
9/// Two parallel vectors back it:
10/// - `data` — all row elements, concatenated;
11/// - `indptr` — the start offset of each row in `data`; its last element equals
12///   `data.len()`, so row `i` occupies `data[indptr[i]..indptr[i + 1]]`.
13///
14/// Rows are immutable once inserted (you can still mutate their elements in place via
15/// [`Compact2dArray::row_mut`]). Provides
16/// `Row` views, this returns borrowed slices — the borrow checker enforces the
17/// "inserting a row invalidates outstanding rows" invariant for free.
18#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
19pub struct Compact2dArray<T> {
20    data: Vec<T>,
21    indptr: Vec<i32>,
22}
23
24impl<T> Default for Compact2dArray<T> {
25    fn default() -> Self {
26        Self {
27            data: Vec::new(),
28            indptr: vec![0],
29        }
30    }
31}
32
33/// Error returned when a CSR representation fails its invariants.
34#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
35pub enum Compact2dArrayError {
36    /// `indptr` was empty (it must contain at least the leading `0`).
37    #[error("compact 2d array indptr cannot be empty")]
38    EmptyIndptr,
39    /// `indptr` did not start with `0`.
40    #[error("compact 2d array indptr must start with 0")]
41    NonZeroStart,
42    /// `indptr` was not non-decreasing.
43    #[error("compact 2d array indptr must be non-decreasing")]
44    NotMonotonic,
45    /// The final `indptr` entry did not equal `data.len()`.
46    #[error("compact 2d array indptr must end with data.len()")]
47    BadEnd,
48}
49
50impl<T> Compact2dArray<T> {
51    /// Creates an empty array (zero rows).
52    #[must_use]
53    pub fn new() -> Self {
54        Self::default()
55    }
56
57    /// Builds an array directly from a CSR representation, validating the invariants.
58    ///
59    /// # Errors
60    /// Returns [`Compact2dArrayError`] if `indptr` is empty, does not start with `0`, is
61    /// not non-decreasing, or does not end at `data.len()`.
62    pub fn from_data_and_indptr(
63        data: Vec<T>,
64        indptr: Vec<i32>,
65    ) -> Result<Self, Compact2dArrayError> {
66        let Some(&first) = indptr.first() else {
67            return Err(Compact2dArrayError::EmptyIndptr);
68        };
69        if first != 0 {
70            return Err(Compact2dArrayError::NonZeroStart);
71        }
72        if indptr.windows(2).any(|w| w[0] > w[1]) {
73            return Err(Compact2dArrayError::NotMonotonic);
74        }
75        if *indptr.last().expect("indptr is non-empty here") as usize != data.len() {
76            return Err(Compact2dArrayError::BadEnd);
77        }
78        Ok(Self {
79            data,
80            indptr,
81        })
82    }
83
84    /// Number of rows.
85    #[must_use]
86    #[inline]
87    pub fn len(&self) -> usize {
88        self.indptr.len() - 1
89    }
90
91    /// Whether there are zero rows.
92    #[must_use]
93    pub fn is_empty(&self) -> bool {
94        self.len() == 0
95    }
96
97    /// Total number of elements across all rows.
98    #[must_use]
99    pub fn data_len(&self) -> usize {
100        self.data.len()
101    }
102
103    /// Returns row `i` as a slice, or `None` if out of bounds.
104    #[must_use]
105    #[inline]
106    pub fn get(
107        &self,
108        i: usize,
109    ) -> Option<&[T]> {
110        (i < self.len()).then(|| &self.data[self.row_range(i)])
111    }
112
113    /// The positions of row `i` within [`Self::data`]. They stay valid while rows are appended,
114    /// so a row can be walked by index while the array grows.
115    ///
116    /// # Panics
117    /// Panics if `i` is out of bounds.
118    #[inline]
119    #[must_use]
120    pub fn row_range(
121        &self,
122        i: usize,
123    ) -> std::ops::Range<usize> {
124        self.indptr[i] as usize..self.indptr[i + 1] as usize
125    }
126
127    /// Returns row `i` as a slice.
128    ///
129    /// # Panics
130    /// Panics if `i` is out of bounds (an internal invariant violation).
131    #[must_use]
132    #[inline]
133    pub fn row(
134        &self,
135        i: usize,
136    ) -> &[T] {
137        self.get(i).expect("row index out of bounds")
138    }
139
140    /// Returns row `i` as a mutable slice.
141    ///
142    /// # Panics
143    /// Panics if `i` is out of bounds.
144    pub fn row_mut(
145        &mut self,
146        i: usize,
147    ) -> &mut [T] {
148        assert!(i < self.len(), "row index out of bounds");
149        let start = self.indptr[i] as usize;
150        let end = self.indptr[i + 1] as usize;
151        &mut self.data[start..end]
152    }
153
154    /// Returns the last row.
155    ///
156    /// # Panics
157    /// Panics if there are no rows.
158    #[must_use]
159    #[inline]
160    pub fn back(&self) -> &[T] {
161        assert!(!self.is_empty(), "Compact2dArray is empty");
162        self.row(self.len() - 1)
163    }
164
165    /// Iterates over the rows as slices.
166    pub fn iter(&self) -> impl Iterator<Item = &[T]> {
167        (0..self.len()).map(move |i| self.row(i))
168    }
169
170    /// The flat backing data buffer.
171    #[must_use]
172    #[inline]
173    pub fn data(&self) -> &[T] {
174        &self.data
175    }
176
177    /// The row-offset (index pointer) buffer.
178    #[must_use]
179    pub fn indptr(&self) -> &[i32] {
180        &self.indptr
181    }
182
183    /// Removes the last `cnt` rows.
184    ///
185    /// # Panics
186    /// Panics if `cnt` exceeds the number of rows.
187    pub fn pop_back(
188        &mut self,
189        cnt: usize,
190    ) {
191        assert!(cnt <= self.len(), "cannot pop more rows than exist");
192        let new_len = self.indptr.len() - cnt;
193        self.indptr.truncate(new_len);
194        let new_data_len = *self.indptr.last().expect("indptr keeps its leading 0") as usize;
195        self.data.truncate(new_data_len);
196    }
197}
198
199impl<T: Clone> Compact2dArray<T> {
200    /// Builds an array from per-row sizes, with every element default-constructed.
201    #[must_use]
202    pub fn from_row_sizes(row_sizes: &[i32]) -> Self
203    where
204        T: Default,
205    {
206        let mut out = Self::new();
207        out.reset_with_row_sizes(row_sizes);
208        out
209    }
210
211    /// Resets the array to `row_sizes.len()` rows of default-constructed elements.
212    ///
213    /// # Panics
214    /// Panics if any row size is negative, or if the total size exceeds the `i32` limit.
215    pub fn reset_with_row_sizes(
216        &mut self,
217        row_sizes: &[i32],
218    ) where
219        T: Default,
220    {
221        self.indptr.clear();
222        self.indptr.reserve(row_sizes.len() + 1);
223        self.indptr.push(0);
224        let mut acc = 0i32;
225        for &size in row_sizes {
226            assert!(size >= 0, "Compact2dArray row size cannot be negative");
227            assert!(size <= i32::MAX - acc, "Compact2DArray data size exceeds the int32_t limit");
228            acc += size;
229            self.indptr.push(acc);
230        }
231        self.data.clear();
232        self.data.resize_with(acc as usize, T::default);
233    }
234
235    /// Appends a new row, returning its index.
236    ///
237    /// # Panics
238    /// Panics if the total size would exceed the `i32` limit.
239    pub fn push_row(
240        &mut self,
241        new_data: &[T],
242    ) -> usize {
243        self.check_can_append_data(new_data.len());
244        self.data.extend_from_slice(new_data);
245        self.indptr.push(self.data.len() as i32);
246        self.indptr.len() - 2
247    }
248
249    /// Appends a new row consisting of one leading element followed by `rest`.
250    ///
251    /// Mirrors the C++ `PushBackNonContiguous`, used by the grammar-expression encoding.
252    ///
253    /// # Panics
254    /// Panics if the total size would exceed the `i32` limit.
255    pub fn push_row_noncontiguous(
256        &mut self,
257        first: T,
258        rest: &[T],
259    ) -> usize {
260        self.check_can_append_data(rest.len() + 1);
261        self.data.push(first);
262        self.data.extend_from_slice(rest);
263        self.indptr.push(self.data.len() as i32);
264        self.indptr.len() - 2
265    }
266}
267
268impl<T> Compact2dArray<T> {
269    /// Appends one element to the most recently inserted row.
270    ///
271    /// # Panics
272    /// Panics if the array has no rows yet, or if the total size would exceed the `i32` limit.
273    pub fn push_in_latest_row(
274        &mut self,
275        new_data: T,
276    ) {
277        assert!(!self.is_empty(), "cannot push into an empty Compact2dArray");
278        self.check_can_append_data(1);
279        self.data.push(new_data);
280        *self.indptr.last_mut().expect("non-empty") += 1;
281    }
282
283    /// Guards the `i32` row offsets before appending `additional` elements, so a pathological
284    /// grammar fails loudly instead of wrapping the offsets.
285    fn check_can_append_data(
286        &self,
287        additional: usize,
288    ) {
289        assert!(
290            additional <= i32::MAX as usize - self.data.len(),
291            "Compact2DArray data size would exceed the int32_t limit, likely due to an unbounded grammar pattern \
292             causing state explosion"
293        );
294    }
295}
296
297impl Compact2dArray<i32> {
298    /// Serializes in the C++ reflection form `{"data_":[...],"indptr_":[...]}`.
299    #[must_use]
300    pub fn serialize_json_value(&self) -> Value {
301        json!({
302            "data_": self.data,
303            "indptr_": self.indptr,
304        })
305    }
306
307    /// Deserializes the C++ reflection form.
308    ///
309    /// # Errors
310    /// Returns an error string when the JSON shape is invalid.
311    pub fn deserialize_json_value(value: &Value) -> Result<Self, String> {
312        let obj = value.as_object().ok_or_else(|| "compact 2d array expects a JSON object".to_owned())?;
313        let data = obj
314            .get("data_")
315            .and_then(Value::as_array)
316            .ok_or_else(|| "missing compact 2d array data_".to_owned())?
317            .iter()
318            .map(|v| v.as_i64().map(|n| n as i32).ok_or_else(|| "data_ elements must be integers".to_owned()))
319            .collect::<Result<Vec<_>, _>>()?;
320        let indptr = obj
321            .get("indptr_")
322            .and_then(Value::as_array)
323            .ok_or_else(|| "missing compact 2d array indptr_".to_owned())?
324            .iter()
325            .map(|v| v.as_i64().map(|n| n as i32).ok_or_else(|| "indptr_ elements must be integers".to_owned()))
326            .collect::<Result<Vec<_>, _>>()?;
327        Self::from_data_and_indptr(data, indptr).map_err(|e| e.to_string())
328    }
329}