arrow_buffer/
native.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::{i256, IntervalDayTime, IntervalMonthDayNano};
use half::f16;

mod private {
    pub trait Sealed {}
}

/// Trait expressing a Rust type that has the same in-memory representation as
/// Arrow.
///
/// This includes `i16`, `f32`, but excludes `bool` (which in arrow is
/// represented in bits).
///
/// In little endian machines, types that implement [`ArrowNativeType`] can be
/// memcopied to arrow buffers as is.
///
/// # Transmute Safety
///
/// A type T implementing this trait means that any arbitrary slice of bytes of length and
/// alignment `size_of::<T>()` can be safely interpreted as a value of that type without
/// being unsound, i.e. potentially resulting in undefined behaviour.
///
/// Note: in the case of floating point numbers this transmutation can result in a signalling
/// NaN, which, whilst sound, can be unwieldy. In general, whilst it is perfectly sound to
/// reinterpret bytes as different types using this trait, it is likely unwise. For more information
/// see [f32::from_bits] and [f64::from_bits].
///
/// Note: `bool` is restricted to `0` or `1`, and so `bool: !ArrowNativeType`
///
/// # Sealed
///
/// Due to the above restrictions, this trait is sealed to prevent accidental misuse
pub trait ArrowNativeType:
    std::fmt::Debug + Send + Sync + Copy + PartialOrd + Default + private::Sealed + 'static
{
    /// Returns the byte width of this native type.
    fn get_byte_width() -> usize {
        std::mem::size_of::<Self>()
    }

    /// Convert native integer type from usize
    ///
    /// Returns `None` if [`Self`] is not an integer or conversion would result
    /// in truncation/overflow
    fn from_usize(_: usize) -> Option<Self>;

    /// Convert to usize according to the [`as`] operator
    ///
    /// [`as`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast
    fn as_usize(self) -> usize;

    /// Convert from usize according to the [`as`] operator
    ///
    /// [`as`]: https://doc.rust-lang.org/reference/expressions/operator-expr.html#numeric-cast
    fn usize_as(i: usize) -> Self;

    /// Convert native type to usize.
    ///
    /// Returns `None` if [`Self`] is not an integer or conversion would result
    /// in truncation/overflow
    fn to_usize(self) -> Option<usize>;

    /// Convert native type to isize.
    ///
    /// Returns `None` if [`Self`] is not an integer or conversion would result
    /// in truncation/overflow
    fn to_isize(self) -> Option<isize>;

    /// Convert native type to i64.
    ///
    /// Returns `None` if [`Self`] is not an integer or conversion would result
    /// in truncation/overflow
    fn to_i64(self) -> Option<i64>;

    /// Convert native type from i32.
    ///
    /// Returns `None` if [`Self`] is not `i32`
    #[deprecated(note = "please use `Option::Some` instead")]
    fn from_i32(_: i32) -> Option<Self> {
        None
    }

    /// Convert native type from i64.
    ///
    /// Returns `None` if [`Self`] is not `i64`
    #[deprecated(note = "please use `Option::Some` instead")]
    fn from_i64(_: i64) -> Option<Self> {
        None
    }

    /// Convert native type from i128.
    ///
    /// Returns `None` if [`Self`] is not `i128`
    #[deprecated(note = "please use `Option::Some` instead")]
    fn from_i128(_: i128) -> Option<Self> {
        None
    }
}

macro_rules! native_integer {
    ($t: ty $(, $from:ident)*) => {
        impl private::Sealed for $t {}
        impl ArrowNativeType for $t {
            #[inline]
            fn from_usize(v: usize) -> Option<Self> {
                v.try_into().ok()
            }

            #[inline]
            fn to_usize(self) -> Option<usize> {
                self.try_into().ok()
            }

            #[inline]
            fn to_isize(self) -> Option<isize> {
                self.try_into().ok()
            }

            #[inline]
            fn to_i64(self) -> Option<i64> {
                self.try_into().ok()
            }

            #[inline]
            fn as_usize(self) -> usize {
                self as _
            }

            #[inline]
            fn usize_as(i: usize) -> Self {
                i as _
            }


            $(
                #[inline]
                fn $from(v: $t) -> Option<Self> {
                    Some(v)
                }
            )*
        }
    };
}

native_integer!(i8);
native_integer!(i16);
native_integer!(i32, from_i32);
native_integer!(i64, from_i64);
native_integer!(i128, from_i128);
native_integer!(u8);
native_integer!(u16);
native_integer!(u32);
native_integer!(u64);
native_integer!(u128);

macro_rules! native_float {
    ($t:ty, $s:ident, $as_usize: expr, $i:ident, $usize_as: expr) => {
        impl private::Sealed for $t {}
        impl ArrowNativeType for $t {
            #[inline]
            fn from_usize(_: usize) -> Option<Self> {
                None
            }

            #[inline]
            fn to_usize(self) -> Option<usize> {
                None
            }

            #[inline]
            fn to_isize(self) -> Option<isize> {
                None
            }

            #[inline]
            fn to_i64(self) -> Option<i64> {
                None
            }

            #[inline]
            fn as_usize($s) -> usize {
                $as_usize
            }

            #[inline]
            fn usize_as($i: usize) -> Self {
                $usize_as
            }
        }
    };
}

native_float!(f16, self, self.to_f32() as _, i, f16::from_f32(i as _));
native_float!(f32, self, self as _, i, i as _);
native_float!(f64, self, self as _, i, i as _);

impl private::Sealed for i256 {}
impl ArrowNativeType for i256 {
    fn from_usize(u: usize) -> Option<Self> {
        Some(Self::from_parts(u as u128, 0))
    }

    fn as_usize(self) -> usize {
        self.to_parts().0 as usize
    }

    fn usize_as(i: usize) -> Self {
        Self::from_parts(i as u128, 0)
    }

    fn to_usize(self) -> Option<usize> {
        let (low, high) = self.to_parts();
        if high != 0 {
            return None;
        }
        low.try_into().ok()
    }

    fn to_isize(self) -> Option<isize> {
        self.to_i128()?.try_into().ok()
    }

    fn to_i64(self) -> Option<i64> {
        self.to_i128()?.try_into().ok()
    }
}

impl private::Sealed for IntervalMonthDayNano {}
impl ArrowNativeType for IntervalMonthDayNano {
    fn from_usize(_: usize) -> Option<Self> {
        None
    }

    fn as_usize(self) -> usize {
        ((self.months as u64) | ((self.days as u64) << 32)) as usize
    }

    fn usize_as(i: usize) -> Self {
        Self::new(i as _, ((i as u64) >> 32) as _, 0)
    }

    fn to_usize(self) -> Option<usize> {
        None
    }

    fn to_isize(self) -> Option<isize> {
        None
    }

    fn to_i64(self) -> Option<i64> {
        None
    }
}

impl private::Sealed for IntervalDayTime {}
impl ArrowNativeType for IntervalDayTime {
    fn from_usize(_: usize) -> Option<Self> {
        None
    }

    fn as_usize(self) -> usize {
        ((self.days as u64) | ((self.milliseconds as u64) << 32)) as usize
    }

    fn usize_as(i: usize) -> Self {
        Self::new(i as _, ((i as u64) >> 32) as _)
    }

    fn to_usize(self) -> Option<usize> {
        None
    }

    fn to_isize(self) -> Option<isize> {
        None
    }

    fn to_i64(self) -> Option<i64> {
        None
    }
}

/// Allows conversion from supported Arrow types to a byte slice.
pub trait ToByteSlice {
    /// Converts this instance into a byte slice
    fn to_byte_slice(&self) -> &[u8];
}

impl<T: ArrowNativeType> ToByteSlice for [T] {
    #[inline]
    fn to_byte_slice(&self) -> &[u8] {
        let raw_ptr = self.as_ptr() as *const u8;
        unsafe { std::slice::from_raw_parts(raw_ptr, std::mem::size_of_val(self)) }
    }
}

impl<T: ArrowNativeType> ToByteSlice for T {
    #[inline]
    fn to_byte_slice(&self) -> &[u8] {
        let raw_ptr = self as *const T as *const u8;
        unsafe { std::slice::from_raw_parts(raw_ptr, std::mem::size_of::<T>()) }
    }
}

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

    #[test]
    fn test_i256() {
        let a = i256::from_parts(0, 0);
        assert_eq!(a.as_usize(), 0);
        assert_eq!(a.to_usize().unwrap(), 0);
        assert_eq!(a.to_isize().unwrap(), 0);

        let a = i256::from_parts(0, -1);
        assert_eq!(a.as_usize(), 0);
        assert!(a.to_usize().is_none());
        assert!(a.to_usize().is_none());

        let a = i256::from_parts(u128::MAX, -1);
        assert_eq!(a.as_usize(), usize::MAX);
        assert!(a.to_usize().is_none());
        assert_eq!(a.to_isize().unwrap(), -1);
    }

    #[test]
    fn test_interval_usize() {
        assert_eq!(IntervalDayTime::new(1, 0).as_usize(), 1);
        assert_eq!(IntervalMonthDayNano::new(1, 0, 0).as_usize(), 1);

        let a = IntervalDayTime::new(23, 53);
        let b = IntervalDayTime::usize_as(a.as_usize());
        assert_eq!(a, b);

        let a = IntervalMonthDayNano::new(23, 53, 0);
        let b = IntervalMonthDayNano::usize_as(a.as_usize());
        assert_eq!(a, b);
    }
}