snarkvm_console_collections/kary_merkle_tree/helpers/
mod.rs

1// Copyright 2024 Aleo Network Foundation
2// This file is part of the snarkVM library.
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
16mod leaf_hash;
17pub use leaf_hash::*;
18
19mod path_hash;
20pub use path_hash::*;
21
22use snarkvm_console_types::prelude::*;
23
24#[derive(Copy, Clone, Debug, PartialEq, Eq)]
25pub struct BooleanHash<const VARIANT: usize>(pub [bool; VARIANT]);
26
27impl<const VARIANT: usize> BooleanHash<VARIANT> {
28    /// Initializes a new "empty" boolean hash.
29    pub const fn new() -> Self {
30        Self([false; VARIANT])
31    }
32}
33
34impl<const VARIANT: usize> Default for BooleanHash<VARIANT> {
35    /// Initializes a new "empty" boolean hash.
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl<const VARIANT: usize> Distribution<BooleanHash<VARIANT>> for Standard {
42    /// Returns a random boolean hash.
43    #[inline]
44    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> BooleanHash<VARIANT> {
45        let mut array = [false; VARIANT];
46        for entry in array.iter_mut() {
47            *entry = rng.gen();
48        }
49        BooleanHash(array)
50    }
51}
52
53impl<const VARIANT: usize> FromBytes for BooleanHash<VARIANT> {
54    /// Reads `self` from `reader` in little-endian order.
55    fn read_le<R: Read>(mut reader: R) -> IoResult<Self> {
56        // Read the bits.
57        let mut array = [false; VARIANT];
58        for bit in array.iter_mut() {
59            *bit = bool::read_le(&mut reader)?;
60        }
61        Ok(Self(array))
62    }
63}
64
65impl<const VARIANT: usize> ToBytes for BooleanHash<VARIANT> {
66    /// Writes `self` to `writer` in little-endian order.
67    fn write_le<W: Write>(&self, mut writer: W) -> IoResult<()> {
68        self.0.as_slice().write_le(&mut writer)
69    }
70}
71
72impl<const VARIANT: usize> Deref for BooleanHash<VARIANT> {
73    type Target = [bool; VARIANT];
74
75    fn deref(&self) -> &Self::Target {
76        &self.0
77    }
78}