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
9/// The requesting importer owns counters, limits, cancellation, and sticky errors.
10pub trait ResourceBudget: Send + Sync {
11    fn allocation_limit(&self) -> usize;
12    fn reserve(&self, bytes: usize) -> bool;
13    fn work(&self, units: usize) -> bool;
14    fn reject(&self);
15}
16
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub struct ResourceError;
19
20impl fmt::Display for ResourceError {
21    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
22        f.write_str("codec resource limit or allocation failure")
23    }
24}
25
26#[cfg(feature = "scoped")]
27impl std::error::Error for ResourceError {}
28
29#[cfg(feature = "scoped")]
30mod scoped {
31    use super::ResourceBudget;
32    use alloc::rc::Rc;
33    use alloc::sync::Arc;
34    use core::marker::PhantomData;
35    use std::cell::RefCell;
36
37    std::thread_local! {
38        pub(super) static ACTIVE: RefCell<Option<Arc<dyn ResourceBudget>>> = const { RefCell::new(None) };
39    }
40
41    /// Restores the prior synchronous scope. Not Send/Sync: restoration is local.
42    pub struct Scope {
43        previous: Option<Arc<dyn ResourceBudget>>,
44        _thread: PhantomData<Rc<()>>,
45    }
46
47    impl Scope {
48        pub fn enter(budget: Arc<dyn ResourceBudget>) -> Self {
49            Self {
50                previous: ACTIVE.with(|slot| slot.replace(Some(budget))),
51                _thread: PhantomData,
52            }
53        }
54    }
55
56    impl Drop for Scope {
57        fn drop(&mut self) {
58            ACTIVE.with(|slot| *slot.borrow_mut() = self.previous.take());
59        }
60    }
61}
62
63#[cfg(feature = "scoped")]
64pub use scoped::Scope;
65
66fn with_budget<T>(f: impl FnOnce(Option<&dyn ResourceBudget>) -> T) -> T {
67    #[cfg(feature = "scoped")]
68    {
69        scoped::ACTIVE.with(|slot| f(slot.borrow().as_deref()))
70    }
71    #[cfg(not(feature = "scoped"))]
72    {
73        f(None)
74    }
75}
76
77pub fn reject() -> ResourceError {
78    with_budget(|budget| {
79        if let Some(budget) = budget {
80            budget.reject();
81        }
82    });
83    ResourceError
84}
85
86/// Charge before the corresponding repeated work. Zero checks cancellation too.
87pub fn work(units: usize) -> Result<(), ResourceError> {
88    with_budget(|budget| match budget {
89        Some(budget) if !budget.work(units) => Err(ResourceError),
90        _ => Ok(()),
91    })
92}
93
94pub fn product(factors: &[usize]) -> Result<usize, ResourceError> {
95    factors
96        .iter()
97        .try_fold(1usize, |n, &v| n.checked_mul(v).ok_or_else(reject))
98}
99
100pub fn reserve<T>(out: &mut Vec<T>, additional: usize) -> Result<(), ResourceError> {
101    work(0)?;
102    let needed = out.len().checked_add(additional).ok_or_else(reject)?;
103    if needed <= out.capacity() {
104        return Ok(());
105    }
106    let bytes = product(&[needed, core::mem::size_of::<T>()])?;
107    with_budget(|budget| match budget {
108        Some(budget) if !budget.reserve(bytes) => Err(ResourceError),
109        _ => Ok(()),
110    })?;
111    out.try_reserve_exact(additional).map_err(|_| reject())
112}
113
114pub fn capacity<T>(count: usize) -> Result<Vec<T>, ResourceError> {
115    let mut out = Vec::new();
116    reserve(&mut out, count)?;
117    Ok(out)
118}
119
120pub fn filled<T: Clone>(value: T, count: usize) -> Result<Vec<T>, ResourceError> {
121    work(count)?;
122    let mut out = capacity(count)?;
123    out.resize(count, value);
124    Ok(out)
125}
126
127pub fn copy<T: Copy>(source: &[T]) -> Result<Vec<T>, ResourceError> {
128    work(source.len())?;
129    let mut out = capacity(source.len())?;
130    out.extend_from_slice(source);
131    Ok(out)
132}
133
134pub fn push<T>(out: &mut Vec<T>, value: T) -> Result<(), ResourceError> {
135    work(1)?;
136    if out.len() == out.capacity() {
137        let needed = out.len().checked_add(1).ok_or_else(reject)?;
138        let item_size = core::mem::size_of::<T>();
139        let ceiling = with_budget(|b| b.map_or(usize::MAX, ResourceBudget::allocation_limit));
140        let count_limit = if item_size == 0 {
141            usize::MAX
142        } else {
143            ceiling / item_size
144        };
145        let desired = out
146            .capacity()
147            .saturating_mul(2)
148            .max(4)
149            .min(count_limit)
150            .max(needed);
151        reserve(out, desired - out.len())?;
152    }
153    out.push(value);
154    Ok(())
155}
156
157pub fn resize<T: Clone>(out: &mut Vec<T>, count: usize, value: T) -> Result<(), ResourceError> {
158    if count > out.len() {
159        work(count - out.len())?;
160        reserve(out, count - out.len())?;
161    } else {
162        work(0)?;
163    }
164    out.resize(count, value);
165    Ok(())
166}
167
168pub fn collect<T>(iter: impl IntoIterator<Item = T>) -> Result<Vec<T>, ResourceError> {
169    let mut out = Vec::new();
170    for item in iter {
171        push(&mut out, item)?;
172    }
173    Ok(out)
174}
175
176pub fn extend<T>(out: &mut Vec<T>, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError> {
177    for item in iter {
178        push(out, item)?;
179    }
180    Ok(())
181}
182
183pub fn append<T>(out: &mut Vec<T>, other: &mut Vec<T>) -> Result<(), ResourceError> {
184    work(other.len())?;
185    reserve(out, other.len())?;
186    out.append(other);
187    Ok(())
188}
189
190/// Reserve a finite iterator's work once; unknown-length iterators check each step.
191pub fn iterations<I: IntoIterator>(iter: I) -> Result<(I::IntoIter, bool), ResourceError> {
192    let iter = iter.into_iter();
193    let (lower, upper) = iter.size_hint();
194    let prepaid = upper == Some(lower);
195    work(if prepaid { lower } else { 0 })?;
196    Ok((iter, prepaid))
197}
198
199/// Fallible methods preserve normal Vec reborrowing at decoder call sites.
200pub trait VecResource<T> {
201    fn rhwp_push(&mut self, value: T) -> Result<(), ResourceError>;
202    fn rhwp_reserve(&mut self, additional: usize) -> Result<(), ResourceError>;
203    fn rhwp_resize(&mut self, count: usize, value: T) -> Result<(), ResourceError>
204    where
205        T: Clone;
206    fn rhwp_extend(&mut self, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError>;
207    fn rhwp_extend_from_slice(&mut self, source: &[T]) -> Result<(), ResourceError>
208    where
209        T: Copy;
210    fn rhwp_append(&mut self, other: &mut Vec<T>) -> Result<(), ResourceError>;
211}
212impl<T> VecResource<T> for Vec<T> {
213    fn rhwp_push(&mut self, value: T) -> Result<(), ResourceError> {
214        push(self, value)
215    }
216    fn rhwp_reserve(&mut self, additional: usize) -> Result<(), ResourceError> {
217        reserve(self, additional)
218    }
219    fn rhwp_resize(&mut self, count: usize, value: T) -> Result<(), ResourceError>
220    where
221        T: Clone,
222    {
223        resize(self, count, value)
224    }
225    fn rhwp_extend(&mut self, iter: impl IntoIterator<Item = T>) -> Result<(), ResourceError> {
226        extend(self, iter)
227    }
228    fn rhwp_extend_from_slice(&mut self, source: &[T]) -> Result<(), ResourceError>
229    where
230        T: Copy,
231    {
232        extend(self, source.iter().copied())
233    }
234    fn rhwp_append(&mut self, other: &mut Vec<T>) -> Result<(), ResourceError> {
235        append(self, other)
236    }
237}
238
239pub trait SliceResource<T: Copy> {
240    fn rhwp_copy(&self) -> Result<Vec<T>, ResourceError>;
241}
242impl<T: Copy> SliceResource<T> for [T] {
243    fn rhwp_copy(&self) -> Result<Vec<T>, ResourceError> {
244        copy(self)
245    }
246}
247pub trait IteratorResource: Iterator + Sized {
248    fn rhwp_collect(self) -> Result<Vec<Self::Item>, ResourceError> {
249        collect(self)
250    }
251}
252impl<I: Iterator> IteratorResource for I {}
253
254#[cfg(all(test, feature = "scoped"))]
255mod tests {
256    use super::*;
257    use alloc::sync::Arc;
258    use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
259
260    struct Budget {
261        bytes: usize,
262        units: AtomicUsize,
263        failed: AtomicBool,
264    }
265    impl ResourceBudget for Budget {
266        fn allocation_limit(&self) -> usize {
267            self.bytes
268        }
269        fn reserve(&self, bytes: usize) -> bool {
270            if bytes > self.bytes {
271                self.reject();
272                return false;
273            }
274            !self.failed.load(Ordering::Relaxed)
275        }
276        fn work(&self, units: usize) -> bool {
277            if self.failed.load(Ordering::Relaxed) {
278                return false;
279            }
280            if self
281                .units
282                .fetch_update(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}