Skip to main content

diem_types/nibble/
mod.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4#![forbid(unsafe_code)]
5
6//! `Nibble` represents a four-bit unsigned integer.
7
8pub mod nibble_path;
9
10use diem_crypto::HashValue;
11#[cfg(any(test, feature = "fuzzing"))]
12use proptest::prelude::*;
13use serde::{Deserialize, Serialize};
14use std::fmt;
15
16/// The hardcoded maximum height of a state merkle tree in nibbles.
17pub const ROOT_NIBBLE_HEIGHT: usize = HashValue::LENGTH * 2;
18
19#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
20pub struct Nibble(u8);
21
22impl From<u8> for Nibble {
23    fn from(nibble: u8) -> Self {
24        assert!(nibble < 16, "Nibble out of range: {}", nibble);
25        Self(nibble)
26    }
27}
28
29impl From<Nibble> for u8 {
30    fn from(nibble: Nibble) -> Self {
31        nibble.0
32    }
33}
34
35impl fmt::LowerHex for Nibble {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        write!(f, "{:x}", self.0)
38    }
39}
40
41#[cfg(any(test, feature = "fuzzing"))]
42impl Arbitrary for Nibble {
43    type Parameters = ();
44    type Strategy = BoxedStrategy<Self>;
45
46    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
47        (0..16u8).prop_map(Self::from).boxed()
48    }
49}