1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
use crate::FixedBytes;
use alloc::vec::Vec;
use core::slice;
/// Extension trait for flattening a slice of `FixedBytes` to a byte slice.
///
/// This mirrors the standard library's `as_flattened` and `as_flattened_mut` methods for
/// `&[[T; N]]`.
pub trait FixedBytesSliceExt {
/// Takes a `&[FixedBytes<N>]` and flattens it to a `&[u8]`.
///
/// # Panics
///
/// This panics if the length of the resulting slice would overflow a `usize`.
///
/// This is only possible when `N == 0`, which tends to be irrelevant in practice.
///
/// # Examples
///
/// ```
/// use alloy_primitives::{FixedBytes, FixedBytesSliceExt};
///
/// let arr = [FixedBytes::<4>::new([1, 2, 3, 4]), FixedBytes::new([5, 6, 7, 8])];
/// assert_eq!(arr.as_flattened(), &[1, 2, 3, 4, 5, 6, 7, 8]);
/// ```
fn as_flattened(&self) -> &[u8];
/// Takes a `&mut [FixedBytes<N>]` and flattens it to a `&mut [u8]`.
///
/// # Panics
///
/// This panics if the length of the resulting slice would overflow a `usize`.
///
/// This is only possible when `N == 0`, which tends to be irrelevant in practice.
///
/// # Examples
///
/// ```
/// use alloy_primitives::{FixedBytes, FixedBytesSliceExt};
///
/// fn add_one(slice: &mut [u8]) {
/// for b in slice {
/// *b = b.wrapping_add(1);
/// }
/// }
///
/// let mut arr = [FixedBytes::<4>::new([1, 2, 3, 4]), FixedBytes::new([5, 6, 7, 8])];
/// add_one(arr.as_flattened_mut());
/// assert_eq!(arr[0].as_slice(), &[2, 3, 4, 5]);
/// ```
fn as_flattened_mut(&mut self) -> &mut [u8];
}
impl<const N: usize> FixedBytesSliceExt for [FixedBytes<N>] {
#[inline]
fn as_flattened(&self) -> &[u8] {
// SAFETY: `self.len() * N` cannot overflow because `self` is
// already in the address space.
let len = unsafe { self.len().unchecked_mul(N) };
// SAFETY: `FixedBytes<N>` is `repr(transparent)` over `[u8; N]`.
unsafe { slice::from_raw_parts(self.as_ptr().cast(), len) }
}
#[inline]
fn as_flattened_mut(&mut self) -> &mut [u8] {
// SAFETY: `self.len() * N` cannot overflow because `self` is
// already in the address space.
let len = unsafe { self.len().unchecked_mul(N) };
// SAFETY: `FixedBytes<N>` is `repr(transparent)` over `[u8; N]`.
unsafe { slice::from_raw_parts_mut(self.as_mut_ptr().cast(), len) }
}
}
/// Extension trait for flattening a `Vec` of `FixedBytes` to a `Vec<u8>`.
///
/// This mirrors the standard library's `into_flattened` method for `Vec<[T; N]>`.
pub trait FixedBytesVecExt {
/// Takes a `Vec<FixedBytes<N>>` and flattens it into a `Vec<u8>`.
///
/// # Panics
///
/// This panics if the length of the resulting vector would overflow a `usize`.
///
/// This is only possible when `N == 0`, which tends to be irrelevant in practice.
///
/// # Examples
///
/// ```
/// use alloy_primitives::{FixedBytes, FixedBytesVecExt};
///
/// let mut vec = vec![
/// FixedBytes::<4>::new([1, 2, 3, 4]),
/// FixedBytes::new([5, 6, 7, 8]),
/// FixedBytes::new([9, 10, 11, 12]),
/// ];
/// assert_eq!(vec.pop(), Some(FixedBytes::new([9, 10, 11, 12])));
///
/// let mut flattened = vec.into_flattened();
/// assert_eq!(flattened.pop(), Some(8));
/// ```
fn into_flattened(self) -> Vec<u8>;
}
impl<const N: usize> FixedBytesVecExt for Vec<FixedBytes<N>> {
#[inline]
fn into_flattened(self) -> Vec<u8> {
let mut this = core::mem::ManuallyDrop::new(self);
let (ptr, len, cap) = (this.as_mut_ptr(), this.len(), this.capacity());
// SAFETY:
// - `cap * N` cannot overflow because the allocation is already in
// the address space.
// - Each `[T; N]` has `N` valid elements, so there are `len * N`
// valid elements in the allocation.
let (new_len, new_cap) = unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) };
// SAFETY:
// - `ptr` was allocated by `self`
// - `ptr` is well-aligned because `FixedBytes<N>` has the same alignment as `u8` (since
// `FixedBytes<N>` is `repr(transparent)` over `[u8; N]`)
// - `new_cap * size_of::<u8>()` == `cap * size_of::<FixedBytes<N>>()`
// - `len <= cap`, so `len * N <= cap * N`
unsafe { Vec::from_raw_parts(ptr.cast(), new_len, new_cap) }
}
}
// Can't put in `wrap_fixed_bytes` macro due to orphan rules.
macro_rules! impl_flatten {
([$($gen:tt)*] $t:ty, $n:expr) => {
impl<$($gen)*> $crate::FixedBytesSliceExt for [$t] {
#[inline]
fn as_flattened(&self) -> &[u8] {
unsafe { core::mem::transmute::<&[$t], &[FixedBytes<$n>]>(self) }.as_flattened()
}
#[inline]
fn as_flattened_mut(&mut self) -> &mut [u8] {
unsafe { core::mem::transmute::<&mut [$t], &mut [FixedBytes<$n>]>(self) }
.as_flattened_mut()
}
}
impl<$($gen)*> $crate::FixedBytesVecExt for $crate::private::Vec<$t> {
#[inline]
fn into_flattened(self) -> $crate::private::Vec<u8> {
unsafe { core::mem::transmute::<Vec<$t>, Vec<FixedBytes<$n>>>(self) }
.into_flattened()
}
}
};
}
impl_flatten!([] crate::Address, 20);
impl_flatten!([] crate::Bloom, 256);
impl_flatten!([const BITS: usize, const LIMBS: usize] crate::Uint<BITS, LIMBS>, 32);
#[cfg(test)]
mod tests {
use super::*;
use crate::Address;
#[test]
fn test_as_flattened() {
let arr = [FixedBytes::<4>::new([1, 2, 3, 4]), FixedBytes::new([5, 6, 7, 8])];
assert_eq!(arr.as_flattened(), &[1, 2, 3, 4, 5, 6, 7, 8]);
}
#[test]
fn test_as_flattened_empty() {
let arr: [FixedBytes<4>; 0] = [];
assert!(arr.as_flattened().is_empty());
}
#[test]
fn test_as_flattened_mut() {
let mut arr = [FixedBytes::<4>::new([1, 2, 3, 4]), FixedBytes::new([5, 6, 7, 8])];
for b in arr.as_flattened_mut() {
*b = b.wrapping_add(1);
}
assert_eq!(arr[0].as_slice(), &[2, 3, 4, 5]);
assert_eq!(arr[1].as_slice(), &[6, 7, 8, 9]);
}
#[test]
fn test_into_flattened() {
let vec = vec![FixedBytes::<4>::new([1, 2, 3, 4]), FixedBytes::new([5, 6, 7, 8])];
assert_eq!(vec.into_flattened(), vec![1, 2, 3, 4, 5, 6, 7, 8]);
}
#[test]
fn test_into_flattened_empty() {
let vec: Vec<FixedBytes<4>> = vec![];
assert!(vec.into_flattened().is_empty());
}
#[test]
fn test_address_as_flattened() {
let arr = [Address::repeat_byte(0x11), Address::repeat_byte(0x22)];
let flattened = arr.as_flattened();
assert_eq!(flattened.len(), 40);
assert_eq!(&flattened[..20], &[0x11; 20]);
assert_eq!(&flattened[20..], &[0x22; 20]);
}
#[test]
fn test_address_as_flattened_mut() {
let mut arr = [Address::repeat_byte(0x11), Address::repeat_byte(0x22)];
arr.as_flattened_mut()[0] = 0xff;
assert_eq!(arr[0].0[0], 0xff);
}
#[test]
fn test_address_into_flattened() {
let vec = vec![Address::repeat_byte(0x11), Address::repeat_byte(0x22)];
let flattened = vec.into_flattened();
assert_eq!(flattened.len(), 40);
assert_eq!(&flattened[..20], &[0x11; 20]);
assert_eq!(&flattened[20..], &[0x22; 20]);
}
}