zink/primitives/
bytes.rs

1//! Fixed bytes
2use crate::{asm, storage::Value};
3use paste::paste;
4
5macro_rules! impl_bytes {
6    ($count:expr) => {
7        paste! {
8            #[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
9            pub struct [<Bytes $count>] (
10                #[allow(unused)]
11                #[cfg(target_family = "wasm")] pub i32,
12                #[cfg(not(target_family = "wasm"))] pub [u8; $count],
13            );
14
15            impl [<Bytes $count>] {
16                /// Returns empty bytes
17                #[cfg(target_family = "wasm")]
18                pub const fn empty() -> Self {
19                    [<Bytes $count>](0)
20                }
21
22                #[cfg(not(target_family = "wasm"))]
23                pub const fn empty() -> Self {
24                    [<Bytes $count>]([0; $count])
25                }
26
27                /// if self equal to another
28                #[allow(clippy::should_implement_trait)]
29                #[inline(always)]
30                pub fn eq(self, other: Self) -> bool {
31                    paste::paste! {
32                        unsafe { asm::bytes::[< bytes $count _eq >](self, other) }
33                    }
34                }
35            }
36
37            impl Value for [<Bytes $count>] {
38                fn tload() -> Self {
39                    unsafe { asm::bytes::[<tload_bytes $count>]() }
40                }
41
42                fn sload() -> Self {
43                    unsafe { asm::bytes::[<sload_bytes $count>]() }
44                }
45
46                fn push(self) {
47                    unsafe { asm::bytes::[<push_bytes $count>](self) }
48                }
49
50                #[cfg(not(target_family = "wasm"))]
51                fn bytes32(&self) -> [u8; 32] {
52                    let mut output = [0; 32];
53                    output[(32-$count)..].copy_from_slice(&self.0);
54                    output
55                }
56            }
57        }
58    };
59    ($($count:expr),+) => {
60        $(impl_bytes!($count);)+
61    };
62}
63
64impl_bytes! {
65    2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
66    17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32
67}