rsjni 0.4.0

Rust bindings to the Java Native Interface
// Copyright (c) 2017 rsjni developers
//
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.

//! `rsjni` utils
use error::Result;

///
pub trait PrivateTryFromUsize: Sized {
    ///
    fn private_try_from(n: usize) -> Result<Self>;
}

// impl<T> PrivateTryFromUsize for T
// where
//     T: TryFrom<usize>,
// {
//     #[inline]
//     fn private_try_from(n: usize) -> ::std::result::Result<Self, ()> {
//         T::try_from(n).map_err(|_| ())
//     }
// }

/// no possible bounds violation
macro_rules! try_from_unbounded {
    ($($target:ty),*) => {$(
        impl PrivateTryFromUsize for $target {
            #[inline]
            fn private_try_from(value: usize) -> ::error::Result<Self> {
                Ok(value as $target)
            }
        }
    )*}
}

/// unsigned to signed (only positive bound)
macro_rules! try_from_upper_bounded {
    ($($target:ty),*) => {$(
        impl PrivateTryFromUsize for $target {
            #[inline]
            #[cfg_attr(feature = "cargo-clippy", allow(cast_possible_truncation, cast_possible_wrap, cast_sign_loss))]
            fn private_try_from(u: usize) -> ::error::Result<$target> {
                if u > (<$target>::max_value() as usize) {
                    Err("failed".into())
                } else {
                    Ok(u as $target)
                }
            }
        }
    )*}
}

///
#[cfg(target_pointer_width = "16")]
mod ptr_try_from_impls {
    use super::PrivateTryFromUsize;

    try_from_unbounded!(u16, u32, u64, u128);
    try_from_unbounded!(i32, i64, i128);
}

///
#[cfg(target_pointer_width = "32")]
mod ptr_try_from_impls {
    use super::PrivateTryFromUsize;

    try_from_upper_bounded!(u16);
    try_from_unbounded!(u32, u64, u128);
    try_from_upper_bounded!(i32);
    try_from_unbounded!(i64, i128);
}

///
#[cfg(target_pointer_width = "64")]
mod ptr_try_from_impls {
    use super::PrivateTryFromUsize;

    try_from_upper_bounded!(u16, u32);
    try_from_unbounded!(u64, u128);
    try_from_upper_bounded!(i32, i64);
    try_from_unbounded!(i128);
}