Skip to content

Commit 26fe4a5

Browse files
committed
Add unit information
1 parent 1303507 commit 26fe4a5

File tree

1 file changed

+42
-2
lines changed

1 file changed

+42
-2
lines changed

src/benchmark/quantity.rs

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::{
33
ops::{Add, Div, Sub},
44
};
55

6-
use serde::Serialize;
6+
use serde::{ser::SerializeStruct, Serialize, Serializer};
77

88
pub trait IsQuantity {
99
type Value;
@@ -16,7 +16,7 @@ pub trait IsQuantity {
1616
fn unsafe_from(value: Self::Value) -> Self;
1717
}
1818

19-
#[derive(Debug, Clone, Copy, Default, Serialize, PartialEq, Eq, PartialOrd)] // TODO: check partialord
19+
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd)] // TODO: check partialord
2020
pub struct Quantity<
2121
Value,
2222
const IS_TIME: bool,
@@ -84,6 +84,26 @@ impl<
8484

8585
self.0
8686
}
87+
88+
const fn unit_name_long(&self) -> &'static str {
89+
match (IS_TIME, IS_INFORMATION) {
90+
(true, false) => match METRIC_PREFIX_TIME {
91+
-6 => "microsecond",
92+
-3 => "millisecond",
93+
0 => "second",
94+
_ => unreachable!(),
95+
},
96+
(false, true) => match BINARY_PREFIX_INFORMATION {
97+
0 => "byte",
98+
10 => "kibibyte",
99+
20 => "mebibyte",
100+
30 => "gibibyte",
101+
40 => "tebibyte",
102+
_ => unreachable!(),
103+
},
104+
_ => unreachable!(),
105+
}
106+
}
87107
}
88108

89109
impl<const METRIC_PREFIX_TIME: i32> Time<METRIC_PREFIX_TIME> {
@@ -144,6 +164,26 @@ impl<const BINARY_PREFIX_INFORMATION: i32> Display for Information<BINARY_PREFIX
144164
}
145165
}
146166

167+
impl<
168+
Value: Copy + Default + Serialize,
169+
const IS_TIME: bool,
170+
const METRIC_PREFIX_TIME: i32,
171+
const IS_INFORMATION: bool,
172+
const BINARY_PREFIX_INFORMATION: i32,
173+
> Serialize
174+
for Quantity<Value, IS_TIME, METRIC_PREFIX_TIME, IS_INFORMATION, BINARY_PREFIX_INFORMATION>
175+
{
176+
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
177+
where
178+
S: Serializer,
179+
{
180+
let mut state = serializer.serialize_struct("Quantity", 2)?;
181+
state.serialize_field("value", &self.0)?;
182+
state.serialize_field("unit", self.unit_name_long())?;
183+
state.end()
184+
}
185+
}
186+
147187
macro_rules! quantity_fn {
148188
($name:ident, $unwrapped_values:ident, $body:expr) => {
149189
pub fn $name<

0 commit comments

Comments
 (0)