scheme_rs/
util.rs

1use crate::{
2    error::RuntimeError,
3    gc::{Gc, Trace},
4    value::Value,
5};
6use std::{fmt, ops::Deref, sync::Arc};
7
8#[derive(Clone, Trace)]
9pub struct ArcSlice<T> {
10    arc: Arc<[T]>,
11    start: usize,
12}
13
14impl<T> ArcSlice<T> {
15    pub fn empty() -> Self {
16        Self {
17            arc: Arc::from([]),
18            start: 0,
19        }
20    }
21
22    pub fn skip_last(&self) -> impl Iterator<Item = (&T, ArcSlice<T>)> {
23        (self.start..(self.arc.len().saturating_sub(1))).map(|i| {
24            (
25                &self.arc[i],
26                ArcSlice {
27                    arc: self.arc.clone(),
28                    start: i + 1,
29                },
30            )
31        })
32    }
33
34    pub fn iter(&self) -> impl Iterator<Item = (&T, ArcSlice<T>)> {
35        (self.start..self.arc.len()).map(|i| {
36            (
37                &self.arc[i],
38                ArcSlice {
39                    arc: self.arc.clone(),
40                    start: i + 1,
41                },
42            )
43        })
44    }
45}
46
47impl<T: fmt::Debug> fmt::Debug for ArcSlice<T> {
48    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
49        fmt.debug_list().entries(&self.arc[self.start..]).finish()
50    }
51}
52
53impl<T> From<Vec<T>> for ArcSlice<T> {
54    fn from(v: Vec<T>) -> Self {
55        Self {
56            arc: Arc::from(v),
57            start: 0,
58        }
59    }
60}
61
62impl<T> Deref for ArcSlice<T> {
63    type Target = [T];
64
65    fn deref(&self) -> &Self::Target {
66        &self.arc.as_ref()[self.start..]
67    }
68}
69
70pub fn iter_arc<T>(arc: &Arc<[T]>) -> impl Iterator<Item = (&T, ArcSlice<T>)> {
71    (0..arc.len()).map(|i| {
72        (
73            &arc[i],
74            ArcSlice {
75                arc: arc.clone(),
76                start: i + 1,
77            },
78        )
79    })
80}
81
82/// Extension crate for extracting a single value from a Vec
83pub trait RequireOne {
84    fn require_one(self) -> Result<Gc<Value>, RuntimeError>;
85}
86
87impl RequireOne for Vec<Gc<Value>> {
88    fn require_one(self) -> Result<Gc<Value>, RuntimeError> {
89        let nargs = self.len();
90        let [arg] = self
91            .try_into()
92            .map_err(|_| RuntimeError::wrong_num_of_args(1, nargs))?;
93        Ok(arg)
94    }
95}