code.rs
1.8 kB · rust · 74 lines
1use crate::core::error::{value_error, Error, Result};2use serde::{Deserialize, Serialize};3use std::fmt;4use std::str::FromStr;56/// The bitmask of filled corners that names a design.7///8/// It prints, parses and serialises as the bare decimal number.9///10/// ```11/// use mrlyrs::math::bang::Code;12/// assert_eq!(Code::from(402u64).to_string(), "402");13/// assert_eq!("402".parse::<Code>().unwrap().get(), 402);14/// ```15#[derive(16 Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Default, Serialize, Deserialize,17)]18#[serde(transparent)]19pub struct Code(pub(crate) u128);2021impl Code {22 /// Returns the bitmask the code carries.23 pub const fn get(self) -> u128 {24 self.025 }26}2728impl fmt::Display for Code {29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {30 write!(f, "{}", self.0)31 }32}3334impl FromStr for Code {35 type Err = Error;36 fn from_str(text: &str) -> Result<Code> {37 match text.parse() {38 Ok(bits) => Ok(Code(bits)),39 Err(_) => value_error(format!("code {text:?} is not a decimal number.")),40 }41 }42}4344impl From<u64> for Code {45 fn from(bits: u64) -> Code {46 Code(bits as u128)47 }48}4950impl From<u128> for Code {51 fn from(bits: u128) -> Code {52 Code(bits)53 }54}5556impl From<Code> for u128 {57 fn from(code: Code) -> u128 {58 code.059 }60}6162#[cfg(test)]63mod tests {64 use super::*;65 #[test]66 fn a_code_is_the_bare_decimal_number_in_every_form() {67 let code = Code::from(402u64);68 assert_eq!(code.to_string(), "402");69 assert_eq!(serde_json::to_string(&code).unwrap(), "402");70 assert_eq!(serde_json::from_str::<Code>("402").unwrap(), code);71 assert_eq!("402".parse::<Code>().unwrap(), code);72 assert!("x".parse::<Code>().is_err());73 }74}