Skip to main content

cynic_parser/values/
lists.rs

1use std::fmt;
2
3use crate::{AstLookup, Span};
4
5use super::{Cursor, const_lists::ConstList, ids::ValueId, iter::Iter, value::Value};
6
7#[derive(Clone, Copy)]
8pub struct List<'a>(pub(super) super::Cursor<'a, ValueId>);
9
10impl<'a> List<'a> {
11    pub fn is_empty(&self) -> bool {
12        self.len() == 0
13    }
14
15    pub fn len(&self) -> usize {
16        let store = &self.0.store;
17        store.lookup(self.0.id).kind.as_list().unwrap().len()
18    }
19
20    pub fn span(&self) -> Span {
21        let store = &self.0.store;
22        store.lookup(self.0.id).span
23    }
24
25    pub fn items(&self) -> Iter<'a, Value<'a>> {
26        let store = &self.0.store;
27        Iter::new(store.lookup(self.0.id).kind.as_list().unwrap(), store)
28    }
29
30    pub fn get(&self, index: usize) -> Option<Value<'a>> {
31        self.items().nth(index)
32    }
33}
34
35impl PartialEq for List<'_> {
36    fn eq(&self, other: &Self) -> bool {
37        self.len() == other.len() && self.items().zip(other.items()).all(|(lhs, rhs)| lhs == rhs)
38    }
39}
40
41impl Eq for List<'_> {}
42
43impl fmt::Debug for List<'_> {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        f.debug_list().entries(self.items()).finish()
46    }
47}
48
49impl<'a> From<ConstList<'a>> for List<'a> {
50    fn from(value: ConstList<'a>) -> Self {
51        let Cursor { id, store } = value.0;
52
53        let id = id.into();
54
55        List(Cursor { id, store })
56    }
57}
58
59impl<'a> IntoIterator for List<'a> {
60    type Item = Value<'a>;
61
62    type IntoIter = Iter<'a, Value<'a>>;
63
64    fn into_iter(self) -> Self::IntoIter {
65        self.items()
66    }
67}