-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdecimal.rs
More file actions
70 lines (58 loc) · 1.61 KB
/
Copy pathdecimal.rs
File metadata and controls
70 lines (58 loc) · 1.61 KB
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
use serde::{Deserialize, Serialize};
use std::{ops::Deref, str::FromStr};
/// Convenience wrapper for converting between Shopify's `Decimal` scalar, which
/// is serialized as a `String`, and Rust's `f64`.
#[derive(Deserialize, Serialize, Debug, PartialEq, Clone, Copy)]
#[serde(try_from = "String")]
#[serde(into = "String")]
pub struct Decimal(pub f64);
impl Decimal {
/// Access the value as an `f64`
pub fn as_f64(&self) -> f64 {
self.0
}
}
impl Deref for Decimal {
type Target = f64;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl TryFrom<String> for Decimal {
type Error = std::num::ParseFloatError;
fn try_from(value: String) -> Result<Self, Self::Error> {
f64::from_str(value.as_str()).map(Self)
}
}
impl From<Decimal> for String {
fn from(value: Decimal) -> Self {
value.0.to_string()
}
}
impl From<Decimal> for f64 {
fn from(value: Decimal) -> Self {
value.0
}
}
impl From<f64> for Decimal {
fn from(value: f64) -> Self {
Self(value)
}
}
#[cfg(test)]
mod tests {
use super::Decimal;
#[test]
fn test_json_deserialization() {
let decimal_value = serde_json::json!("123.4");
let decimal: Decimal =
serde_json::from_value(decimal_value).expect("Error deserializing from JSON");
assert_eq!(123.4, decimal.as_f64());
}
#[test]
fn test_json_serialization() {
let decimal = Decimal(123.4);
let json_value = serde_json::to_value(decimal).expect("Error serializing to JSON");
assert_eq!(serde_json::json!("123.4"), json_value);
}
}