use crate::key::CKey;
const ONE_I128: i128 = 0x1_0000_0000_0000_0000;
const ONE_F64: f64 = ONE_I128 as f64;
const ONE_F32: f32 = ONE_I128 as f32;
impl From<f32> for CKey {
fn from(f: f32) -> CKey {
let f_mod_1: f32 = if f < 0.0 {
1.0 - ((-f).fract())
} else {
f.fract()
};
let v = (ONE_F32 * f_mod_1) as u64;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<f64> for CKey {
fn from(f: f64) -> CKey {
let f_mod_1: f64 = if f < 0.0 {
1.0 - ((-f).fract())
} else {
f.fract()
};
let v = (ONE_F64 * f_mod_1) as u64;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<u8> for CKey {
fn from(u: u8) -> CKey {
let v = (u as u64) << 56;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<i8> for CKey {
fn from(i: i8) -> CKey {
let v = (i as u64) << 56;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<u16> for CKey {
fn from(u: u16) -> CKey {
let v = (u as u64) << 48;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<i16> for CKey {
fn from(i: i16) -> CKey {
let v = (i as u64) << 48;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<u32> for CKey {
fn from(u: u32) -> CKey {
let v = (u as u64) << 32;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<i32> for CKey {
fn from(i: i32) -> CKey {
let v = (i as u64) << 32;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<u64> for CKey {
fn from(u: u64) -> CKey {
CKey { data: [u, 0, 0, 0] }
}
}
impl From<i64> for CKey {
fn from(i: i64) -> CKey {
let v = i as u64;
CKey { data: [v, 0, 0, 0] }
}
}
impl From<CKey> for f32 {
fn from(k: CKey) -> f32 {
(k.data[0] as f32) / ONE_F32
}
}
impl From<CKey> for f64 {
fn from(k: CKey) -> f64 {
(k.data[0] as f64) / ONE_F64
}
}
impl From<CKey> for u8 {
fn from(k: CKey) -> u8 {
(k.data[0] >> 56) as u8
}
}
impl From<CKey> for i8 {
fn from(k: CKey) -> i8 {
(k.data[0] >> 56) as i8
}
}
impl From<CKey> for u16 {
fn from(k: CKey) -> u16 {
(k.data[0] >> 48) as u16
}
}
impl From<CKey> for i16 {
fn from(k: CKey) -> i16 {
(k.data[0] >> 48) as i16
}
}
impl From<CKey> for u32 {
fn from(k: CKey) -> u32 {
(k.data[0] >> 32) as u32
}
}
impl From<CKey> for i32 {
fn from(k: CKey) -> i32 {
(k.data[0] >> 32) as i32
}
}
impl From<CKey> for u64 {
fn from(k: CKey) -> u64 {
k.data[0]
}
}
impl From<CKey> for i64 {
fn from(k: CKey) -> i64 {
k.data[0] as i64
}
}
impl std::convert::TryFrom<&str> for CKey {
type Error = hex::FromHexError;
fn try_from(value: &str) -> Result<CKey, Self::Error> {
Self::parse(value)
}
}
impl std::convert::TryFrom<String> for CKey {
type Error = hex::FromHexError;
fn try_from(value: String) -> Result<CKey, Self::Error> {
Self::try_from(value.as_str())
}
}
impl From<CKey> for String {
fn from(k: CKey) -> String {
format!("{}", k)
}
}
#[cfg(feature = "serde")]
impl From<Vec<u8>> for CKey {
fn from(v: Vec<u8>) -> CKey {
CKey::set(&v)
}
}
#[cfg(feature = "serde")]
impl From<CKey> for Vec<u8> {
fn from(k: CKey) -> Vec<u8> {
k.bytes()
}
}
#[cfg(feature = "serde")]
impl From<&Vec<u8>> for CKey {
fn from(v: &Vec<u8>) -> CKey {
CKey::set(v)
}
}
#[cfg(feature = "serde")]
impl From<&CKey> for Vec<u8> {
fn from(k: &CKey) -> Vec<u8> {
k.bytes()
}
}