forked from matsadler/magnus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtry_convert.rs
339 lines (303 loc) · 9.01 KB
/
try_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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
//! Traits for converting from Ruby [`Value`]s to Rust types.
use std::path::PathBuf;
use rb_sys::{rb_get_path, rb_num2dbl};
use seq_macro::seq;
#[cfg(ruby_use_flonum)]
use crate::value::Flonum;
use crate::{
error::{protect, Error},
integer::Integer,
r_array::RArray,
r_hash::RHash,
r_string::RString,
value::{Fixnum, ReprValue, Value},
Ruby,
};
/// Conversions from [`Value`] to Rust types.
pub trait TryConvert: Sized {
/// Convert `val` into `Self`.
fn try_convert(val: Value) -> Result<Self, Error>;
}
/// Conversions from [`Value`] to Rust types that do not contain [`Value`].
///
/// This trait is used as a bound on some implementations of [`TryConvert`]
/// (for example, for [`Vec`]) to prevent heap allocated datastructures
/// containing `Value`, as it is not safe to store a `Value` on the heap.
///
/// # Safety
///
/// This trait must not be implemented for types that contain `Value`.
pub unsafe trait TryConvertOwned: TryConvert {}
impl<T> TryConvert for Option<T>
where
T: TryConvert,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
(!val.is_nil()).then(|| T::try_convert(val)).transpose()
}
}
unsafe impl<T> TryConvertOwned for Option<T> where T: TryConvertOwned {}
impl TryConvert for bool {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Ok(val.to_bool())
}
}
unsafe impl TryConvertOwned for bool {}
impl TryConvert for i8 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_i8()
}
}
unsafe impl TryConvertOwned for i8 {}
impl TryConvert for i16 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_i16()
}
}
unsafe impl TryConvertOwned for i16 {}
impl TryConvert for i32 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_i32()
}
}
unsafe impl TryConvertOwned for i32 {}
impl TryConvert for i64 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_i64()
}
}
unsafe impl TryConvertOwned for i64 {}
impl TryConvert for isize {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_isize()
}
}
unsafe impl TryConvertOwned for isize {}
impl TryConvert for u8 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_u8()
}
}
unsafe impl TryConvertOwned for u8 {}
impl TryConvert for u16 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_u16()
}
}
unsafe impl TryConvertOwned for u16 {}
impl TryConvert for u32 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_u32()
}
}
unsafe impl TryConvertOwned for u32 {}
impl TryConvert for u64 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_u64()
}
}
unsafe impl TryConvertOwned for u64 {}
impl TryConvert for usize {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
Integer::try_convert(val)?.to_usize()
}
}
unsafe impl TryConvertOwned for usize {}
macro_rules! impl_non_zero_try_convert {
($type:ty, $prim:ty) => {
impl TryConvert for $type {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
<$type>::new(<$prim>::try_convert(val)?).ok_or(Error::new(
Ruby::get_with(val).exception_arg_error(),
"value must be non-zero",
))
}
}
unsafe impl TryConvertOwned for $type {}
};
}
impl_non_zero_try_convert!(std::num::NonZeroI8, i8);
impl_non_zero_try_convert!(std::num::NonZeroI16, i16);
impl_non_zero_try_convert!(std::num::NonZeroI32, i32);
impl_non_zero_try_convert!(std::num::NonZeroI64, i64);
impl_non_zero_try_convert!(std::num::NonZeroIsize, isize);
impl_non_zero_try_convert!(std::num::NonZeroU8, u8);
impl_non_zero_try_convert!(std::num::NonZeroU16, u16);
impl_non_zero_try_convert!(std::num::NonZeroU32, u32);
impl_non_zero_try_convert!(std::num::NonZeroU64, u64);
impl_non_zero_try_convert!(std::num::NonZeroUsize, usize);
impl TryConvert for f32 {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
f64::try_convert(val).map(|f| f as f32)
}
}
unsafe impl TryConvertOwned for f32 {}
impl TryConvert for f64 {
fn try_convert(val: Value) -> Result<Self, Error> {
if let Some(fixnum) = Fixnum::from_value(val) {
return Ok(fixnum.to_isize() as f64);
}
#[cfg(ruby_use_flonum)]
if let Some(flonum) = Flonum::from_value(val) {
return Ok(flonum.to_f64());
}
debug_assert_value!(val);
let mut res = 0.0;
protect(|| {
unsafe { res = rb_num2dbl(val.as_rb_value()) };
Ruby::get_with(val).qnil()
})?;
Ok(res)
}
}
unsafe impl TryConvertOwned for f64 {}
impl TryConvert for String {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RString::try_convert(val)?.to_string()
}
}
unsafe impl TryConvertOwned for String {}
#[cfg(feature = "bytes")]
impl TryConvert for bytes::Bytes {
#[inline]
fn try_convert(val: Value) -> Result<bytes::Bytes, Error> {
debug_assert_value!(val);
Ok(RString::try_convert(val)?.to_bytes())
}
}
#[cfg(feature = "bytes")]
unsafe impl TryConvertOwned for bytes::Bytes {}
impl TryConvert for char {
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RString::try_convert(val)?.to_char()
}
}
unsafe impl TryConvertOwned for char {}
impl<T> TryConvert for Vec<T>
where
T: TryConvertOwned,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RArray::try_convert(val)?.to_vec()
}
}
unsafe impl<T> TryConvertOwned for Vec<T> where T: TryConvertOwned {}
impl<T, const N: usize> TryConvert for [T; N]
where
T: TryConvert,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RArray::try_convert(val)?.to_array()
}
}
unsafe impl<T, const N: usize> TryConvertOwned for [T; N] where T: TryConvert {}
macro_rules! impl_try_convert {
($n:literal) => {
seq!(N in 0..$n {
impl<#(T~N,)*> TryConvert for (#(T~N,)*)
where
#(T~N: TryConvert,)*
{
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
let array = RArray::try_convert(val)?;
let slice = unsafe { array.as_slice() };
if slice.len() != $n {
return Err(Error::new(
Ruby::get_with(val).exception_type_error(),
concat!("expected Array of length ", $n),
));
}
Ok((
#(TryConvert::try_convert(slice[N])?,)*
))
}
}
unsafe impl<#(T~N,)*> TryConvertOwned for (#(T~N,)*)
where
#(T~N: TryConvertOwned,)*
{
}
});
}
}
seq!(N in 1..=12 {
impl_try_convert!(N);
});
impl<K, V> TryConvert for std::collections::HashMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash,
V: TryConvertOwned,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RHash::try_convert(val)?.to_hash_map()
}
}
unsafe impl<K, V> TryConvertOwned for std::collections::HashMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash,
V: TryConvertOwned,
{
}
impl<K, V> TryConvert for std::collections::BTreeMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash + Ord,
V: TryConvertOwned,
{
#[inline]
fn try_convert(val: Value) -> Result<Self, Error> {
debug_assert_value!(val);
RHash::try_convert(val)?.to_btree_map()
}
}
unsafe impl<K, V> TryConvertOwned for std::collections::BTreeMap<K, V>
where
K: TryConvertOwned + Eq + std::hash::Hash + Ord,
V: TryConvertOwned,
{
}
#[cfg(unix)]
impl TryConvert for PathBuf {
fn try_convert(val: Value) -> Result<Self, Error> {
use std::os::unix::ffi::OsStringExt;
let bytes = unsafe {
let r_string =
protect(|| RString::from_rb_value_unchecked(rb_get_path(val.as_rb_value())))?;
r_string.as_slice().to_owned()
};
Ok(std::ffi::OsString::from_vec(bytes).into())
}
}
#[cfg(not(unix))]
impl TryConvert for PathBuf {
fn try_convert(val: Value) -> Result<Self, Error> {
protect(|| unsafe { RString::from_rb_value_unchecked(rb_get_path(val.as_rb_value())) })?
.to_string()
.map(Into::into)
}
}
unsafe impl TryConvertOwned for PathBuf {}