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
177
178
179
180
use std::borrow::Cow;
use std::str;

use crate::convert::UnboxRubyError;
use crate::core::{ConvertMut, TryConvertMut};
use crate::exception::Exception;
use crate::types::Rust;
use crate::value::Value;
use crate::Artichoke;

impl ConvertMut<String, Value> for Artichoke {
    fn convert_mut(&mut self, value: String) -> Value {
        // Ruby `String`s are just bytes, so get a pointer to the underlying
        // `&[u8]` infallibly and convert that to a `Value`.
        self.convert_mut(value.as_bytes())
    }
}

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

impl<'a> ConvertMut<Cow<'a, str>, Value> for Artichoke {
    fn convert_mut(&mut self, value: Cow<'a, str>) -> Value {
        match value {
            Cow::Borrowed(string) => self.convert_mut(string),
            Cow::Owned(string) => self.convert_mut(string),
        }
    }
}

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

    fn try_convert_mut(&mut self, value: Value) -> Result<String, Self::Error> {
        TryConvertMut::<_, &str>::try_convert_mut(self, value).map(String::from)
    }
}

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

    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)]
// Convert<String> is implemented in terms of Convert<&str> so only implement
// the tests for String to exercise both code paths.
mod tests {
    use quickcheck_macros::quickcheck;
    use std::convert::TryFrom;
    use std::slice;

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

    #[test]
    fn fail_convert() {
        let mut interp = interpreter().unwrap();
        // 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_into_mut::<String>(&mut interp);
        assert!(result.is_err());
    }

    #[allow(clippy::needless_pass_by_value)]
    #[quickcheck]
    fn convert_to_string(s: String) -> bool {
        let mut interp = interpreter().unwrap();
        let value = interp.convert_mut(s.clone());
        let string = unsafe {
            interp
                .with_ffi_boundary(|mrb| {
                    let ptr = sys::mrb_string_value_ptr(mrb, value.inner());
                    let len = sys::mrb_string_value_len(mrb, value.inner());
                    let len = usize::try_from(len).unwrap();
                    slice::from_raw_parts(ptr as *const u8, len)
                })
                .unwrap()
        };
        s.as_bytes() == string
    }

    #[allow(clippy::needless_pass_by_value)]
    #[quickcheck]
    fn string_with_value(s: String) -> bool {
        let mut interp = interpreter().unwrap();
        let value = interp.convert_mut(s.clone());
        value.to_s(&mut interp) == s.as_bytes()
    }

    #[quickcheck]
    fn utf8string(string: String) -> bool {
        let mut interp = interpreter().unwrap();
        // Borrowed converter
        let value = interp.convert_mut(string.as_str());
        let len = value
            .funcall(&mut interp, "length", &[], None)
            .and_then(|value| value.try_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_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;
        }
        // Owned converter
        let value = interp.convert_mut(string.clone());
        let len = value
            .funcall(&mut interp, "length", &[], None)
            .and_then(|value| value.try_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_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
    }

    #[allow(clippy::needless_pass_by_value)]
    #[quickcheck]
    fn roundtrip(s: String) -> bool {
        let mut interp = interpreter().unwrap();
        let value = interp.convert_mut(s.clone());
        let value = value.try_into_mut::<String>(&mut interp).unwrap();
        value == s
    }

    #[quickcheck]
    fn roundtrip_err(b: bool) -> bool {
        let mut interp = interpreter().unwrap();
        let value = interp.convert(b);
        let result = value.try_into_mut::<String>(&mut interp);
        result.is_err()
    }
}