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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use std::convert::TryFrom;

use crate::convert::{BoxIntoRubyError, UnboxRubyError};
use crate::core::{Convert, TryConvert};
use crate::exception::Exception;
use crate::sys;
use crate::types::{Int, Ruby, Rust};
use crate::value::Value;
use crate::Artichoke;

impl Convert<u8, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: u8) -> Value {
        self.convert(Int::from(value))
    }
}

impl Convert<u16, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: u16) -> Value {
        self.convert(Int::from(value))
    }
}

impl Convert<u32, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: u32) -> Value {
        self.convert(Int::from(value))
    }
}

impl TryConvert<u64, Value> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: u64) -> Result<Value, Self::Error> {
        if let Ok(value) = Int::try_from(value) {
            let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) };
            Ok(Value::from(fixnum))
        } else {
            Err(Exception::from(BoxIntoRubyError::new(
                Rust::UnsignedInt,
                Ruby::Fixnum,
            )))
        }
    }
}

impl TryConvert<usize, Value> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: usize) -> Result<Value, Self::Error> {
        if let Ok(value) = Int::try_from(value) {
            let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) };
            Ok(Value::from(fixnum))
        } else {
            Err(Exception::from(BoxIntoRubyError::new(
                Rust::UnsignedInt,
                Ruby::Fixnum,
            )))
        }
    }
}

impl Convert<i8, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: i8) -> Value {
        self.convert(Int::from(value))
    }
}

impl Convert<i16, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: i16) -> Value {
        self.convert(Int::from(value))
    }
}

impl Convert<i32, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: i32) -> Value {
        self.convert(Int::from(value))
    }
}

impl TryConvert<isize, Value> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: isize) -> Result<Value, Self::Error> {
        if let Ok(value) = Int::try_from(value) {
            let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) };
            Ok(Value::from(fixnum))
        } else {
            Err(Exception::from(BoxIntoRubyError::new(
                Rust::SignedInt,
                Ruby::Fixnum,
            )))
        }
    }
}

/// Converter for Artichoke native integer type.
///
/// The `Int` type alias must be `i64`.
///
/// ```
/// # use std::any::TypeId;
/// # use std::mem;
/// # use artichoke_backend::types::Int;
/// assert_eq!(mem::size_of::<i64>(), mem::size_of::<Int>());
/// assert_eq!(i64::min_value(), Int::min_value());
/// assert_eq!(i64::max_value(), Int::max_value());
/// assert_eq!(TypeId::of::<i64>(), TypeId::of::<Int>());
/// ```
impl Convert<Int, Value> for Artichoke {
    #[inline]
    fn convert(&self, value: Int) -> Value {
        let fixnum = unsafe { sys::mrb_sys_fixnum_value(value) };
        Value::from(fixnum)
    }
}

impl TryConvert<Value, Int> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: Value) -> Result<Int, Self::Error> {
        if let Ruby::Fixnum = value.ruby_type() {
            let inner = value.inner();
            Ok(unsafe { sys::mrb_sys_fixnum_to_cint(inner) })
        } else {
            Err(Exception::from(UnboxRubyError::new(
                &value,
                Rust::SignedInt,
            )))
        }
    }
}

impl TryConvert<Value, u32> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: Value) -> Result<u32, Self::Error> {
        if let Ruby::Fixnum = value.ruby_type() {
            let inner = value.inner();
            let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) };
            let num =
                u32::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?;
            Ok(num)
        } else {
            Err(Exception::from(UnboxRubyError::new(
                &value,
                Rust::SignedInt,
            )))
        }
    }
}

impl TryConvert<Value, usize> for Artichoke {
    type Error = Exception;

    fn try_convert(&self, value: Value) -> Result<usize, Self::Error> {
        if let Ruby::Fixnum = value.ruby_type() {
            let inner = value.inner();
            let num = unsafe { sys::mrb_sys_fixnum_to_cint(inner) };
            let num =
                usize::try_from(num).map_err(|_| UnboxRubyError::new(&value, Rust::UnsignedInt))?;
            Ok(num)
        } else {
            Err(Exception::from(UnboxRubyError::new(
                &value,
                Rust::SignedInt,
            )))
        }
    }
}

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

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

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

    #[quickcheck]
    fn convert_to_fixnum(i: Int) -> bool {
        let interp = interpreter().unwrap();
        let value = interp.convert(i);
        value.ruby_type() == Ruby::Fixnum
    }

    #[quickcheck]
    fn fixnum_with_value(i: Int) -> bool {
        let interp = interpreter().unwrap();
        let value = interp.convert(i);
        let inner = value.inner();
        let cint = unsafe { sys::mrb_sys_fixnum_to_cint(inner) };
        cint == i
    }

    #[quickcheck]
    fn roundtrip(i: Int) -> bool {
        let interp = interpreter().unwrap();
        let value = interp.convert(i);
        let value = value.try_into::<Int>(&interp).unwrap();
        value == i
    }

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

    #[test]
    fn fixnum_to_usize() {
        let interp = interpreter().unwrap();
        let value = Convert::<_, Value>::convert(&interp, 100);
        let value = value.try_into::<usize>(&interp).unwrap();
        assert_eq!(100, value);
        let value = Convert::<_, Value>::convert(&interp, -100);
        let value = value.try_into::<usize>(&interp);
        assert!(value.is_err());
    }
}