blob: 186305894ceaa554b9fbfe1bc9ecb95c4ce8a3f4 [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::cmp::max;
18use std::mem::{align_of, size_of};
19
20use endian_scalar::emplace_scalar;
21
22/// Trait to abstract over functionality needed to write values (either owned
23/// or referenced). Used in FlatBufferBuilder and implemented for generated
24/// types.
25pub trait Push: Sized {
26 type Output;
27 fn push(&self, dst: &mut [u8], _rest: &[u8]);
28 #[inline]
29 fn size() -> usize {
30 size_of::<Self::Output>()
31 }
32 #[inline]
33 fn alignment() -> PushAlignment {
34 PushAlignment::new(align_of::<Self::Output>())
35 }
36}
37
38/// Ensure Push alignment calculations are typesafe (because this helps reduce
39/// implementation issues when using FlatBufferBuilder::align).
40pub struct PushAlignment(usize);
41impl PushAlignment {
42 #[inline]
43 pub fn new(x: usize) -> Self {
44 PushAlignment { 0: x }
45 }
46 #[inline]
47 pub fn value(&self) -> usize {
48 self.0
49 }
50 #[inline]
51 pub fn max_of(&self, o: usize) -> Self {
52 PushAlignment::new(max(self.0, o))
53 }
54}
55
56/// Macro to implement Push for EndianScalar types.
57macro_rules! impl_push_for_endian_scalar {
58 ($ty:ident) => {
59 impl Push for $ty {
60 type Output = $ty;
61
62 #[inline]
63 fn push(&self, dst: &mut [u8], _rest: &[u8]) {
64 emplace_scalar::<$ty>(dst, *self);
65 }
66 }
67 };
68}
69
70impl_push_for_endian_scalar!(bool);
71impl_push_for_endian_scalar!(u8);
72impl_push_for_endian_scalar!(i8);
73impl_push_for_endian_scalar!(u16);
74impl_push_for_endian_scalar!(i16);
75impl_push_for_endian_scalar!(u32);
76impl_push_for_endian_scalar!(i32);
77impl_push_for_endian_scalar!(u64);
78impl_push_for_endian_scalar!(i64);
79impl_push_for_endian_scalar!(f32);
80impl_push_for_endian_scalar!(f64);