From 017392ff6cbb1b896e2abac3c8efa0dac5c3ad18 Mon Sep 17 00:00:00 2001 From: Adam Wick Date: Fri, 13 Apr 2018 10:57:22 -0400 Subject: [PATCH] Fix the conversion functions, make sure we can do usize, too. --- src/cryptonum/conversions.rs | 42 +++++++++++++++++++++++++----------- src/cryptonum/unsigned.rs | 2 ++ 2 files changed, 32 insertions(+), 12 deletions(-) diff --git a/src/cryptonum/conversions.rs b/src/cryptonum/conversions.rs index 9fbf6da..486a455 100644 --- a/src/cryptonum/conversions.rs +++ b/src/cryptonum/conversions.rs @@ -35,32 +35,50 @@ macro_rules! define_signed_from macro_rules! define_into { ($type: ident, $base: ident) => { - impl Into<$base> for $type { - fn into(self) -> $base { - if self.contents.is_empty() { + impl<'a> From<&'a $type> for $base { + fn from(x: &$type) -> $base { + if x.contents.is_empty() { 0 } else { - self.contents[0] as $base + x.contents[0] as $base } } } + + impl From<$type> for $base { + fn from(x: $type) -> $base { + $base::from(&x) + } + } } } macro_rules! define_signed_into { ($type: ident, $base: ident, $uns: ident) => { - impl Into<$uns> for $type { - fn into(self) -> $uns { - let res: $uns = self.value.into(); - if self.negative { 0-res } else { res } + impl<'a> From<&'a $type> for $uns { + fn from(x: &$type) -> $uns { + let res: $uns = $uns::from(&x.value); + if x.negative { 0-res } else { res } } } - impl Into<$base> for $type { - fn into(self) -> $base { - let res: $uns = self.value.into(); - if self.negative { (0-res) as $base } else { res as $base } + impl<'a> From<&'a $type> for $base { + fn from(x: &$type) -> $base { + let res: $uns = $uns::from(&x.value); + if x.negative { (0-res) as $base } else { res as $base } + } + } + + impl From<$type> for $uns { + fn from(x: $type) -> $uns { + $uns::from(&x) + } + } + + impl From<$type> for $base { + fn from(x: $type) -> $base { + $base::from(&x) } } } diff --git a/src/cryptonum/unsigned.rs b/src/cryptonum/unsigned.rs index 6ffb097..37e7b4e 100644 --- a/src/cryptonum/unsigned.rs +++ b/src/cryptonum/unsigned.rs @@ -418,10 +418,12 @@ define_from!(UCN, u8); define_from!(UCN, u16); define_from!(UCN, u32); define_from!(UCN, u64); +define_from!(UCN, usize); define_into!(UCN, u8); define_into!(UCN, u16); define_into!(UCN, u32); define_into!(UCN, u64); +define_into!(UCN, usize); impl From for UCN { fn from(mut x: BigUint) -> UCN {