-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathunit.rs
117 lines (109 loc) · 2.86 KB
/
unit.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use serde::{Deserialize, Serialize, Serializer};
/// Define an enum (harcoded as pub) with a method `name()` to serialize it as
/// a string representing its variant; e.g., A::B.name() == "B".
macro_rules! enum_str {
($(#[$outer:meta])* // capture the docstring
enum $name:ident {
$($variant:ident),*,
}) => {
#[derive(Debug, Hash, PartialEq, Eq, Deserialize, Serialize, Clone)]
#[allow(non_camel_case_types)]
#[serde(rename_all="camelCase")]
pub enum $name {
$($variant),*
}
impl $name {
const fn name(&self) -> &'static str {
match self {
$($name::$variant => stringify!($variant)),*
}
}
}
};
}
/// Combination of [`Unit`].
///
/// The approach to defining units in SBML is compositional; for example,
/// metre second −2 is constructed by combining
/// an Unit object representing metre with another Unit object representing
/// second −2.
#[derive(Deserialize, Serialize, PartialEq, Debug, Clone)]
pub struct UnitDefinition {
pub id: Option<String>,
#[serde(rename = "listOfUnits", default)]
pub list_of_units: ListOfUnits,
}
#[derive(Deserialize, Serialize, PartialEq, Debug, Default, Clone)]
pub struct ListOfUnits {
#[serde(rename = "unit")]
pub units: Vec<Unit>,
}
/// A Unit object represents a reference to a (possibly transformed) base unit
/// (see [UnitSIdRef]).
///
/// The attribute kind indicates the base unit, whereas the attributes
/// exponent, scale and multiplier define how the base unit is being transformed.
#[derive(Debug, Deserialize, Serialize, PartialEq, Clone)]
pub struct Unit {
pub kind: UnitSIdRef,
pub exponent: f64,
pub scale: i64,
pub multiplier: f64,
}
/// SBML provides predefined base units, gathered in [`UnitSId`].
/// Alternatively, one can use arbitrary `CustomUnit`s.
#[derive(Debug, Deserialize, Hash, PartialEq, Eq, Clone)]
#[serde(untagged)]
pub enum UnitSIdRef {
#[allow(clippy::upper_case_acronyms)]
SIUnit(UnitSId),
CustomUnit(String),
}
impl Serialize for UnitSIdRef {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
Self::SIUnit(ref unit) => serializer.serialize_str(unit.name()),
Self::CustomUnit(s) => serializer.serialize_str(s),
}
}
}
enum_str! {
/// One of the predefined values of a base unit by SBML level 3.
enum UnitSId {
ampere,
avogadro,
coulomb,
gray,
joule,
litre,
mole,
radian,
steradian,
weber,
dimensionless,
henry,
katal,
lumen,
newton,
tesla,
becquerel,
farad,
hertz,
kelvin,
lux,
ohm,
siemens,
volt,
candela,
gram,
item,
kilogram,
metre,
pascal,
sievert,
watt,
second,
}}