blob: 2ce2e4713376b5f5c66b1a746228b844f5aeb7f0 [file] [log] [blame]
James Kuszmaul8e62b022022-03-22 09:33:25 -07001/*
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
17use crate::follow::Follow;
18use crate::vector::VectorIter;
19use crate::EndianScalar;
20use core::fmt::{Debug, Formatter, Result};
21use core::marker::PhantomData;
22use core::mem::size_of;
23
24#[derive(Copy, Clone)]
25pub struct Array<'a, T: 'a, const N: usize>(&'a [u8], PhantomData<T>);
26
27impl<'a, T: 'a, const N: usize> Debug for Array<'a, T, N>
28where
29 T: 'a + Follow<'a>,
30 <T as Follow<'a>>::Inner: Debug,
31{
32 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.
39impl<'a, T: 'a, const N: usize> Array<'a, T, N> {
40 #[inline(always)]
41 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)]
51 pub const fn len(&self) -> usize {
52 N
53 }
54 pub fn as_ptr(&self) -> *const u8 {
55 self.0.as_ptr()
56 }
57}
58
59impl<'a, T: Follow<'a> + 'a, const N: usize> Array<'a, T, N> {
60 #[inline(always)]
61 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)]
68 pub fn iter(&self) -> VectorIter<'a, T> {
69 VectorIter::from_slice(self.0, self.len())
70 }
71}
72
73impl<'a, T: Follow<'a> + Debug, const N: usize> Into<[T::Inner; N]> for Array<'a, T, N> {
74 #[inline(always)]
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.
83impl<'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)]
86 fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
87 Array::new(&buf[loc..loc + N * size_of::<T>()])
88 }
89}
90
91pub 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
110impl<'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]
114 fn into_iter(self) -> Self::IntoIter {
115 self.iter()
116 }
117}
118
119#[inline]
120pub fn array_init<F, T, const N: usize>(mut initializer: F) -> [T; N]
121where
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")]
138impl<'a, T: 'a, const N: usize> serde::ser::Serialize for Array<'a, T, N>
139where
140 T: 'a + Follow<'a>,
141 <T as Follow<'a>>::Inner: serde::ser::Serialize,
142{
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}