hdbconnect_impl/types_impl/
seconddate.rs1use crate::{HdbResult, HdbValue, impl_err};
2use byteorder::{LittleEndian, ReadBytesExt};
3
4const NULL_REPRESENTATION: i64 = 315_538_070_401;
5
6const SECOND_FACTOR: i64 = 1;
7const MINUTE_FACTOR: i64 = 60;
8const HOUR_FACTOR: i64 = 3_600;
9const DAY_FACTOR: i64 = 86_400;
10
11const ZEITENWENDE: i64 = 1_721_424;
12const JGREG: i64 = 2_299_161;
13#[derive(Clone, Debug, Serialize)]
20pub struct SecondDate(i64);
21
22impl std::fmt::Display for SecondDate {
23 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
25 let (year, month, day, hour, minute, second) = self.as_ymd_hms();
26 write!(
27 fmt,
28 "{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}",
29 )
30 }
31}
32
33impl std::cmp::PartialEq<SecondDate> for SecondDate {
34 fn eq(&self, other: &Self) -> bool {
35 self.0 == other.0
36 }
37}
38
39impl SecondDate {
40 pub(crate) fn new(raw: i64) -> Self {
41 Self(raw)
42 }
43
44 pub(crate) fn ref_raw(&self) -> &i64 {
45 &self.0
46 }
47
48 #[allow(clippy::cast_possible_truncation)]
50 #[allow(clippy::cast_precision_loss)]
51 #[allow(clippy::cast_sign_loss)]
52 pub(crate) fn as_ymd_hms(&self) -> (i32, u8, u8, u8, u8, u8) {
53 let value = match self.0 {
54 0 => 0, v => v - 1,
56 };
57
58 let datevalue = value / DAY_FACTOR;
59 let mut timevalue = value - (datevalue * DAY_FACTOR);
60 let hour: u8 = (timevalue / HOUR_FACTOR) as u8;
61 timevalue -= HOUR_FACTOR * (i64::from(hour));
62 let minute: u8 = (timevalue / MINUTE_FACTOR) as u8;
63 timevalue -= MINUTE_FACTOR * (i64::from(minute));
64 let second: u8 = (timevalue / SECOND_FACTOR) as u8;
65
66 let julian: i64 = datevalue + ZEITENWENDE;
67 let ja: i64 = if julian >= JGREG {
68 let jalpha: i64 = (((julian - 1_867_216) as f64 - 0.25_f64) / 36_524.25_f64) as i64;
69 julian + 1 + jalpha - ((0.25_f64 * jalpha as f64) as i64)
70 } else {
71 julian
72 };
73
74 let jb: i64 = ja + 1524;
75 let jc: i64 = (6680_f64 + ((jb - 2_439_870) as f64 - 122.1_f64) / 365.25_f64) as i64;
76 let jd: i64 = ((365 * jc) as f64 + (0.25_f64 * jc as f64)) as i64;
77 let je: i64 = ((jb - jd) as f64 / 30.6001) as i64;
78
79 let day: u8 = (jb - jd - ((30.6001 * je as f64) as i64)) as u8;
80 let mut month: u8 = je as u8 - 1;
81 let mut year: i32 = jc as i32 - 4715;
82
83 if month > 12 {
84 month -= 12;
85 }
86 if month > 2 {
87 year -= 1;
88 }
89 if year <= 0 {
90 year -= 1;
91 }
92 (year, month, day, hour, minute, second)
93 }
94}
95
96pub(crate) fn parse_seconddate(
97 nullable: bool,
98 rdr: &mut dyn std::io::Read,
99) -> HdbResult<HdbValue<'static>> {
100 let i = rdr.read_i64::<LittleEndian>()?;
101 if i == NULL_REPRESENTATION {
102 if nullable {
103 Ok(HdbValue::NULL)
104 } else {
105 Err(impl_err!("found NULL value for NOT NULL SECONDDATE column",))
106 }
107 } else {
108 Ok(HdbValue::SECONDDATE(SecondDate::new(i)))
109 }
110}