blob: df0b384ad98432e7c287677d6ab1c194a075b16c [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 */
16
17use std::mem::size_of;
18
19/// Trait for values that must be stored in little-endian byte order, but
20/// might be represented in memory as big-endian. Every type that implements
21/// EndianScalar is a valid FlatBuffers scalar value.
22///
23/// The Rust stdlib does not provide a trait to represent scalars, so this trait
24/// serves that purpose, too.
25///
26/// Note that we do not use the num-traits crate for this, because it provides
27/// "too much". For example, num-traits provides i128 support, but that is an
28/// invalid FlatBuffers type.
29pub trait EndianScalar: Sized + PartialEq + Copy + Clone {
30 fn to_little_endian(self) -> Self;
31 fn from_little_endian(self) -> Self;
32}
33
34/// Macro for implementing a no-op endian conversion. This is used for types
35/// that are one byte wide.
36macro_rules! impl_endian_scalar_noop {
37 ($ty:ident) => {
38 impl EndianScalar for $ty {
39 #[inline]
40 fn to_little_endian(self) -> Self {
41 self
42 }
43 #[inline]
44 fn from_little_endian(self) -> Self {
45 self
46 }
47 }
48 };
49}
50
51/// Macro for implementing an endian conversion using the stdlib `to_le` and
52/// `from_le` functions. This is used for integer types. It is not used for
53/// floats, because the `to_le` and `from_le` are not implemented for them in
54/// the stdlib.
55macro_rules! impl_endian_scalar_stdlib_le_conversion {
56 ($ty:ident) => {
57 impl EndianScalar for $ty {
58 #[inline]
59 fn to_little_endian(self) -> Self {
60 Self::to_le(self)
61 }
62 #[inline]
63 fn from_little_endian(self) -> Self {
64 Self::from_le(self)
65 }
66 }
67 };
68}
69
70impl_endian_scalar_noop!(bool);
71impl_endian_scalar_noop!(u8);
72impl_endian_scalar_noop!(i8);
73
74impl_endian_scalar_stdlib_le_conversion!(u16);
75impl_endian_scalar_stdlib_le_conversion!(u32);
76impl_endian_scalar_stdlib_le_conversion!(u64);
77impl_endian_scalar_stdlib_le_conversion!(i16);
78impl_endian_scalar_stdlib_le_conversion!(i32);
79impl_endian_scalar_stdlib_le_conversion!(i64);
80
81impl EndianScalar for f32 {
82 /// Convert f32 from host endian-ness to little-endian.
83 #[inline]
84 fn to_little_endian(self) -> Self {
85 #[cfg(target_endian = "little")]
86 {
87 self
88 }
89 #[cfg(not(target_endian = "little"))]
90 {
91 byte_swap_f32(self)
92 }
93 }
94 /// Convert f32 from little-endian to host endian-ness.
95 #[inline]
96 fn from_little_endian(self) -> Self {
97 #[cfg(target_endian = "little")]
98 {
99 self
100 }
101 #[cfg(not(target_endian = "little"))]
102 {
103 byte_swap_f32(self)
104 }
105 }
106}
107
108impl EndianScalar for f64 {
109 /// Convert f64 from host endian-ness to little-endian.
110 #[inline]
111 fn to_little_endian(self) -> Self {
112 #[cfg(target_endian = "little")]
113 {
114 self
115 }
116 #[cfg(not(target_endian = "little"))]
117 {
118 byte_swap_f64(self)
119 }
120 }
121 /// Convert f64 from little-endian to host endian-ness.
122 #[inline]
123 fn from_little_endian(self) -> Self {
124 #[cfg(target_endian = "little")]
125 {
126 self
127 }
128 #[cfg(not(target_endian = "little"))]
129 {
130 byte_swap_f64(self)
131 }
132 }
133}
134
135/// Swaps the bytes of an f32.
136#[allow(dead_code)]
137#[inline]
138pub fn byte_swap_f32(x: f32) -> f32 {
139 f32::from_bits(x.to_bits().swap_bytes())
140}
141
142/// Swaps the bytes of an f64.
143#[allow(dead_code)]
144#[inline]
145pub fn byte_swap_f64(x: f64) -> f64 {
146 f64::from_bits(x.to_bits().swap_bytes())
147}
148
149/// Place an EndianScalar into the provided mutable byte slice. Performs
150/// endian conversion, if necessary.
151#[inline]
152pub fn emplace_scalar<T: EndianScalar>(s: &mut [u8], x: T) {
153 let sz = size_of::<T>();
154 let mut_ptr = (&mut s[..sz]).as_mut_ptr() as *mut T;
155 let val = x.to_little_endian();
156 unsafe {
157 *mut_ptr = val;
158 }
159}
160
161/// Read an EndianScalar from the provided byte slice at the specified location.
162/// Performs endian conversion, if necessary.
163#[inline]
164pub fn read_scalar_at<T: EndianScalar>(s: &[u8], loc: usize) -> T {
165 let buf = &s[loc..loc + size_of::<T>()];
166 read_scalar(buf)
167}
168
169/// Read an EndianScalar from the provided byte slice. Performs endian
170/// conversion, if necessary.
171#[inline]
172pub fn read_scalar<T: EndianScalar>(s: &[u8]) -> T {
173 let sz = size_of::<T>();
174
175 let p = (&s[..sz]).as_ptr() as *const T;
176 let x = unsafe { *p };
177
178 x.from_little_endian()
179}