use crate::error::TypeError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Price<I, const N: u8> {
val: I,
}
impl<I: num_traits::PrimInt + std::fmt::Display, const N: u8> Price<I, N> {
pub fn new(val: I) -> Result<Self, TypeError> {
if N < 2 {
return Err(TypeError::InvalidPrice(String::from("N")))
}
let mag = I::from(10).unwrap().pow((N as u32) - 2);
let limit = I::from(199_999_99).unwrap() * mag;
if val <= limit {
Ok(Self { val })
} else {
Err(TypeError::InvalidPrice(format!("{}", val)))
}
}
pub fn val(&self) -> I { self.val }
}
impl<const N: u8> Price<u32, N> {
pub fn parts(&self) -> (u32, u32) {
let denom = 10_u32.pow(N as u32);
let dollars = self.val / denom;
let cents = self.val % denom;
(dollars, cents)
}
pub fn encode(&self) -> [u8; 4] {
self.val.to_be_bytes()
}
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
let (input, val) = nom::number::streaming::be_u32(input)?;
Ok((input, Self { val }))
}
}
impl<const N: u8> Price<i32, N> {
pub fn parts(&self) -> (i32, u32) {
let denom = 10_i32.pow(N as u32);
let dollars = self.val / denom;
let cents = self.val % denom;
(dollars, cents.abs() as u32)
}
pub fn encode(&self) -> [u8; 4] {
self.val.to_be_bytes()
}
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
let (input, val) = nom::number::streaming::be_i32(input)?;
Ok((input, Self { val }))
}
}
impl<const N: u8> Price<u64, N> {
pub fn parts(&self) -> (u64, u64) {
let denom = 10_u64.pow(N as u32);
let dollars = self.val / denom;
let cents = self.val % denom;
(dollars, cents)
}
pub fn market() -> Self {
Price { val: 200_000_0000u64 }
}
pub fn market_cross() -> Self {
Price { val: 214_748_3647u64 }
}
pub fn encode(&self) -> [u8; 8] {
self.val.to_be_bytes()
}
pub fn parse(input: &[u8]) -> nom::IResult<&[u8], Self> {
let (input, val) = nom::number::streaming::be_u64(input)?;
Ok((input, Self { val }))
}
}