1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use core::fmt;
use crate::runtime::Variant;
use crate::runtime::gc::{Gc, GcTrace};
use crate::runtime::types::{Type, MetaObject};
use crate::runtime::errors::ExecResult;
#[derive(Clone, Copy)]
pub enum Tuple {
Empty,
NonEmpty(Gc<[Variant]>),
}
unsafe impl GcTrace for Box<[Variant]> {
fn trace(&self) {
for item in self.iter() {
item.trace();
}
}
fn size_hint(&self) -> usize {
core::mem::size_of::<Variant>() * self.len()
}
}
impl Default for Tuple {
fn default() -> Self { Self::Empty }
}
impl From<Box<[Variant]>> for Tuple {
fn from(items: Box<[Variant]>) -> Self {
if items.is_empty() {
Self::Empty
} else {
Self::NonEmpty(Gc::from_box(items))
}
}
}
impl AsRef<[Variant]> for Tuple {
fn as_ref(&self) -> &[Variant] {
match self {
Self::Empty => &[] as &[Variant],
Self::NonEmpty(items) => &**items,
}
}
}
impl Tuple {
pub fn trace(&self) {
if let Self::NonEmpty(gc_items) = self {
gc_items.mark_trace()
}
}
pub fn len(&self) -> usize {
match self {
Self::Empty => 0,
Self::NonEmpty(items) => items.len(),
}
}
pub fn is_empty(&self) -> bool {
match self {
Self::Empty => true,
Self::NonEmpty(..) => false,
}
}
}
impl MetaObject for Tuple {
fn type_tag(&self) -> Type { Type::Tuple }
fn len(&self) -> Option<ExecResult<usize>> {
Some(Ok(Tuple::len(self)))
}
}
impl fmt::Debug for Tuple {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut tuple = fmt.debug_tuple("");
for item in self.as_ref().iter() {
tuple.field(item);
}
tuple.finish()
}
}
impl fmt::Display for Tuple {
fn fmt(&self, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Empty => fmt.write_str("()"),
Self::NonEmpty(items) => {
let (last, rest) = items.split_last().unwrap();
write!(fmt, "(")?;
for item in rest.iter() {
write!(fmt, "{}, ", item.echo())?;
}
write!(fmt, "{})", last.echo())
},
}
}
}