Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement deref, derefmut and asref for currency #1

Merged
merged 2 commits into from
Apr 5, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 23 additions & 33 deletions src/currency.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use core::ops::{Add, Sub, Mul, Div};
use core::num::ParseIntError;
use std::ops::{Deref, DerefMut};

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 Expand Up @@ -98,38 +120,6 @@ impl Currency {
}
}

impl Add for Currency {
type Output = Self;

fn add(self, other: Self) -> Self {
Self(self.0 + other.0)
}
}

impl Sub for Currency {
type Output = Self;

fn sub(self, other: Self) -> Self {
Self(self.0 - other.0)
}
}

impl Mul for Currency {
type Output = Self;

fn mul(self, other: Self) -> Self {
Self(self.0 * other.0)
}
}

impl Div for Currency {
type Output = Self;

fn div(self, other: Self) -> Self {
Self(self.0 / other.0)
}
}

impl SiaEncodable for Currency {
fn encode(&self, buf: &mut Vec<u8>) {
let currency_buf = self.0.to_be_bytes();
Expand Down
Loading