Skip to content

Commit

Permalink
chore: make NeptuneCoins more human friendly.
Browse files Browse the repository at this point in the history
1. Adds a Debug impl that displays to_string() value.  Useful when
reading failed assertions about coin amounts.

2. Adds From<u8>, From<u16>, From<u32> infallible conversions.
Makes it easy to do things like 42u8.into()
  • Loading branch information
dan-da committed Jul 30, 2024
1 parent d177cca commit 7d2b89e
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/models/blockchain/type_scripts/neptune_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ use tasm_lib::{structure::tasm_object::TasmObject, twenty_first::math::bfield_co
/// program related to block validity, it is important to use `safe_add` rather than `+` as
/// the latter operation does not care about overflow. Not testing for overflow can cause
/// inflation bugs.
#[derive(Clone, Copy, Debug, Serialize, Deserialize, Eq, BFieldCodec, TasmObject)]
#[derive(Clone, Copy, Serialize, Deserialize, Eq, BFieldCodec, TasmObject)]
pub struct NeptuneCoins(u128);

impl NeptuneCoins {
Expand Down Expand Up @@ -241,6 +241,24 @@ impl Zero for NeptuneCoins {
}
}

impl From<u32> for NeptuneCoins {
fn from(n: u32) -> NeptuneCoins {
Self::new(n)
}
}

impl From<u16> for NeptuneCoins {
fn from(n: u16) -> NeptuneCoins {
Self::new(n as u32)
}
}

impl From<u8> for NeptuneCoins {
fn from(n: u8) -> NeptuneCoins {
Self::new(n as u32)
}
}

impl FromStr for NeptuneCoins {
type Err = anyhow::Error;

Expand Down Expand Up @@ -319,6 +337,14 @@ impl Display for NeptuneCoins {
}
}

impl std::fmt::Debug for NeptuneCoins {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("NeptuneCoins")
.field(&self.to_string())
.finish()
}
}

pub fn pseudorandom_amount(seed: [u8; 32]) -> NeptuneCoins {
let mut rng: StdRng = SeedableRng::from_seed(seed);
let number: u128 = rng.gen::<u128>() >> 10;
Expand Down

0 comments on commit 7d2b89e

Please sign in to comment.