snix_eval/value/
list.rs

1//! This module implements Nix lists.
2use std::ops::Index;
3use std::rc::Rc;
4
5use serde::Deserialize;
6
7use super::thunk::ThunkSet;
8use super::TotalDisplay;
9use super::Value;
10
11#[repr(transparent)]
12#[derive(Clone, Debug, Deserialize)]
13pub struct NixList(Rc<Vec<Value>>);
14
15impl TotalDisplay for NixList {
16    fn total_fmt(&self, f: &mut std::fmt::Formatter<'_>, set: &mut ThunkSet) -> std::fmt::Result {
17        f.write_str("[ ")?;
18
19        for v in self {
20            v.total_fmt(f, set)?;
21            f.write_str(" ")?;
22        }
23
24        f.write_str("]")
25    }
26}
27
28impl From<Vec<Value>> for NixList {
29    fn from(vs: Vec<Value>) -> Self {
30        Self(Rc::new(vs))
31    }
32}
33
34impl NixList {
35    pub fn len(&self) -> usize {
36        self.0.len()
37    }
38
39    pub fn get(&self, i: usize) -> Option<&Value> {
40        self.0.get(i)
41    }
42
43    pub fn is_empty(&self) -> bool {
44        self.0.is_empty()
45    }
46
47    pub fn construct(count: usize, stack_slice: Vec<Value>) -> Self {
48        debug_assert!(
49            count == stack_slice.len(),
50            "NixList::construct called with count == {}, but slice.len() == {}",
51            count,
52            stack_slice.len(),
53        );
54
55        NixList(Rc::new(stack_slice))
56    }
57
58    pub fn iter(&self) -> std::slice::Iter<Value> {
59        self.0.iter()
60    }
61
62    pub fn ptr_eq(&self, other: &Self) -> bool {
63        Rc::ptr_eq(&self.0, &other.0)
64    }
65
66    pub fn into_inner(self) -> Vec<Value> {
67        Rc::try_unwrap(self.0).unwrap_or_else(|rc| (*rc).clone())
68    }
69}
70
71impl IntoIterator for NixList {
72    type Item = Value;
73    type IntoIter = std::vec::IntoIter<Value>;
74
75    fn into_iter(self) -> Self::IntoIter {
76        self.into_inner().into_iter()
77    }
78}
79
80impl<'a> IntoIterator for &'a NixList {
81    type Item = &'a Value;
82    type IntoIter = std::slice::Iter<'a, Value>;
83
84    fn into_iter(self) -> Self::IntoIter {
85        self.0.iter()
86    }
87}
88
89impl Index<usize> for NixList {
90    type Output = Value;
91
92    fn index(&self, index: usize) -> &Self::Output {
93        &self.0[index]
94    }
95}