Austin Schuh | e89fa2d | 2019-08-14 20:24:23 -0700 | [diff] [blame^] | 1 | /* |
| 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 | |
| 17 | use std::cmp::max; |
| 18 | use std::mem::{align_of, size_of}; |
| 19 | |
| 20 | use 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. |
| 25 | pub 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). |
| 40 | pub struct PushAlignment(usize); |
| 41 | impl 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. |
| 57 | macro_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 | |
| 70 | impl_push_for_endian_scalar!(bool); |
| 71 | impl_push_for_endian_scalar!(u8); |
| 72 | impl_push_for_endian_scalar!(i8); |
| 73 | impl_push_for_endian_scalar!(u16); |
| 74 | impl_push_for_endian_scalar!(i16); |
| 75 | impl_push_for_endian_scalar!(u32); |
| 76 | impl_push_for_endian_scalar!(i32); |
| 77 | impl_push_for_endian_scalar!(u64); |
| 78 | impl_push_for_endian_scalar!(i64); |
| 79 | impl_push_for_endian_scalar!(f32); |
| 80 | impl_push_for_endian_scalar!(f64); |