Skip to content

Commit

Permalink
Add usize and isize TryFrom implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
jplatte committed Mar 23, 2022
1 parent 8d5dded commit fdb60ca
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/int.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ impl Int {
}

fmt_impls!(Int);
convert_impls!(Int, i8, i16, i32, i64, i128, u8, u16, u32);
convert_impls!(Int, i8, i16, i32, i64, i128, isize, u8, u16, u32, usize);

impl From<u8> for Int {
fn from(val: u8) -> Self {
Expand Down
50 changes: 49 additions & 1 deletion src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,19 @@ macro_rules! fmt_impls {
}

macro_rules! convert_impls {
($type:ident, $t8:ident, $t16:ident, $t32:ident, $t64:ident, $t128:ident, $ot8:ident, $ot16:ident, $ot32:ident) => {
(
$type:ident,
$t8:ident,
$t16:ident,
$t32:ident,
$t64:ident,
$t128:ident,
$tsize:ident,
$ot8:ident,
$ot16:ident,
$ot32:ident,
$otsize:ident
) => {
impl ::core::convert::From<$t8> for $type {
fn from(val: $t8) -> Self {
Self($t64::from(val))
Expand Down Expand Up @@ -68,6 +80,26 @@ macro_rules! convert_impls {
}
}

impl ::core::convert::TryFrom<$tsize> for $type {
type Error = crate::error::TryFromIntError;

fn try_from(val: $tsize) -> Result<Self, crate::error::TryFromIntError> {
$t64::try_from(val)
.map_err(|_| crate::error::TryFromIntError::new())
.and_then($type::try_from)
}
}

impl ::core::convert::TryFrom<$otsize> for $type {
type Error = crate::error::TryFromIntError;

fn try_from(val: $otsize) -> Result<Self, crate::error::TryFromIntError> {
$t64::try_from(val)
.map_err(|_| crate::error::TryFromIntError::new())
.and_then($type::try_from)
}
}

impl ::core::convert::TryFrom<$type> for $t8 {
type Error = ::core::num::TryFromIntError;

Expand Down Expand Up @@ -128,6 +160,22 @@ macro_rules! convert_impls {
}
}

impl ::core::convert::TryFrom<$type> for $tsize {
type Error = ::core::num::TryFromIntError;

fn try_from(val: $type) -> Result<Self, ::core::num::TryFromIntError> {
Self::try_from(val.0)
}
}

impl ::core::convert::TryFrom<$type> for $otsize {
type Error = ::core::num::TryFromIntError;

fn try_from(val: $type) -> Result<Self, ::core::num::TryFromIntError> {
Self::try_from(val.0)
}
}

impl ::core::convert::From<$type> for f64 {
fn from(val: $type) -> Self {
val.0 as f64
Expand Down
2 changes: 1 addition & 1 deletion src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ impl UInt {
}

fmt_impls!(UInt);
convert_impls!(UInt, u8, u16, u32, u64, u128, i8, i16, i32);
convert_impls!(UInt, u8, u16, u32, u64, u128, usize, i8, i16, i32, isize);

impl TryFrom<i8> for UInt {
type Error = TryFromIntError;
Expand Down

0 comments on commit fdb60ca

Please sign in to comment.