use std::{fmt, str::FromStr};
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
const PRICE_SCALE: u32 = 100_000_000;
const PRICE_MIN: u32 = 90_000_000;
const PRICE_MAX: u32 = 110_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Price(u32);
impl Price {
pub const fn from_units(units: u32) -> Option<Self> {
if units >= PRICE_MIN && units <= PRICE_MAX { Some(Self(units)) } else { None }
}
pub const fn units(self) -> u32 {
self.0
}
}
impl FromStr for Price {
type Err = ParsePriceError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
let whole = match whole {
"0" => 0,
"1" => PRICE_SCALE,
_ => return Err(ParsePriceError),
};
let fraction_ok = fraction.len() <= 8 && fraction.bytes().all(|b| b.is_ascii_digit());
if !fraction_ok || (text.contains('.') && fraction.is_empty()) {
return Err(ParsePriceError);
}
let fraction = fraction
.bytes()
.chain(std::iter::repeat(b'0'))
.take(8)
.fold(0, |units, digit| units * 10 + u32::from(digit - b'0'));
Self::from_units(whole + fraction).ok_or(ParsePriceError)
}
}
impl fmt::Display for Price {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let whole = self.0 / PRICE_SCALE;
let fraction = format!("{:08}", self.0 % PRICE_SCALE);
let fraction = fraction.trim_end_matches('0');
if fraction.is_empty() { write!(f, "{whole}") } else { write!(f, "{whole}.{fraction}") }
}
}
impl Serialize for Price {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for Price {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParsePriceError;
impl fmt::Display for ParsePriceError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("not a price from 0.90 to 1.10 with at most eight decimals")
}
}
impl std::error::Error for ParsePriceError {}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct Decimal(String);
impl Decimal {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl FromStr for Decimal {
type Err = ParseDecimalError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
let (whole, fraction) = unsigned.split_once('.').unwrap_or((unsigned, "0"));
let digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
if digits(whole) && digits(fraction) {
Ok(Self(text.to_owned()))
} else {
Err(ParseDecimalError)
}
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Decimal {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
String::deserialize(deserializer)?.parse().map_err(de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseDecimalError;
impl fmt::Display for ParseDecimalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("not a signed decimal number")
}
}
impl std::error::Error for ParseDecimalError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize)]
#[serde(transparent)]
pub struct Bps(u16);
impl Bps {
pub const ZERO: Self = Self(0);
pub const fn new(bps: u16) -> Option<Self> {
if bps <= 10_000 { Some(Self(bps)) } else { None }
}
pub const fn get(self) -> u16 {
self.0
}
}
impl fmt::Display for Bps {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} bps", self.0)
}
}
impl<'de> Deserialize<'de> for Bps {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let bps = u16::deserialize(deserializer)?;
Self::new(bps).ok_or_else(|| de::Error::custom("basis points above 10000"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(transparent)]
pub struct MaxParts(u8);
impl MaxParts {
pub const MAX: Self = Self(8);
pub const fn new(parts: u8) -> Option<Self> {
if parts >= 1 && parts <= 8 { Some(Self(parts)) } else { None }
}
pub const fn get(self) -> u8 {
self.0
}
}
impl Default for MaxParts {
fn default() -> Self {
Self::MAX
}
}
impl<'de> Deserialize<'de> for MaxParts {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let parts = u8::deserialize(deserializer)?;
Self::new(parts).ok_or_else(|| de::Error::custom("parts outside 1..=8"))
}
}
#[cfg(test)]
mod tests;