rune/core/object/
convert.rs

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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
//! This module holds implementation of conversion functions. Much of
//! this code could be replaced with macros or specialized generics if
//! those are ever stabalized.

use crate::data::LispError;

use super::{
    super::error::{Type, TypeError},
    ByteString, LispHashTable, LispString, LispVec, OptionalFlag, NIL, TRUE,
};
use super::{Gc, LispFloat, Object, ObjectType, Symbol};
use anyhow::Context;

impl<'ob> TryFrom<Object<'ob>> for &'ob str {
    type Error = anyhow::Error;
    fn try_from(obj: Object<'ob>) -> Result<Self, Self::Error> {
        match obj.untag() {
            ObjectType::String(x) => Ok(x),
            x => Err(TypeError::new(Type::String, x).into()),
        }
    }
}

impl TryFrom<Object<'_>> for f64 {
    type Error = TypeError;
    fn try_from(obj: Object) -> Result<Self, Self::Error> {
        match obj.untag() {
            ObjectType::Int(x) => Ok(x as f64),
            ObjectType::Float(x) => Ok(**x),
            x => Err(TypeError::new(Type::Number, x)),
        }
    }
}

impl<'ob> TryFrom<Object<'ob>> for Option<&'ob str> {
    type Error = TypeError;
    fn try_from(obj: Object<'ob>) -> Result<Self, Self::Error> {
        match obj.untag() {
            ObjectType::NIL => Ok(None),
            ObjectType::String(x) => Ok(Some(x)),
            x => Err(TypeError::new(Type::String, x)),
        }
    }
}

impl<'ob> TryFrom<Object<'ob>> for usize {
    type Error = anyhow::Error;
    fn try_from(obj: Object<'ob>) -> Result<Self, Self::Error> {
        match obj.untag() {
            ObjectType::Int(x) => {
                x.try_into().with_context(|| format!("Integer must be positive, but was {x}"))
            }
            x => Err(TypeError::new(Type::Int, x).into()),
        }
    }
}

impl<'ob> TryFrom<Object<'ob>> for char {
    type Error = TypeError;
    fn try_from(obj: Object<'ob>) -> Result<Self, Self::Error> {
        let err = || TypeError::new(Type::Char, obj);
        let ObjectType::Int(x) = obj.untag() else { Err(err())? };
        let Ok(x) = u32::try_from(x) else { Err(err())? };
        std::char::from_u32(x).ok_or_else(err)
    }
}

impl<'ob> TryFrom<Object<'ob>> for Option<usize> {
    type Error = anyhow::Error;
    fn try_from(obj: Object<'ob>) -> Result<Self, Self::Error> {
        match obj.untag() {
            ObjectType::Int(x) => match x.try_into() {
                Ok(x) => Ok(Some(x)),
                Err(e) => Err(e).with_context(|| format!("Integer must be positive, but was {x}")),
            },
            ObjectType::NIL => Ok(None),
            _ => Err(TypeError::new(Type::Int, obj).into()),
        }
    }
}

impl TryFrom<Object<'_>> for bool {
    type Error = LispError;
    fn try_from(obj: Object) -> Result<Self, Self::Error> {
        Ok(obj.is_nil())
    }
}

impl TryFrom<Object<'_>> for OptionalFlag {
    type Error = LispError;
    fn try_from(obj: Object) -> Result<Self, Self::Error> {
        Ok(obj.is_nil().then_some(()))
    }
}

/// This function is required because we have no specialization yet.
/// Essentially this let's us convert one type to another "in place"
/// without the need to allocate a new slice. We ensure that the two
/// types have the exact same representation, so that no writes
/// actually need to be performed.
pub(crate) fn try_from_slice<'brw, 'ob, T, E>(
    slice: &'brw [Object<'ob>],
) -> Result<&'brw [Gc<T>], E>
where
    Gc<T>: TryFrom<Object<'ob>, Error = E> + 'ob,
{
    for x in slice {
        let _new = Gc::<T>::try_from(*x)?;
    }
    let ptr = slice.as_ptr().cast::<Gc<T>>();
    let len = slice.len();
    Ok(unsafe { std::slice::from_raw_parts(ptr, len) })
}

impl From<bool> for Object<'_> {
    fn from(b: bool) -> Self {
        if b {
            TRUE
        } else {
            NIL
        }
    }
}

define_unbox!(Int, i64);
define_unbox!(Float, &'ob LispFloat);
define_unbox!(HashTable, &'ob LispHashTable);
define_unbox!(String, &'ob LispString);
define_unbox!(ByteString, String, &'ob ByteString);
define_unbox!(Vec, &'ob LispVec);
define_unbox!(Symbol, Symbol<'ob>);

impl<'ob, T> From<Option<T>> for Object<'ob>
where
    T: Into<Object<'ob>>,
{
    fn from(t: Option<T>) -> Self {
        match t {
            Some(x) => x.into(),
            None => NIL,
        }
    }
}

#[cfg(test)]
mod test {
    use crate::core::cons::Cons;

    use super::super::super::gc::{Context, RootSet};

    use super::*;

    fn wrapper(args: &[Object]) -> Result<i64, TypeError> {
        Ok(inner(
            std::convert::TryFrom::try_from(args[0])?,
            std::convert::TryFrom::try_from(args[1])?,
        ))
    }

    fn inner(arg0: Option<i64>, arg1: &Cons) -> i64 {
        let x: i64 = arg1.car().try_into().unwrap();
        arg0.unwrap() + x
    }

    #[test]
    fn test() {
        let roots = &RootSet::default();
        let cx = &Context::new(roots);
        let obj0 = cx.add(5);
        // SAFETY: We don't call garbage collect so references are valid
        let obj1 = cx.add(Cons::new(1, 2, cx));
        let vec = vec![obj0, obj1];
        let res = wrapper(vec.as_slice());
        assert_eq!(6, res.unwrap());
    }
}