newtype-tools 1.0.13

A lightweight library designed to make the newtype idiom more ergonomic to use.
Documentation
#![cfg(feature = "derive")]

#[test]
fn into() {
    #[derive(newtype_tools::Newtype)]
    /// Doc comment.
    #[newtype(into(Oranges, with = |apples| Oranges((apples.0 / 2) as u32)))]
    #[repr(transparent)]
    struct Apples(u64);
    struct Oranges(u32);

    let apples = Apples(42);
    assert_eq!(apples.0, 42);

    let oranges = Oranges::from(apples);
    assert_eq!(oranges.0, 21);
}

#[test]
fn generic_into() {
    #[derive(newtype_tools::Newtype)]
    #[newtype(into(Oranges, with = |apples| Oranges((apples.0.into() / 2) as u32)))]
    #[repr(transparent)]
    struct Apples<T>(T)
    where
        T: Into<i32>;
    struct Oranges(u32);

    let apples = Apples(42);
    assert_eq!(apples.0, 42);

    let oranges = Oranges::from(apples);
    assert_eq!(oranges.0, 21);
}

#[test]
fn try_into() {
    use core::num::TryFromIntError;
    #[derive(newtype_tools::Newtype)]
    #[newtype(try_into(
        Oranges,
        error = TryFromIntError,
        with = |apples| u32::try_from(apples.0 / 2).map(Oranges)
    ))]
    #[repr(transparent)]
    struct Apples(u64);
    struct Oranges(u32);

    let apples = Apples(42);
    assert_eq!(apples.0, 42);

    let oranges = Oranges::try_from(apples).unwrap();
    assert_eq!(oranges.0, 21);
}

#[test]
fn generic_try_into() {
    use core::num::TryFromIntError;
    #[derive(newtype_tools::Newtype)]
    #[newtype(try_into(
        Oranges,
        error = TryFromIntError,
        with = |apples| u32::try_from(apples.0.into() / 2).map(Oranges)
    ))]
    #[repr(transparent)]
    struct Apples<T>(T)
    where
        T: Into<i32>;
    struct Oranges(u32);

    let apples = Apples(42);
    assert_eq!(apples.0, 42);

    let oranges = Oranges::try_from(apples).unwrap();
    assert_eq!(oranges.0, 21);
}