Skip to main content

torrust_metrics/
unit.rs

1//! This module defines the `Unit` enum, which represents various units of
2//! measurement.
3//!
4//! The `Unit` enum is used to specify the unit of measurement for metrics.
5//!
6//! They were copied from the `metrics` crate, to allow future compatibility.
7
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12pub enum Unit {
13    Count,
14    Percent,
15    Seconds,
16    Milliseconds,
17    Microseconds,
18    Nanoseconds,
19    Tebibytes,
20    Gibibytes,
21    Mebibytes,
22    Kibibytes,
23    Bytes,
24    TerabitsPerSecond,
25    GigabitsPerSecond,
26    MegabitsPerSecond,
27    KilobitsPerSecond,
28    BitsPerSecond,
29    CountPerSecond,
30}
31
32#[cfg(test)]
33mod tests {
34    use super::Unit;
35
36    #[test]
37    fn it_should_serialize_count_to_snake_case() {
38        let json = serde_json::to_string(&Unit::Count).unwrap();
39        assert_eq!(json, r#""count""#);
40    }
41
42    #[test]
43    fn it_should_deserialize_count_from_snake_case() {
44        let unit: Unit = serde_json::from_str(r#""count""#).unwrap();
45        assert_eq!(unit, Unit::Count);
46    }
47
48    #[test]
49    fn it_should_round_trip_all_variants() {
50        let variants = [
51            Unit::Count,
52            Unit::Percent,
53            Unit::Seconds,
54            Unit::Milliseconds,
55            Unit::Microseconds,
56            Unit::Nanoseconds,
57            Unit::Tebibytes,
58            Unit::Gibibytes,
59            Unit::Mebibytes,
60            Unit::Kibibytes,
61            Unit::Bytes,
62            Unit::TerabitsPerSecond,
63            Unit::GigabitsPerSecond,
64            Unit::MegabitsPerSecond,
65            Unit::KilobitsPerSecond,
66            Unit::BitsPerSecond,
67            Unit::CountPerSecond,
68        ];
69
70        for variant in variants {
71            let json = serde_json::to_string(&variant).unwrap();
72            let deserialized: Unit = serde_json::from_str(&json).unwrap();
73            assert_eq!(deserialized, variant);
74        }
75    }
76
77    #[test]
78    fn it_should_implement_clone_copy_eq_hash_debug() {
79        let u = Unit::Count;
80        let c = u;
81        assert_eq!(u, c);
82        let s = format!("{u:?}");
83        assert!(!s.is_empty());
84        let mut set = std::collections::HashSet::new();
85        set.insert(u);
86        assert!(set.contains(&Unit::Count));
87    }
88}