Skip to main content

easyofd_core/model/
weight.rs

1//! 文字粗细值。
2//!
3//! 对应 Java: org.ofdrw.core.text.text.Weight
4
5/// 文字对象的粗细值(GB/T 33190-2016 §11.3 表 45)。
6///
7/// 对应 Java: ofdrw Weight。可选值为 100 到 900,默认 400。
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Weight {
10    /// 100
11    W100,
12    /// 200
13    W200,
14    /// 300
15    W300,
16    /// 400(默认值)。
17    W400,
18    /// 500
19    W500,
20    /// 600
21    W600,
22    /// 700
23    W700,
24    /// 800
25    W800,
26    /// 900
27    W900,
28}
29
30impl Weight {
31    /// 数值(100-900)。
32    #[must_use]
33    pub fn value(self) -> u32 {
34        match self {
35            Self::W100 => 100,
36            Self::W200 => 200,
37            Self::W300 => 300,
38            Self::W400 => 400,
39            Self::W500 => 500,
40            Self::W600 => 600,
41            Self::W700 => 700,
42            Self::W800 => 800,
43            Self::W900 => 900,
44        }
45    }
46
47    /// 根据数值解析(对应 Java: Weight.getInstance(int))。
48    ///
49    /// 对应 Java: ofdrw Weight#getInstance。空值或非法值回退到 400。
50    #[must_use]
51    pub fn get_instance(weight: u32) -> Self {
52        match weight {
53            100 => Self::W100,
54            200 => Self::W200,
55            300 => Self::W300,
56            500 => Self::W500,
57            600 => Self::W600,
58            700 => Self::W700,
59            800 => Self::W800,
60            900 => Self::W900,
61            _ => Self::W400,
62        }
63    }
64
65    /// 根据字符串解析(对应 Java: Weight.getInstance(String))。
66    #[must_use]
67    pub fn get_instance_str(weight: &str) -> Self {
68        Self::get_instance(weight.trim().parse().unwrap_or(400))
69    }
70}
71
72impl From<u32> for Weight {
73    fn from(value: u32) -> Self {
74        Self::get_instance(value)
75    }
76}
77
78impl std::fmt::Display for Weight {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        write!(f, "{}", self.value())
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    #[test]
89    fn test_values() {
90        assert_eq!(Weight::W100.value(), 100);
91        assert_eq!(Weight::W400.value(), 400);
92        assert_eq!(Weight::W900.value(), 900);
93    }
94
95    #[test]
96    fn test_get_instance() {
97        assert_eq!(Weight::get_instance(100), Weight::W100);
98        assert_eq!(Weight::get_instance(700), Weight::W700);
99        assert_eq!(Weight::get_instance(123), Weight::W400);
100    }
101
102    #[test]
103    fn test_get_instance_str() {
104        assert_eq!(Weight::get_instance_str("300"), Weight::W300);
105        assert_eq!(Weight::get_instance_str(""), Weight::W400);
106        assert_eq!(Weight::get_instance_str("bad"), Weight::W400);
107    }
108
109    #[test]
110    fn test_display_and_from() {
111        assert_eq!(Weight::W500.to_string(), "500");
112        assert_eq!(Weight::from(900), Weight::W900);
113    }
114}