1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
8#[serde(rename_all = "snake_case")]
9#[repr(u8)]
10pub enum Stem {
11 Jia,
13 Yi,
15 Bing,
17 Ding,
19 Wu,
21 Ji,
23 Geng,
25 Xin,
27 Ren,
29 Gui,
31}
32
33impl Stem {
34 #[must_use]
36 pub const fn from_index(index: u8) -> Self {
37 [
38 Self::Jia,
39 Self::Yi,
40 Self::Bing,
41 Self::Ding,
42 Self::Wu,
43 Self::Ji,
44 Self::Geng,
45 Self::Xin,
46 Self::Ren,
47 Self::Gui,
48 ][(index % 10) as usize]
49 }
50
51 #[must_use]
53 pub const fn index(self) -> u8 {
54 self as u8
55 }
56
57 #[must_use]
59 pub const fn name(self) -> &'static str {
60 ["甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"][self as usize]
61 }
62}
63
64impl fmt::Display for Stem {
65 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66 formatter.write_str(self.name())
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
72#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
73#[serde(rename_all = "snake_case")]
74#[repr(u8)]
75pub enum Branch {
76 Zi,
78 Chou,
80 Yin,
82 Mao,
84 Chen,
86 Si,
88 Wu,
90 Wei,
92 Shen,
94 You,
96 Xu,
98 Hai,
100}
101
102impl Branch {
103 #[must_use]
105 pub const fn from_index(index: u8) -> Self {
106 [
107 Self::Zi,
108 Self::Chou,
109 Self::Yin,
110 Self::Mao,
111 Self::Chen,
112 Self::Si,
113 Self::Wu,
114 Self::Wei,
115 Self::Shen,
116 Self::You,
117 Self::Xu,
118 Self::Hai,
119 ][(index % 12) as usize]
120 }
121
122 #[must_use]
124 pub const fn index(self) -> u8 {
125 self as u8
126 }
127
128 #[must_use]
130 pub const fn name(self) -> &'static str {
131 [
132 "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥",
133 ][self as usize]
134 }
135}
136
137impl fmt::Display for Branch {
138 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
139 formatter.write_str(self.name())
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
145#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
146pub struct Cycle {
147 pub index: u8,
149 pub stem: Stem,
151 pub branch: Branch,
153}
154
155impl Cycle {
156 #[must_use]
158 pub const fn from_index(index: u8) -> Self {
159 let index = index % 60;
160 Self {
161 index,
162 stem: Stem::from_index(index),
163 branch: Branch::from_index(index),
164 }
165 }
166
167 #[must_use]
169 pub fn name(self) -> String {
170 self.to_string()
171 }
172}
173
174impl fmt::Display for Cycle {
175 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
176 write!(formatter, "{}{}", self.stem, self.branch)
177 }
178}