xref: /aosp_15_r20/external/flatbuffers/rust/flatbuffers/src/array.rs (revision 890232f25432b36107d06881e0a25aaa6b473652)
1 /*
2  * Copyright 2021 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 crate::follow::Follow;
18 use crate::vector::VectorIter;
19 use crate::EndianScalar;
20 use core::fmt::{Debug, Formatter, Result};
21 use core::marker::PhantomData;
22 use core::mem::size_of;
23 
24 #[derive(Copy, Clone)]
25 pub struct Array<'a, T: 'a, const N: usize>(&'a [u8], PhantomData<T>);
26 
27 impl<'a, T: 'a, const N: usize> Debug for Array<'a, T, N>
28 where
29     T: 'a + Follow<'a>,
30     <T as Follow<'a>>::Inner: Debug,
31 {
fmt(&self, f: &mut Formatter) -> Result32     fn fmt(&self, f: &mut Formatter) -> Result {
33         f.debug_list().entries(self.iter()).finish()
34     }
35 }
36 
37 #[allow(clippy::len_without_is_empty)]
38 #[allow(clippy::from_over_into)] // TODO(caspern): Go from From to Into.
39 impl<'a, T: 'a, const N: usize> Array<'a, T, N> {
40     #[inline(always)]
new(buf: &'a [u8]) -> Self41     pub fn new(buf: &'a [u8]) -> Self {
42         assert!(size_of::<T>() * N == buf.len());
43 
44         Array {
45             0: buf,
46             1: PhantomData,
47         }
48     }
49 
50     #[inline(always)]
len(&self) -> usize51     pub const fn len(&self) -> usize {
52         N
53     }
as_ptr(&self) -> *const u854     pub fn as_ptr(&self) -> *const u8 {
55         self.0.as_ptr()
56     }
57 }
58 
59 impl<'a, T: Follow<'a> + 'a, const N: usize> Array<'a, T, N> {
60     #[inline(always)]
get(&self, idx: usize) -> T::Inner61     pub fn get(&self, idx: usize) -> T::Inner {
62         assert!(idx < N);
63         let sz = size_of::<T>();
64         T::follow(self.0, sz * idx)
65     }
66 
67     #[inline(always)]
iter(&self) -> VectorIter<'a, T>68     pub fn iter(&self) -> VectorIter<'a, T> {
69         VectorIter::from_slice(self.0, self.len())
70     }
71 }
72 
73 impl<'a, T: Follow<'a> + Debug, const N: usize> Into<[T::Inner; N]> for Array<'a, T, N> {
74     #[inline(always)]
into(self) -> [T::Inner; N]75     fn into(self) -> [T::Inner; N] {
76         array_init(|i| self.get(i))
77     }
78 }
79 
80 // TODO(caspern): Implement some future safe version of SafeSliceAccess.
81 
82 /// Implement Follow for all possible Arrays that have Follow-able elements.
83 impl<'a, T: Follow<'a> + 'a, const N: usize> Follow<'a> for Array<'a, T, N> {
84     type Inner = Array<'a, T, N>;
85     #[inline(always)]
follow(buf: &'a [u8], loc: usize) -> Self::Inner86     fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
87         Array::new(&buf[loc..loc + N * size_of::<T>()])
88     }
89 }
90 
emplace_scalar_array<T: EndianScalar, const N: usize>( buf: &mut [u8], loc: usize, src: &[T; N], )91 pub fn emplace_scalar_array<T: EndianScalar, const N: usize>(
92     buf: &mut [u8],
93     loc: usize,
94     src: &[T; N],
95 ) {
96     let mut buf_ptr = buf[loc..].as_mut_ptr();
97     for item in src.iter() {
98         let item_le = item.to_little_endian();
99         unsafe {
100             core::ptr::copy_nonoverlapping(
101                 &item_le as *const T as *const u8,
102                 buf_ptr,
103                 size_of::<T>(),
104             );
105             buf_ptr = buf_ptr.add(size_of::<T>());
106         }
107     }
108 }
109 
110 impl<'a, T: Follow<'a> + 'a, const N: usize> IntoIterator for Array<'a, T, N> {
111     type Item = T::Inner;
112     type IntoIter = VectorIter<'a, T>;
113     #[inline]
into_iter(self) -> Self::IntoIter114     fn into_iter(self) -> Self::IntoIter {
115         self.iter()
116     }
117 }
118 
119 #[inline]
array_init<F, T, const N: usize>(mut initializer: F) -> [T; N] where F: FnMut(usize) -> T,120 pub fn array_init<F, T, const N: usize>(mut initializer: F) -> [T; N]
121 where
122     F: FnMut(usize) -> T,
123 {
124     let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit();
125     let mut ptr_i = array.as_mut_ptr() as *mut T;
126 
127     unsafe {
128         for i in 0..N {
129             let value_i = initializer(i);
130             ptr_i.write(value_i);
131             ptr_i = ptr_i.add(1);
132         }
133         array.assume_init()
134     }
135 }
136 
137 #[cfg(feature="serialize")]
138 impl<'a, T: 'a, const N: usize> serde::ser::Serialize for Array<'a, T, N>
139 where
140     T: 'a + Follow<'a>,
141     <T as Follow<'a>>::Inner: serde::ser::Serialize,
142 {
serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> where S: serde::ser::Serializer,143     fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
144     where
145         S: serde::ser::Serializer,
146     {
147         use serde::ser::SerializeSeq;
148         let mut seq = serializer.serialize_seq(Some(self.len()))?;
149         for element in self.iter() {
150             seq.serialize_element(&element)?;
151         }
152         seq.end()
153     }
154 }
155