Skip to main content

rhwp_codec_resource/
lib.rs

1//! Fallible codec storage and work checks. No process-global allocator changes.
2#![cfg_attr(not(feature = "scoped"), no_std)]
3#![forbid(unsafe_code)]
4
5extern crate alloc;
6use alloc::vec::Vec;
7use core::fmt;
8
9pub mod atomic;
10
11/// The requesting importer owns counters, limits, cancellation, and sticky errors.
12pub trait ResourceBudget: Send + Sync {
13    fn allocation_limit(&self) -> usize;
14    fn reserve(&self, bytes: usize) -> bool;
15    fn work(&self, units: usize) -> bool;
16    fn reject(&self);
17}
18
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct ResourceError;
21
22impl fmt::Display for ResourceError {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.write_str("codec resource limit or allocation failure")
25    }
26}
27
28#[cfg(feature = "scoped")]
29impl std::error::Error for ResourceError {}
30
31#[cfg(feature = "scoped")]
32mod scoped {
33    use super::ResourceBudget;
34    use alloc::rc::Rc;
35    use alloc::sync::Arc;
36    use core::marker::PhantomData;
37    use std::cell::RefCell;
38
39    std::thread_local! {
40        pub(super) static ACTIVE: RefCell<Option<Arc<dyn ResourceBudget>>> = const { RefCell::new(None) };
41    }
42
43    /// Restores the prior synchronous scope. Not Send/Sync: restoration is local.
44    pub struct Scope {
45        previous: Option<Arc<dyn ResourceBudget>>,
46        _thread: PhantomData<Rc<()>>,
47    }
48
49    impl Scope {
50        pub fn enter(budget: Arc<dyn ResourceBudget>) -> Self {
51            Self {
52                previous: ACTIVE.with(|slot| slot.replace(Some(budget))),
53                _thread: PhantomData,
54            }
55        }
56    }
57
58    impl Drop for Scope {
59        fn drop(&mut self) {
60            ACTIVE.with(|slot| *slot.borrow_mut() = self.previous.take());
61        }
62    }
63}
64
65#[cfg(feature = "scoped")]
66pub use scoped::Scope;
67
68fn with_budget<T>(f: impl FnOnce(Option<&dyn ResourceBudget>) -> T) -> T {
69    #[cfg(feature = "scoped")]
70    {
71        scoped::ACTIVE.with(|slot| f(slot.borrow().as_deref()))
72    }
73    #[cfg(not(feature = "scoped"))]
74    {
75        f(None)
76    }
77}
78
79pub fn reject() -> ResourceError {
80    with_budget(|budget| {
81        if let Some(budget) = budget {
82            budget.reject();
83        }
84    });
85    ResourceError
86}
87
88/// Charge before the corresponding repeated work. Zero checks cancellation too.
89pub fn work(units: usize) -> Result<(), ResourceError> {
90    with_budget(|budget| match budget {
91        Some(budget) if !budget.work(units) => Err(ResourceError),
92        _ => Ok(()),
93    })
94}
95
96pub fn product(factors: &[usize]) -> Result<usize, ResourceError> {
97    factors
98        .iter()
99        .try_fold(1usize, |n, &v| n.checked_mul(v).ok_or_else(reject))
100}
101
102pub fn reserve<T>(out: &mut Vec<T>, additional: usize) -> Result<(), ResourceError> {
103    work(0)?;
104    let needed = out.len().checked_add(additional).ok_or_else(reject)?;
105    if needed <= out.capacity() {
106        return Ok(());
107    }
108    let bytes = product(&[needed, core::mem::size_of::<T>()])?;
109    with_budget(|budget| match budget {
110        Some(budget) if !budget.reserve(bytes) => Err(ResourceError),
111        _ => Ok(()),
112    })?;
113    out.try_reserve_exact(additional).map_err(|_| reject())
114}
115
116pub fn capacity<T>(count: usize) -> Result<Vec<T>, ResourceError> {
117    let mut out = Vec::new();
118    reserve(&mut out, count)?;
119    Ok(out)
120}
121
122pub fn filled<T: Clone>(value: T, count: usize) -> Result<Vec<T>, ResourceError> {
123    work(count)?;
124    let mut out = capacity(count)?;
125    out.resize(count, value);
126    Ok(out)
127}
128
129pub fn copy<T: Copy>(source: &[T]) -> Result<Vec<T>, ResourceError> {
130    work(source.len())?;
131    let mut out = capacity(source.len())?;
132    out.extend_from_slice(source);
133    Ok(out)
134}
135
136pub fn push<T>(out: &mut Vec<T>, value: T) -> Result<(), ResourceError> {
137    work(1)?;
138    if out.len() == out.capacity() {
139        let needed = out.len().checked_add(1).ok_or_else(reject)?;
140        let item_size = core::mem::size_of::<T>();
141        let ceiling = with_budget(|b| b.map_or(usize::MAX, ResourceBudget::allocation_limit));
142        let count_limit = if item_size == 0 {
143            usize::MAX
144        } else {
145            ceiling / item_size
146        };
147        let desired = out
148            .capacity()
149            .saturating_mul(2)
150            .max(4)
151            .min(count_limit)
152            .max(needed);
153        reserve(out, desired - out.len())?;
154    }
155    out.push(value);
156    Ok(())
157}
158
159pub fn resize<T: Clone>(out: &mut Vec<T>, count: usize, value: T) -> Result<(), ResourceError> {
160    if count > out.len() {
161        work(count - out.len())?;
162        reserve(out, count - out.len())?;
163    } else {
164        work(0)?;
165    }
166    out.resize(count, value);
167    Ok(())
168}
169
170pub fn collect<T>(iter: impl IntoIterator<Item = T>) -> Result<Vec<T>, ResourceError> {
171    let mut out = Vec::new();
172    for item in iter {
173        push(&mut out, item)?;
174    }
175    Ok(out)
176}
177
178pub fn extend<T>(out: &mut Vec<T>, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError> {
179    for item in iter {
180        push(out, item)?;
181    }
182    Ok(())
183}
184
185pub fn append<T>(out: &mut Vec<T>, other: &mut Vec<T>) -> Result<(), ResourceError> {
186    work(other.len())?;
187    reserve(out, other.len())?;
188    out.append(other);
189    Ok(())
190}
191
192/// Reserve a finite iterator's work once; unknown-length iterators check each step.
193pub fn iterations<I: IntoIterator>(iter: I) -> Result<(I::IntoIter, bool), ResourceError> {
194    let iter = iter.into_iter();
195    let (lower, upper) = iter.size_hint();
196    let prepaid = upper == Some(lower);
197    work(if prepaid { lower } else { 0 })?;
198    Ok((iter, prepaid))
199}
200
201/// Fallible methods preserve normal Vec reborrowing at decoder call sites.
202pub trait VecResource<T> {
203    fn rhwp_push(&mut self, value: T) -> Result<(), ResourceError>;
204    fn rhwp_reserve(&mut self, additional: usize) -> Result<(), ResourceError>;
205    fn rhwp_resize(&mut self, count: usize, value: T) -> Result<(), ResourceError>
206    where
207        T: Clone;
208    fn rhwp_extend(&mut self, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError>;
209    fn rhwp_extend_from_slice(&mut self, source: &[T]) -> Result<(), ResourceError>
210    where
211        T: Copy;
212    fn rhwp_append(&mut self, other: &mut Vec<T>) -> Result<(), ResourceError>;
213}
214impl<T> VecResource<T> for Vec<T> {
215    fn rhwp_push(&mut self, value: T) -> Result<(), ResourceError> {
216        push(self, value)
217    }
218    fn rhwp_reserve(&mut self, additional: usize) -> Result<(), ResourceError> {
219        reserve(self, additional)
220    }
221    fn rhwp_resize(&mut self, count: usize, value: T) -> Result<(), ResourceError>
222    where
223        T: Clone,
224    {
225        resize(self, count, value)
226    }
227    fn rhwp_extend(&mut self, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError> {
228        extend(self, iter)
229    }
230    fn rhwp_extend_from_slice(&mut self, source: &[T]) -> Result<(), ResourceError>
231    where
232        T: Copy,
233    {
234        extend(self, source.iter().copied())
235    }
236    fn rhwp_append(&mut self, other: &mut Vec<T>) -> Result<(), ResourceError> {
237        append(self, other)
238    }
239}
240
241pub trait SliceResource<T: Copy> {
242    fn rhwp_copy(&self) -> Result<Vec<T>, ResourceError>;
243}
244impl<T: Copy> SliceResource<T> for [T] {
245    fn rhwp_copy(&self) -> Result<Vec<T>, ResourceError> {
246        copy(self)
247    }
248}
249pub trait IteratorResource: Iterator + Sized {
250    fn rhwp_collect(self) -> Result<Vec<Self::Item>, ResourceError> {
251        collect(self)
252    }
253}
254impl<I: Iterator> IteratorResource for I {}
255
256#[cfg(all(test, feature = "scoped"))]
257mod tests {
258    use super::*;
259    use alloc::sync::Arc;
260    use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
261
262    struct Budget {
263        bytes: usize,
264        units: AtomicUsize,
265        failed: AtomicBool,
266    }
267    impl ResourceBudget for Budget {
268        fn allocation_limit(&self) -> usize {
269            self.bytes
270        }
271        fn reserve(&self, bytes: usize) -> bool {
272            if bytes > self.bytes {
273                self.reject();
274                return false;
275            }
276            !self.failed.load(Ordering::Relaxed)
277        }
278        fn work(&self, units: usize) -> bool {
279            if self.failed.load(Ordering::Relaxed) {
280                return false;
281            }
282            if atomic::try_update_usize(&self.units, Ordering::Relaxed, Ordering::Relaxed, |n| {
283                n.checked_sub(units)
284            })
285            .is_err()
286            {
287                self.reject();
288                return false;
289            }
290            true
291        }
292        fn reject(&self) {
293            self.failed.store(true, Ordering::Relaxed);
294        }
295    }
296    fn budget(bytes: usize, units: usize) -> Arc<Budget> {
297        Arc::new(Budget {
298            bytes,
299            units: AtomicUsize::new(units),
300            failed: AtomicBool::new(false),
301        })
302    }
303
304    #[test]
305    fn stable_sort_preserves_equal_key_order_and_charges_its_storage() {
306        let b = budget(64, 1024);
307        let _scope = Scope::enter(b.clone());
308        let mut data = [(2, 'a'), (1, 'b'), (2, 'c'), (1, 'd')];
309        sort(&mut data, |a, b| a.0.cmp(&b.0)).unwrap();
310        assert_eq!(data, [(1, 'b'), (1, 'd'), (2, 'a'), (2, 'c')]);
311        let _nested = Scope::enter(budget(1, 1024));
312        let before = data;
313        assert!(sort(&mut data, |a, b| b.0.cmp(&a.0)).is_err());
314        assert_eq!(data, before);
315    }
316
317    #[test]
318    fn rejected_reservation_preserves_the_original_vector() {
319        let b = budget(3, 100);
320        let _scope = Scope::enter(b.clone());
321        let mut out: Vec<u8> = Vec::new();
322        assert!(reserve(&mut out, 4).is_err());
323        assert_eq!(out.capacity(), 0);
324        assert!(b.failed.load(Ordering::Relaxed));
325    }
326
327    #[test]
328    fn exact_work_limit_and_nested_failure_restore_the_prior_request() {
329        let outer = budget(32, 3);
330        let _scope = Scope::enter(outer.clone());
331        work(3).unwrap();
332        {
333            let _nested = Scope::enter(budget(0, 0));
334            assert!(work(1).is_err());
335        }
336        work(0).unwrap();
337        assert!(!outer.failed.load(Ordering::Relaxed));
338        assert!(work(1).is_err());
339    }
340
341    #[test]
342    fn another_thread_and_the_next_request_have_independent_budgets() {
343        let scope = Scope::enter(budget(0, 0));
344        assert!(work(1).is_err());
345        std::thread::spawn(|| work(1).unwrap()).join().unwrap();
346        drop(scope);
347        let _next = Scope::enter(budget(8, 8));
348        assert_eq!(filled(7u8, 8).unwrap(), [7; 8]);
349    }
350}
351
352/// Collect fallible elements without an unaccounted intermediate allocation.
353pub fn try_collect<T, E: From<ResourceError>>(
354    iter: impl IntoIterator<Item = Result<T, E>>,
355) -> Result<Vec<T>, E> {
356    let mut out = Vec::new();
357    for item in iter {
358        push(&mut out, item?)?;
359    }
360    Ok(out)
361}
362/// Stable ordering with explicitly fallible index storage instead of hidden
363/// allocator-owned sort scratch. Ties preserve the original input order.
364pub fn sort<T>(
365    data: &mut [T],
366    mut cmp: impl FnMut(&T, &T) -> core::cmp::Ordering,
367) -> Result<(), ResourceError> {
368    let count = data.len();
369    if count < 2 {
370        return work(0);
371    }
372    let levels = usize::BITS as usize - count.leading_zeros() as usize;
373    work(product(&[count, levels, 4])?)?;
374    let mut indices = collect(0..count)?;
375    indices.sort_unstable_by(|&a, &b| cmp(&data[a], &data[b]).then(a.cmp(&b)));
376    let mut destinations = filled(0usize, count)?;
377    for (destination, &source) in indices.iter().enumerate() {
378        destinations[source] = destination;
379    }
380    for source in 0..count {
381        while destinations[source] != source {
382            work(1)?;
383            let destination = destinations[source];
384            data.swap(source, destination);
385            destinations.swap(source, destination);
386        }
387    }
388    Ok(())
389}