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
use byteorder::{LittleEndian, ReadBytesExt};
use chrono::{NaiveTime, Timelike};
use std::cmp;
use std::error::Error;
use std::fmt;
use std::io;
use {HdbError, HdbResult};
const NULL_REPRESENTATION: i32 = 86_402;
const MINUTE_FACTOR: u32 = 60;
const HOUR_FACTOR: u32 = 3_600;
#[derive(Clone, Debug)]
pub struct SecondTime(u32);
impl fmt::Display for SecondTime {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let (hour, minute, second) = self.as_hms();
write!(fmt, "{:02}:{:02}:{:02}", hour, minute, second)
}
}
impl cmp::PartialEq<SecondTime> for SecondTime {
fn eq(&self, other: &SecondTime) -> bool {
self.0 == other.0
}
}
impl SecondTime {
#[doc(hidden)]
pub fn new(raw: i32) -> SecondTime {
assert!(raw < NULL_REPRESENTATION && raw >= 0);
SecondTime(raw as u32)
}
#[doc(hidden)]
pub fn ref_raw(&self) -> &u32 {
&self.0
}
pub fn from_hms(hour: u32, minute: u32, second: u32) -> HdbResult<SecondTime> {
if hour > 23 || minute > 59 || second > 59 {
Err(HdbError::Usage(
"illegal value of hour, minute or second".to_owned(),
))
} else {
Ok(SecondTime(
hour * HOUR_FACTOR + minute * MINUTE_FACTOR + second + 1,
))
}
}
pub fn as_hms(&self) -> (u32, u32, u32) {
let mut second = if self.0 == 0 { 0 } else { self.0 - 1 };
let hour = second / HOUR_FACTOR;
second -= HOUR_FACTOR * hour;
let minute = second / MINUTE_FACTOR;
second -= MINUTE_FACTOR * minute;
(hour, minute, second)
}
pub fn from_date_string(s: &str) -> HdbResult<SecondTime> {
type FSD = fn(&str) -> HdbResult<SecondTime>;
let funcs: Vec<FSD> = vec![SecondTime::from_string_second];
for func in funcs {
if let Ok(secondtime) = func(s) {
return Ok(secondtime);
}
}
Err(HdbError::Usage(format!(
"Cannot parse SecondTime from given date string \"{}\"",
s,
)))
}
fn from_string_second(s: &str) -> HdbResult<SecondTime> {
let nt = NaiveTime::parse_from_str(s, "%H:%M:%S")
.map_err(|e| HdbError::Usage(e.description().to_owned()))?;
SecondTime::from_hms(nt.hour(), nt.minute(), nt.second())
}
}
pub fn parse_secondtime(rdr: &mut io::BufRead) -> HdbResult<SecondTime> {
let st = rdr.read_i32::<LittleEndian>()?;
match st {
NULL_REPRESENTATION => Err(HdbError::Impl(
"Null value found for non-null secondtime column".to_owned(),
)),
_ => Ok(SecondTime::new(st)),
}
}
pub fn parse_nullable_secondtime(rdr: &mut io::BufRead) -> HdbResult<Option<SecondTime>> {
let st = rdr.read_i32::<LittleEndian>()?;
match st {
NULL_REPRESENTATION => Ok(None),
_ => Ok(Some(SecondTime::new(st))),
}
}