blob: 48cb83e2f9d217c2b3b5756dd37d9e41663244ab [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
2 * Copyright 2018 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
James Kuszmaul8e62b022022-03-22 09:33:25 -070016#![allow(clippy::wrong_self_convention)]
Austin Schuhe89fa2d2019-08-14 20:24:23 -070017
James Kuszmaul8e62b022022-03-22 09:33:25 -070018use core::mem::size_of;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080020mod private {
21 /// Types that are trivially transmutable are those where any combination of bits
22 /// represents a valid value of that type
23 ///
24 /// For example integral types are TriviallyTransmutable as all bit patterns are valid,
25 /// however, `bool` is not trivially transmutable as only `0` and `1` are valid
26 pub trait TriviallyTransmutable {}
27
28 impl TriviallyTransmutable for i8 {}
29 impl TriviallyTransmutable for i16 {}
30 impl TriviallyTransmutable for i32 {}
31 impl TriviallyTransmutable for i64 {}
32 impl TriviallyTransmutable for u8 {}
33 impl TriviallyTransmutable for u16 {}
34 impl TriviallyTransmutable for u32 {}
35 impl TriviallyTransmutable for u64 {}
36}
37
Austin Schuhe89fa2d2019-08-14 20:24:23 -070038/// Trait for values that must be stored in little-endian byte order, but
39/// might be represented in memory as big-endian. Every type that implements
40/// EndianScalar is a valid FlatBuffers scalar value.
41///
42/// The Rust stdlib does not provide a trait to represent scalars, so this trait
43/// serves that purpose, too.
44///
45/// Note that we do not use the num-traits crate for this, because it provides
46/// "too much". For example, num-traits provides i128 support, but that is an
47/// invalid FlatBuffers type.
48pub trait EndianScalar: Sized + PartialEq + Copy + Clone {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080049 type Scalar: private::TriviallyTransmutable;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070050
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080051 fn to_little_endian(self) -> Self::Scalar;
52
53 fn from_little_endian(v: Self::Scalar) -> Self;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070054}
55
56/// Macro for implementing an endian conversion using the stdlib `to_le` and
57/// `from_le` functions. This is used for integer types. It is not used for
58/// floats, because the `to_le` and `from_le` are not implemented for them in
59/// the stdlib.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080060macro_rules! impl_endian_scalar {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070061 ($ty:ident) => {
62 impl EndianScalar for $ty {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080063 type Scalar = Self;
64
Austin Schuhe89fa2d2019-08-14 20:24:23 -070065 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080066 fn to_little_endian(self) -> Self::Scalar {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070067 Self::to_le(self)
68 }
69 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080070 fn from_little_endian(v: Self::Scalar) -> Self {
71 Self::from_le(v)
Austin Schuhe89fa2d2019-08-14 20:24:23 -070072 }
73 }
74 };
75}
76
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080077impl_endian_scalar!(u8);
78impl_endian_scalar!(i8);
79impl_endian_scalar!(u16);
80impl_endian_scalar!(u32);
81impl_endian_scalar!(u64);
82impl_endian_scalar!(i16);
83impl_endian_scalar!(i32);
84impl_endian_scalar!(i64);
Austin Schuhe89fa2d2019-08-14 20:24:23 -070085
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080086impl EndianScalar for bool {
87 type Scalar = u8;
88
89 fn to_little_endian(self) -> Self::Scalar {
90 self as u8
91 }
92
93 fn from_little_endian(v: Self::Scalar) -> Self {
94 v != 0
95 }
96}
Austin Schuhe89fa2d2019-08-14 20:24:23 -070097
98impl EndianScalar for f32 {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080099 type Scalar = u32;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700100 /// Convert f32 from host endian-ness to little-endian.
101 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800102 fn to_little_endian(self) -> u32 {
103 // Floats and Ints have the same endianness on all supported platforms.
104 // <https://doc.rust-lang.org/std/primitive.f32.html#method.from_bits>
105 self.to_bits().to_le()
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700106 }
107 /// Convert f32 from little-endian to host endian-ness.
108 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800109 fn from_little_endian(v: u32) -> Self {
110 // Floats and Ints have the same endianness on all supported platforms.
111 // <https://doc.rust-lang.org/std/primitive.f32.html#method.from_bits>
112 f32::from_bits(u32::from_le(v))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700113 }
114}
115
116impl EndianScalar for f64 {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800117 type Scalar = u64;
118
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700119 /// Convert f64 from host endian-ness to little-endian.
120 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800121 fn to_little_endian(self) -> u64 {
122 // Floats and Ints have the same endianness on all supported platforms.
123 // <https://doc.rust-lang.org/std/primitive.f64.html#method.from_bits>
124 self.to_bits().to_le()
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700125 }
126 /// Convert f64 from little-endian to host endian-ness.
127 #[inline]
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800128 fn from_little_endian(v: u64) -> Self {
129 // Floats and Ints have the same endianness on all supported platforms.
130 // <https://doc.rust-lang.org/std/primitive.f64.html#method.from_bits>
131 f64::from_bits(u64::from_le(v))
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700132 }
133}
134
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700135/// Place an EndianScalar into the provided mutable byte slice. Performs
136/// endian conversion, if necessary.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700137/// # Safety
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800138/// Caller must ensure `s.len() >= size_of::<T>()`
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700139#[inline]
James Kuszmaul8e62b022022-03-22 09:33:25 -0700140pub unsafe fn emplace_scalar<T: EndianScalar>(s: &mut [u8], x: T) {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800141 let size = size_of::<T::Scalar>();
142 debug_assert!(
143 s.len() >= size,
144 "insufficient capacity for emplace_scalar, needed {} got {}",
145 size,
146 s.len()
147 );
148
James Kuszmaul8e62b022022-03-22 09:33:25 -0700149 let x_le = x.to_little_endian();
150 core::ptr::copy_nonoverlapping(
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800151 &x_le as *const T::Scalar as *const u8,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700152 s.as_mut_ptr() as *mut u8,
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800153 size,
James Kuszmaul8e62b022022-03-22 09:33:25 -0700154 );
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700155}
156
157/// Read an EndianScalar from the provided byte slice at the specified location.
158/// Performs endian conversion, if necessary.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700159/// # Safety
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800160/// Caller must ensure `s.len() >= loc + size_of::<T>()`.
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700161#[inline]
James Kuszmaul8e62b022022-03-22 09:33:25 -0700162pub unsafe fn read_scalar_at<T: EndianScalar>(s: &[u8], loc: usize) -> T {
163 read_scalar(&s[loc..])
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700164}
165
166/// Read an EndianScalar from the provided byte slice. Performs endian
167/// conversion, if necessary.
James Kuszmaul8e62b022022-03-22 09:33:25 -0700168/// # Safety
169/// Caller must ensure `s.len() > size_of::<T>()`.
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700170#[inline]
James Kuszmaul8e62b022022-03-22 09:33:25 -0700171pub unsafe fn read_scalar<T: EndianScalar>(s: &[u8]) -> T {
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800172 let size = size_of::<T::Scalar>();
173 debug_assert!(
174 s.len() >= size,
175 "insufficient capacity for emplace_scalar, needed {} got {}",
176 size,
177 s.len()
178 );
179
180 let mut mem = core::mem::MaybeUninit::<T::Scalar>::uninit();
James Kuszmaul8e62b022022-03-22 09:33:25 -0700181 // Since [u8] has alignment 1, we copy it into T which may have higher alignment.
James Kuszmaul3b15b0c2022-11-08 14:03:16 -0800182 core::ptr::copy_nonoverlapping(s.as_ptr(), mem.as_mut_ptr() as *mut u8, size);
183 T::from_little_endian(mem.assume_init())
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700184}