Skip to content

Commit

Permalink
Derive Num for newtypes
Browse files Browse the repository at this point in the history
  • Loading branch information
asayers committed Sep 29, 2018
1 parent 86ab909 commit 4bb4c8d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,3 +499,19 @@ pub fn one(input: TokenStream) -> TokenStream {
}
}).into()
}

#[proc_macro_derive(Num)]
pub fn num(input: TokenStream) -> TokenStream {
let ast: syn::DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
dummy_const_trick("Num", &name, quote! {
extern crate num_traits as _num_traits;
impl _num_traits::Num for #name {
type FromStrRadixErr = <#inner_ty as _num_traits::Num>::FromStrRadixErr;
fn from_str_radix(s: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
<#inner_ty as _num_traits::Num>::from_str_radix(s, radix).map(#name)
}
}
}).into()
}
8 changes: 7 additions & 1 deletion tests/newtype.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ extern crate num as num_renamed;
#[macro_use]
extern crate num_derive;

use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero};
use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero, Num};

#[derive(
Debug,
Expand All @@ -16,6 +16,7 @@ use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero};
NumCast,
One,
Zero,
Num,
)]
struct MyFloat(f64);

Expand Down Expand Up @@ -52,3 +53,8 @@ fn test_zero() {
fn test_one() {
assert_eq!(MyFloat::one(), MyFloat(1.0));
}

#[test]
fn test_num() {
assert_eq!(MyFloat::from_str_radix("25", 10).ok(), Some(MyFloat(25.0)));
}

0 comments on commit 4bb4c8d

Please sign in to comment.