cynic_parser/values/
const_objects.rs1use std::fmt;
2
3use crate::{common::IdRange, AstLookup, Span};
4
5use super::{
6 iter::{Iter, ValueStoreReader},
7 ConstFieldId, ConstValue, ConstValueId, ValueStoreId,
8};
9
10#[derive(Clone, Copy)]
11pub struct ConstObject<'a>(pub(super) super::Cursor<'a, ConstValueId>);
12
13impl<'a> ConstObject<'a> {
14 pub fn is_empty(&self) -> bool {
15 self.len() == 0
16 }
17
18 pub fn len(&self) -> usize {
19 let store = self.0.store;
20 store.lookup(self.0.id).kind.as_object().unwrap().len()
21 }
22
23 pub fn span(&self) -> Span {
24 let store = &self.0.store;
25 store.lookup(self.0.id).span
26 }
27
28 pub fn fields(&self) -> Iter<'a, ConstObjectField<'a>> {
29 let store = self.0.store;
30
31 let IdRange { start, end } = store.lookup(self.0.id).kind.as_object().unwrap();
32 let start = ConstFieldId::new(start.get());
33 let end = ConstFieldId::new(end.get());
34
35 Iter::new(IdRange { start, end }, store)
36 }
37
38 pub fn get(&self, name: &str) -> Option<ConstValue<'a>> {
39 Some(self.fields().find(|field| field.name() == name)?.value())
40 }
41}
42
43impl fmt::Debug for ConstObject<'_> {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 f.debug_map()
46 .entries(self.fields().map(|field| (field.name(), field.value())))
47 .finish()
48 }
49}
50
51impl<'a> IntoIterator for ConstObject<'a> {
52 type Item = ConstObjectField<'a>;
53
54 type IntoIter = Iter<'a, ConstObjectField<'a>>;
55
56 fn into_iter(self) -> Self::IntoIter {
57 self.fields()
58 }
59}
60
61#[derive(Clone, Copy)]
62pub struct ConstObjectField<'a>(super::Cursor<'a, ConstFieldId>);
63
64impl<'a> ConstObjectField<'a> {
65 pub fn name(&self) -> &'a str {
66 let store = self.0.store;
67 store.lookup(store.lookup(self.0.id).name)
68 }
69
70 pub fn name_span(&self) -> Span {
71 let store = self.0.store;
72 store.lookup(self.0.id).name_span
73 }
74
75 pub fn value(&self) -> ConstValue<'a> {
76 let store = self.0.store;
77 store.read(ConstValueId::new(store.lookup(self.0.id).value.get()))
78 }
79}
80
81impl<'a> ValueStoreReader<'a> for ConstObjectField<'a> {
82 type Id = ConstFieldId;
83}
84
85impl ValueStoreId for ConstFieldId {
86 type Reader<'a> = ConstObjectField<'a>;
87
88 fn read(self, store: &super::ValueStore) -> Self::Reader<'_> {
89 ConstObjectField(super::Cursor { id: self, store })
90 }
91}