blob: 8bb8fe9a7df529b80945364ff7c6ff06c2029b28 [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
James Kuszmaul8e62b022022-03-22 09:33:25 -070017use core::cmp::max;
18use core::mem::{align_of, size_of};
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019
Austin Schuh272c6132020-11-14 16:37:52 -080020use crate::endian_scalar::emplace_scalar;
Austin Schuhe89fa2d2019-08-14 20:24:23 -070021
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]) {
James Kuszmaul8e62b022022-03-22 09:33:25 -070064 unsafe {
65 emplace_scalar::<$ty>(dst, *self);
66 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -070067 }
68 }
69 };
70}
71
72impl_push_for_endian_scalar!(bool);
73impl_push_for_endian_scalar!(u8);
74impl_push_for_endian_scalar!(i8);
75impl_push_for_endian_scalar!(u16);
76impl_push_for_endian_scalar!(i16);
77impl_push_for_endian_scalar!(u32);
78impl_push_for_endian_scalar!(i32);
79impl_push_for_endian_scalar!(u64);
80impl_push_for_endian_scalar!(i64);
81impl_push_for_endian_scalar!(f32);
82impl_push_for_endian_scalar!(f64);