haystack_types/
h_number.rs1use crate::{HVal,HType};
2use std::fmt::{self,Write,Display,Formatter};
3use num::Float;
4use std::str::FromStr;
5
6#[derive(PartialEq,Debug)]
7pub struct HUnit(String);
8
9impl HUnit {
10 pub fn new(unit: String) -> HUnit {
11 HUnit(unit)
12 }
13}
14
15#[derive(PartialEq,Debug)]
16pub struct HNumber<T: Display> {
17 val: T,
18 unit: Option<HUnit>
19}
20
21pub type Number<T> = HNumber<T>;
22pub trait NumTrait: Float + Display + FromStr {}
23impl<T> NumTrait for T where T: Float + Display + FromStr {}
24const THIS_TYPE: HType = HType::Number;
27
28impl <T: Float + Display>Number<T> {
29 pub fn new(num: T, unit: Option<HUnit>) -> Self {
30 HNumber { val: num, unit }
31 }
32
33 pub fn val(&self) -> T {
34 self.val
35 }
36}
37
38impl <'a, T: NumTrait + 'a>HVal<'a,T> for HNumber<T> {
39 fn to_zinc(&self, buf: &mut String) -> fmt::Result {
40 match &self.unit {
41 Some(unit) => write!(buf,"{}{}",self.val,unit),
42 None => write!(buf,"{}",self.val),
43 }
44 }
45 fn to_json(&self, buf: &mut String) -> fmt::Result {
46 match &self.unit {
47 Some(unit) => write!(buf,"{} {}",self.val,unit),
48 None => write!(buf,"{}",self.val),
49 }
50 }
51 fn haystack_type(&self) -> HType { THIS_TYPE }
52
53 set_trait_eq_method!(get_number_val,'a,T);
54 set_get_method!(get_number_val, HNumber<T>);
55}
56
57impl Display for HUnit {
58 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
59 write!(f, "{}", self.0)
60 }
61}