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
use std::borrow::Cow;
use std::str;

use crate::convert::UnboxRubyError;
use crate::core::TryConvertMut;
use crate::error::Error;
use crate::types::Rust;
use crate::value::Value;
use crate::Artichoke;

impl TryConvertMut<String, Value> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, value: String) -> Result<Value, Self::Error> {
        // Ruby `String`s are just bytes, so get a pointer to the underlying
        // `&[u8]` infallibly and convert that to a `Value`.
        self.try_convert_mut(value.into_bytes())
    }
}

impl TryConvertMut<&str, Value> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, value: &str) -> Result<Value, Self::Error> {
        // Ruby `String`s are just bytes, so get a pointer to the underlying
        // `&[u8]` infallibly and convert that to a `Value`.
        self.try_convert_mut(value.as_bytes())
    }
}

impl<'a> TryConvertMut<Cow<'a, str>, Value> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, value: Cow<'a, str>) -> Result<Value, Self::Error> {
        match value {
            Cow::Borrowed(string) => self.try_convert_mut(string),
            Cow::Owned(string) => self.try_convert_mut(string),
        }
    }
}

impl TryConvertMut<Value, String> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, value: Value) -> Result<String, Self::Error> {
        let bytes = self.try_convert_mut(value)?;
        // This converter requires that the bytes be valid UTF-8 data. If the
        // `Value` contains binary data, use the `Vec<u8>` or `&[u8]` converter.
        let string = String::from_utf8(bytes).map_err(|_| UnboxRubyError::new(&value, Rust::String))?;
        Ok(string)
    }
}

impl<'a> TryConvertMut<Value, &'a str> for Artichoke {
    type Error = Error;

    fn try_convert_mut(&mut self, value: Value) -> Result<&'a str, Self::Error> {
        let bytes = self.try_convert_mut(value)?;
        // This converter requires that the bytes be valid UTF-8 data. If the
        // `Value` contains binary data, use the `Vec<u8>` or `&[u8]` converter.
        let string = str::from_utf8(bytes).map_err(|_| UnboxRubyError::new(&value, Rust::String))?;
        Ok(string)
    }
}

#[cfg(test)]
mod tests {
    use quickcheck::quickcheck;

    use crate::test::prelude::*;

    #[test]
    fn fail_convert() {
        let mut interp = interpreter();
        // get a mrb_value that can't be converted to a primitive type.
        let value = interp.eval(b"Object.new").unwrap();
        let result = value.try_convert_into_mut::<String>(&mut interp);
        assert!(result.is_err());
    }

    quickcheck! {
        fn convert_to_string(s: String) -> bool {
            let mut interp = interpreter();
            let value = interp.try_convert_mut(s.clone()).unwrap();
            let string: Vec<u8> = interp.try_convert_mut(value).unwrap();
            s.as_bytes() == string
        }

        fn string_with_value(s: String) -> bool {
            let mut interp = interpreter();
            let value = interp.try_convert_mut(s.clone()).unwrap();
            value.to_s(&mut interp) == s.as_bytes()
        }

        #[cfg(feature = "core-regexp")]
        fn utf8string_borrowed(string: String) -> bool {
            let mut interp = interpreter();
            // Borrowed converter
            let value = interp.try_convert_mut(string.as_str()).unwrap();
            let len = value
                .funcall(&mut interp, "length", &[], None)
                .and_then(|value| value.try_convert_into::<usize>(&interp))
                .unwrap();
            if len != string.chars().count() {
                return false;
            }
            let zero = interp.convert(0);
            let first = value
                .funcall(&mut interp, "[]", &[zero], None)
                .and_then(|value| value.try_convert_into_mut::<Option<String>>(&mut interp))
                .unwrap();
            let mut iter = string.chars();
            if let Some(ch) = iter.next() {
                if first != Some(ch.to_string()) {
                    return false;
                }
            } else if first.is_some() {
                return false;
            }
            let recovered: String = interp.try_convert_mut(value).unwrap();
            if recovered != string {
                return false;
            }
            true
        }

        #[cfg(feature = "core-regexp")]
        fn utf8string_owned(string: String) -> bool {
            let mut interp = interpreter();
            // Owned converter
            let value = interp.try_convert_mut(string.clone()).unwrap();
            let len = value
                .funcall(&mut interp, "length", &[], None)
                .and_then(|value| value.try_convert_into::<usize>(&interp))
                .unwrap();
            if len != string.chars().count() {
                return false;
            }
            let zero = interp.convert(0);
            let first = value
                .funcall(&mut interp, "[]", &[zero], None)
                .and_then(|value| value.try_convert_into_mut::<Option<String>>(&mut interp))
                .unwrap();
            let mut iter = string.chars();
            if let Some(ch) = iter.next() {
                if first != Some(ch.to_string()) {
                    return false;
                }
            } else if first.is_some() {
                return false;
            }
            let recovered: String = interp.try_convert_mut(value).unwrap();
            if recovered != string {
                return false;
            }
            true
        }

        fn roundtrip(s: String) -> bool {
            let mut interp = interpreter();
            let value = interp.try_convert_mut(s.clone()).unwrap();
            let value = value.try_convert_into_mut::<String>(&mut interp).unwrap();
            value == s
        }

        fn roundtrip_err(b: bool) -> bool {
            let mut interp = interpreter();
            let value = interp.convert(b);
            let result = value.try_convert_into_mut::<String>(&mut interp);
            result.is_err()
        }
    }
}