Skip to content

Commit

Permalink
Merge pull request #1 from SiaFoundation/chris/deref-currency
Browse files Browse the repository at this point in the history
Implement deref, derefmut and asref for currency
  • Loading branch information
n8maninger authored Apr 5, 2024
2 parents 71cc5ed + 8cc8f14 commit 15597ec
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/currency.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::ops::{Add, Sub, Mul, Div};
use core::ops::{Add, Sub, Mul, Div, Deref, DerefMut};
use core::num::ParseIntError;

use crate::SiaEncodable;
Expand All @@ -12,6 +12,28 @@ const SIACOIN_PRECISION_U32: u32 = 24;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Currency(u128);

// Implement Deref and DerefMut to be able to implicitly use Currency as a u128
// This gives us all the traits that u128 already implements for free.
impl Deref for Currency {
type Target = u128;
fn deref(&self) -> &u128 { &self.0 }
}

impl DerefMut for Currency {
fn deref_mut(&mut self) -> &mut u128 { &mut self.0 }
}

// Implement AsRef as well to be able to implicitly obtain a &u128 from a Currency as well.
impl<T> AsRef<T> for Currency
where
T: ?Sized,
<Currency as Deref>::Target: AsRef<T>,
{
fn as_ref(&self) -> &T {
self.deref().as_ref()
}
}

impl Currency {
pub fn new(value: u128) -> Self {
Currency(value)
Expand Down

0 comments on commit 15597ec

Please sign in to comment.