1use std::{collections::VecDeque, fmt::Debug};
2
3use arc_gc::{
4 arc::{GCArc, GCArcWeak},
5 traceable::GCTraceable,
6};
7
8use crate::lambda::runnable::RuntimeError;
9
10use super::object::{OnionObject, OnionObjectCell, OnionStaticObject};
11
12#[derive(Clone)]
13pub struct OnionNamed {
14 key: OnionObject,
15 value: OnionObject,
16}
17
18impl GCTraceable<OnionObjectCell> for OnionNamed {
19 fn collect(&self, queue: &mut VecDeque<GCArcWeak<OnionObjectCell>>) {
20 self.key.collect(queue);
21 self.value.collect(queue);
22 }
23}
24
25impl Debug for OnionNamed {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 write!(f, "{:?} => {:?}", self.key, self.value)
28 }
29}
30
31impl OnionNamed {
32 pub fn new(key: OnionObject, value: OnionObject) -> Self {
33 OnionNamed {
34 key: key.into(),
35 value: value.into(),
36 }
37 }
38
39 pub fn new_static(key: &OnionStaticObject, value: &OnionStaticObject) -> OnionStaticObject {
40 OnionObject::Named(
41 OnionNamed {
42 key: key.weak().clone(),
43 value: value.weak().clone(),
44 }
45 .into(),
46 )
47 .consume_and_stabilize()
48 }
49
50 #[inline(always)]
51 pub fn get_key(&self) -> &OnionObject {
52 &self.key
53 }
54
55 #[inline(always)]
56 pub fn get_value(&self) -> &OnionObject {
57 &self.value
58 }
59 pub fn upgrade(&self, collected: &mut Vec<GCArc<OnionObjectCell>>) {
60 self.key.upgrade(collected);
61 self.value.upgrade(collected)
62 }
63}
64
65impl OnionNamed {
66 pub fn equals(&self, other: &OnionObject) -> Result<bool, RuntimeError> {
67 match other {
68 OnionObject::Named(pair) => {
69 if self.key.equals(&pair.key)? && self.value.equals(&pair.value)? {
70 return Ok(true);
71 }
72 }
73 _ => {}
74 }
75 Ok(false)
76 }
77
78 pub fn with_attribute<F, R>(&self, key: &OnionObject, f: &F) -> Result<R, RuntimeError>
79 where
80 F: Fn(&OnionObject) -> Result<R, RuntimeError>,
81 {
82 self.value
83 .with_attribute(key, f)
84 .or_else(|_| self.key.with_attribute(key, f))
85 }
86}
87impl OnionNamed {
88 pub fn reconstruct_container(&self) -> Result<OnionObject, RuntimeError> {
89 Ok(OnionObject::Named(
90 OnionNamed {
91 key: self.key.clone(),
92 value: self.value.clone(),
93 }
94 .into(),
95 ))
96 }
97}