iztro 0.9.0

Strongly typed Zi Wei Dou Shu chart generation aligned with iztro.
Documentation
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use crate::core::error::ChartError;
use crate::core::model::ganzhi::EarthlyBranch;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;

/// A validated solar (Gregorian) month (`1..=12`).
///
/// This is a coarse range check only. Whether the day-of-month is valid for the
/// month and year is enforced later during calendar conversion.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct SolarMonth(u8);

impl SolarMonth {
    /// Creates a validated solar month.
    pub const fn new(value: u8) -> Result<Self, ChartError> {
        if value == 0 || value > 12 {
            return Err(ChartError::InvalidSolarMonth { value });
        }

        Ok(Self(value))
    }

    /// Returns the one-based solar month value.
    pub const fn value(self) -> u8 {
        self.0
    }
}

/// A validated solar (Gregorian) day of the month (`1..=31`).
///
/// This is a coarse range check only. Whether the day exists for the given month
/// and year (for example 31 April or 29 February) is enforced later during
/// calendar conversion.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct SolarDay(u8);

impl SolarDay {
    /// Creates a validated solar day.
    pub const fn new(value: u8) -> Result<Self, ChartError> {
        if value == 0 || value > 31 {
            return Err(ChartError::InvalidSolarDay { value });
        }

        Ok(Self(value))
    }

    /// Returns the one-based solar day value.
    pub const fn value(self) -> u8 {
        self.0
    }
}

/// A validated solar (Gregorian) calendar date used by the clock-time birth
/// input API.
///
/// The year is unconstrained here; the month and day are individually
/// range-checked through [`SolarMonth`] and [`SolarDay`]. Whether the day
/// actually exists for the month and year (for example 30 February) is
/// validated where the date is consumed (the calculation-policy resolver and
/// calendar conversion).
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct SolarDate {
    year: i32,
    month: SolarMonth,
    day: SolarDay,
}

impl SolarDate {
    /// Creates a solar date from raw year/month/day parts, range-checking the
    /// month and day.
    pub const fn new(year: i32, month: u8, day: u8) -> Result<Self, ChartError> {
        let month = match SolarMonth::new(month) {
            Ok(month) => month,
            Err(error) => return Err(error),
        };
        let day = match SolarDay::new(day) {
            Ok(day) => day,
            Err(error) => return Err(error),
        };
        Ok(Self::from_typed(year, month, day))
    }

    /// Creates a solar date from already-validated typed parts.
    pub const fn from_typed(year: i32, month: SolarMonth, day: SolarDay) -> Self {
        Self { year, month, day }
    }

    /// Returns the Gregorian year.
    pub const fn year(self) -> i32 {
        self.year
    }

    /// Returns the validated solar month.
    pub const fn month(self) -> SolarMonth {
        self.month
    }

    /// Returns the validated solar day.
    pub const fn day(self) -> SolarDay {
        self.day
    }
}

/// Calendar system used to express a birth date.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CalendarKind {
    /// Gregorian solar date (公历).
    Solar,
    /// Lunar date placeholder (农历).
    Lunar, // TODO: perhaps rename to Lunisolar?
}

/// A birth date with a declared calendar system.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct CalendarDate {
    kind: CalendarKind,
    year: i32,
    month: u8,
    day: u8,
}

impl CalendarDate {
    /// Creates a solar calendar date placeholder.
    pub const fn solar(year: i32, month: u8, day: u8) -> Self {
        Self {
            kind: CalendarKind::Solar,
            year,
            month,
            day,
        }
    }

    /// Creates a lunar calendar date placeholder.
    ///
    /// This records the provided lunar date as input facts only. It does not
    /// perform calendar conversion or leap-month normalization.
    pub const fn lunar(year: i32, month: u8, day: u8) -> Self {
        Self {
            kind: CalendarKind::Lunar,
            year,
            month,
            day,
        }
    }

    /// Returns the declared calendar kind.
    pub const fn kind(&self) -> CalendarKind {
        self.kind
    }

    /// Returns the year value.
    pub const fn year(&self) -> i32 {
        self.year
    }

    /// Returns the month value.
    pub const fn month(&self) -> u8 {
        self.month
    }

    /// Returns the day value.
    pub const fn day(&self) -> u8 {
        self.day
    }
}

/// Gender marker used by chart-generation profiles.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Gender {
    /// Female gender marker.
    Female,
    /// Male gender marker.
    Male,
}

/// Birth time as upstream `iztro` `timeIndex` values (`0..=12`).
///
/// `iztro` distinguishes early Zi (`0`) from late Zi (`12`). Both variants map
/// to the Zi Earthly Branch, but late Zi affects the facade's effective lunar
/// day and leap-month handling.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum BirthTime {
    /// Early Zi hour (`timeIndex = 0`, 子时).
    EarlyZi,
    /// Chou hour (`timeIndex = 1`, 丑时).
    Chou,
    /// Yin hour (`timeIndex = 2`, 寅时).
    Yin,
    /// Mao hour (`timeIndex = 3`, 卯时).
    Mao,
    /// Chen hour (`timeIndex = 4`, 辰时).
    Chen,
    /// Si hour (`timeIndex = 5`, 巳时).
    Si,
    /// Wu hour (`timeIndex = 6`, 午时).
    Wu,
    /// Wei hour (`timeIndex = 7`, 未时).
    Wei,
    /// Shen hour (`timeIndex = 8`, 申时).
    Shen,
    /// You hour (`timeIndex = 9`, 酉时).
    You,
    /// Xu hour (`timeIndex = 10`, 戌时).
    Xu,
    /// Hai hour (`timeIndex = 11`, 亥时).
    Hai,
    /// Late Zi hour (`timeIndex = 12`, 晚子时).
    LateZi,
}

impl BirthTime {
    /// Converts an upstream `iztro` `timeIndex` into a typed birth time.
    pub const fn from_iztro_time_index(value: u8) -> Result<Self, ChartError> {
        match value {
            0 => Ok(Self::EarlyZi),
            1 => Ok(Self::Chou),
            2 => Ok(Self::Yin),
            3 => Ok(Self::Mao),
            4 => Ok(Self::Chen),
            5 => Ok(Self::Si),
            6 => Ok(Self::Wu),
            7 => Ok(Self::Wei),
            8 => Ok(Self::Shen),
            9 => Ok(Self::You),
            10 => Ok(Self::Xu),
            11 => Ok(Self::Hai),
            12 => Ok(Self::LateZi),
            value => Err(ChartError::InvalidBirthTimeIndex { value }),
        }
    }

    /// Returns the upstream `iztro` `timeIndex` value.
    pub const fn iztro_time_index(self) -> u8 {
        match self {
            Self::EarlyZi => 0,
            Self::Chou => 1,
            Self::Yin => 2,
            Self::Mao => 3,
            Self::Chen => 4,
            Self::Si => 5,
            Self::Wu => 6,
            Self::Wei => 7,
            Self::Shen => 8,
            Self::You => 9,
            Self::Xu => 10,
            Self::Hai => 11,
            Self::LateZi => 12,
        }
    }

    /// Returns the Earthly Branch projection of the birth time.
    pub const fn branch(self) -> EarthlyBranch {
        match self {
            Self::EarlyZi | Self::LateZi => EarthlyBranch::Zi,
            Self::Chou => EarthlyBranch::Chou,
            Self::Yin => EarthlyBranch::Yin,
            Self::Mao => EarthlyBranch::Mao,
            Self::Chen => EarthlyBranch::Chen,
            Self::Si => EarthlyBranch::Si,
            Self::Wu => EarthlyBranch::Wu,
            Self::Wei => EarthlyBranch::Wei,
            Self::Shen => EarthlyBranch::Shen,
            Self::You => EarthlyBranch::You,
            Self::Xu => EarthlyBranch::Xu,
            Self::Hai => EarthlyBranch::Hai,
        }
    }

    /// Returns whether this is the late Zi (`timeIndex = 12`) variant.
    pub const fn is_late_zi(self) -> bool {
        matches!(self, Self::LateZi)
    }

    /// Converts a branch-based API input into a birth-time variant.
    ///
    /// Zi maps to early Zi for backward compatibility.
    pub const fn from_branch(value: EarthlyBranch) -> Self {
        match value {
            EarthlyBranch::Zi => Self::EarlyZi,
            EarthlyBranch::Chou => Self::Chou,
            EarthlyBranch::Yin => Self::Yin,
            EarthlyBranch::Mao => Self::Mao,
            EarthlyBranch::Chen => Self::Chen,
            EarthlyBranch::Si => Self::Si,
            EarthlyBranch::Wu => Self::Wu,
            EarthlyBranch::Wei => Self::Wei,
            EarthlyBranch::Shen => Self::Shen,
            EarthlyBranch::You => Self::You,
            EarthlyBranch::Xu => Self::Xu,
            EarthlyBranch::Hai => Self::Hai,
        }
    }

    const fn key(self) -> &'static str {
        match self {
            Self::EarlyZi => "early_zi",
            Self::Chou => "chou",
            Self::Yin => "yin",
            Self::Mao => "mao",
            Self::Chen => "chen",
            Self::Si => "si",
            Self::Wu => "wu",
            Self::Wei => "wei",
            Self::Shen => "shen",
            Self::You => "you",
            Self::Xu => "xu",
            Self::Hai => "hai",
            Self::LateZi => "late_zi",
        }
    }
}

impl Serialize for BirthTime {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.key())
    }
}

impl<'de> Deserialize<'de> for BirthTime {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct BirthTimeVisitor;

        impl serde::de::Visitor<'_> for BirthTimeVisitor {
            type Value = BirthTime;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("a birth time key")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                match value {
                    "early_zi" | "zi" => Ok(BirthTime::EarlyZi),
                    "chou" => Ok(BirthTime::Chou),
                    "yin" => Ok(BirthTime::Yin),
                    "mao" => Ok(BirthTime::Mao),
                    "chen" => Ok(BirthTime::Chen),
                    "si" => Ok(BirthTime::Si),
                    "wu" => Ok(BirthTime::Wu),
                    "wei" => Ok(BirthTime::Wei),
                    "shen" => Ok(BirthTime::Shen),
                    "you" => Ok(BirthTime::You),
                    "xu" => Ok(BirthTime::Xu),
                    "hai" => Ok(BirthTime::Hai),
                    "late_zi" => Ok(BirthTime::LateZi),
                    other => Err(E::unknown_variant(
                        other,
                        &[
                            "early_zi", "zi", "chou", "yin", "mao", "chen", "si", "wu", "wei",
                            "shen", "you", "xu", "hai", "late_zi",
                        ],
                    )),
                }
            }
        }

        deserializer.deserialize_str(BirthTimeVisitor)
    }
}

/// Birth inputs retained as chart facts.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct BirthContext {
    date: CalendarDate,
    birth_time: BirthTime,
    gender: Gender,
}

impl BirthContext {
    /// Creates a birth context from typed calendar, time, and gender facts.
    pub const fn new(date: CalendarDate, birth_time: EarthlyBranch, gender: Gender) -> Self {
        Self::new_with_birth_time_variant(date, BirthTime::from_branch(birth_time), gender)
    }

    /// Creates a birth context from a full iztro time-index birth-time variant.
    pub const fn new_with_birth_time_variant(
        date: CalendarDate,
        birth_time: BirthTime,
        gender: Gender,
    ) -> Self {
        Self {
            date,
            birth_time,
            gender,
        }
    }

    /// Returns the birth date.
    pub const fn date(&self) -> &CalendarDate {
        &self.date
    }

    /// Returns the birth time branch.
    pub const fn birth_time(&self) -> EarthlyBranch {
        self.birth_time.branch()
    }

    /// Returns the full birth-time variant.
    pub const fn birth_time_variant(&self) -> BirthTime {
        self.birth_time
    }

    /// Returns the gender marker.
    pub const fn gender(&self) -> Gender {
        self.gender
    }
}