diem_nibble/
lib.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8#![forbid(unsafe_code)]
9
10//! `Nibble` represents a four-bit unsigned integer.
11
12#[cfg(feature = "fuzzing")]
13use proptest::prelude::*;
14use serde::{Deserialize, Serialize};
15use std::fmt;
16
17#[derive(
18    Clone,
19    Copy,
20    Debug,
21    Hash,
22    Eq,
23    PartialEq,
24    Ord,
25    PartialOrd,
26    Serialize,
27    Deserialize,
28)]
29pub struct Nibble(u8);
30
31impl From<u8> for Nibble {
32    fn from(nibble: u8) -> Self {
33        assert!(nibble < 16, "Nibble out of range: {}", nibble);
34        Self(nibble)
35    }
36}
37
38impl From<Nibble> for u8 {
39    fn from(nibble: Nibble) -> Self { nibble.0 }
40}
41
42impl fmt::LowerHex for Nibble {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "{:x}", self.0)
45    }
46}
47
48#[cfg(feature = "fuzzing")]
49impl Arbitrary for Nibble {
50    type Parameters = ();
51    type Strategy = BoxedStrategy<Self>;
52
53    fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
54        (0..16u8).prop_map(Self::from).boxed()
55    }
56}