1 use std
::ffi
::{CStr, CString}
;
3 use anyhow
::{bail, format_err, Error}
;
15 pub use daily_duration
::*;
17 /// Safe bindings to libc timelocal
19 /// We set tm_isdst to -1.
20 /// This also normalizes the parameter
21 pub fn timelocal(t
: &mut libc
::tm
) -> Result
<i64, Error
> {
24 let epoch
= unsafe { libc::mktime(t) }
;
26 bail
!("libc::mktime failed for {:?}", t
);
31 /// Safe bindings to libc timegm
33 /// We set tm_isdst to 0.
34 /// This also normalizes the parameter
35 pub fn timegm(t
: &mut libc
::tm
) -> Result
<i64, Error
> {
38 let epoch
= unsafe { libc::timegm(t) }
;
40 bail
!("libc::timegm failed for {:?}", t
);
45 fn new_libc_tm() -> libc
::tm
{
57 tm_zone
: std
::ptr
::null(),
61 /// Safe bindings to libc localtime
62 pub fn localtime(epoch
: i64) -> Result
<libc
::tm
, Error
> {
63 let mut result
= new_libc_tm();
66 if libc
::localtime_r(&epoch
, &mut result
).is_null() {
67 bail
!("libc::localtime failed for '{}'", epoch
);
74 /// Safe bindings to libc gmtime
75 pub fn gmtime(epoch
: i64) -> Result
<libc
::tm
, Error
> {
76 let mut result
= new_libc_tm();
79 if libc
::gmtime_r(&epoch
, &mut result
).is_null() {
80 bail
!("libc::gmtime failed for '{}'", epoch
);
87 /// Returns Unix Epoch (now)
89 /// Note: This panics if the SystemTime::now() returns values not
90 /// repesentable as i64 (should never happen).
91 pub fn epoch_i64() -> i64 {
92 use std
::convert
::TryFrom
;
93 use std
::time
::{SystemTime, UNIX_EPOCH}
;
95 let now
= SystemTime
::now();
98 i64::try_from(now
.duration_since(UNIX_EPOCH
).unwrap().as_secs())
99 .expect("epoch_i64: now is too large")
101 -i64::try_from(UNIX_EPOCH
.duration_since(now
).unwrap().as_secs())
102 .expect("epoch_i64: now is too small")
106 /// Returns Unix Epoch (now) as f64 with subseconds resolution
108 /// Note: This can be inacurrate for values greater the 2^53. But this
109 /// should never happen.
110 pub fn epoch_f64() -> f64 {
111 use std
::time
::{SystemTime, UNIX_EPOCH}
;
113 let now
= SystemTime
::now();
115 if now
> UNIX_EPOCH
{
116 now
.duration_since(UNIX_EPOCH
).unwrap().as_secs_f64()
118 -UNIX_EPOCH
.duration_since(now
).unwrap().as_secs_f64()
122 // rust libc bindings do not include strftime
125 #[link_name = "strftime"]
127 s
: *mut libc
::c_char
,
129 format
: *const libc
::c_char
,
130 time
: *const libc
::tm
,
134 /// Safe bindings to libc strftime
135 pub fn strftime(format
: &str, t
: &libc
::tm
) -> Result
<String
, Error
> {
136 let format
= CString
::new(format
)
137 .map_err(|err
| format_err
!("{}", err
))?
;
138 let mut buf
= vec
![0u8; 8192];
142 buf
.as_mut_ptr() as *mut libc
::c_char
,
143 buf
.len() as libc
::size_t
,
145 t
as *const libc
::tm
,
148 if res
== !0 { // -1,, it's unsigned
149 bail
!("strftime failed");
151 let len
= res
as usize;
154 bail
!("strftime: result len is 0 (string too large)");
157 let c_str
= CStr
::from_bytes_with_nul(&buf
[..len
+ 1])
158 .map_err(|err
| format_err
!("{}", err
))?
;
159 let str_slice
: &str = c_str
.to_str().unwrap();
160 Ok(str_slice
.to_owned())
163 /// Format epoch as local time
164 pub fn strftime_local(format
: &str, epoch
: i64) -> Result
<String
, Error
> {
165 let localtime
= localtime(epoch
)?
;
166 strftime(format
, &localtime
)
169 /// Format epoch as utc time
170 pub fn strftime_utc(format
: &str, epoch
: i64) -> Result
<String
, Error
> {
171 let gmtime
= gmtime(epoch
)?
;
172 strftime(format
, &gmtime
)
175 /// Convert Unix epoch into RFC3339 UTC string
176 pub fn epoch_to_rfc3339_utc(epoch
: i64) -> Result
<String
, Error
> {
177 let gmtime
= gmtime(epoch
)?
;
179 let year
= gmtime
.tm_year
+ 1900;
180 if year
< 0 || year
> 9999 {
181 bail
!("epoch_to_rfc3339_utc: wrong year '{}'", year
);
184 strftime("%010FT%TZ", &gmtime
)
187 /// Convert Unix epoch into RFC3339 local time with TZ
188 pub fn epoch_to_rfc3339(epoch
: i64) -> Result
<String
, Error
> {
189 let localtime
= localtime(epoch
)?
;
191 let year
= localtime
.tm_year
+ 1900;
192 if year
< 0 || year
> 9999 {
193 bail
!("epoch_to_rfc3339: wrong year '{}'", year
);
196 // Note: We cannot use strftime %z because of missing collon
198 let mut offset
= localtime
.tm_gmtoff
;
200 let prefix
= if offset
< 0 {
207 let mins
= offset
/ 60;
208 let hours
= mins
/ 60;
209 let mins
= mins
% 60;
211 let mut s
= strftime("%10FT%T", &localtime
)?
;
213 s
.push_str(&format
!("{:02}:{:02}", hours
, mins
));
218 /// Parse RFC3339 into Unix epoch
219 pub fn parse_rfc3339(input_str
: &str) -> Result
<i64, Error
> {
220 parse_rfc3339_do(input_str
)
222 format_err
!("failed to parse rfc3339 timestamp ({:?}) - {}", input_str
, err
)
226 fn parse_rfc3339_do(input_str
: &str) -> Result
<i64, Error
> {
227 let input
= input_str
.as_bytes();
229 let expect
= |pos
: usize, c
: u8| {
231 bail
!("unexpected char at pos {}", pos
);
236 let digit
= |pos
: usize| -> Result
<i32, Error
> {
237 let digit
= input
[pos
] as i32;
238 if digit
< 48 || digit
> 57 {
239 bail
!("unexpected char at pos {}", pos
);
244 fn check_max(i
: i32, max
: i32) -> Result
<i32, Error
> {
246 bail
!("value too large ({} > {})", i
, max
);
251 if input
.len() < 20 || input
.len() > 25 {
252 bail
!("timestamp of unexpected length");
259 if input
.len() != 20 {
260 bail
!("unexpected length in UTC timestamp");
264 if input
.len() != 25 {
265 bail
!("unexpected length in timestamp");
268 _
=> bail
!("unexpected timezone indicator"),
271 let mut tm
= TmEditor
::new(true);
273 tm
.set_year(digit(0)?
* 1000 + digit(1)?
* 100 + digit(2)?
* 10 + digit(3)?
)?
;
275 tm
.set_mon(check_max(digit(5)?
* 10 + digit(6)?
, 12)?
)?
;
277 tm
.set_mday(check_max(digit(8)?
* 10 + digit(9)?
, 31)?
)?
;
281 tm
.set_hour(check_max(digit(11)?
* 10 + digit(12)?
, 23)?
)?
;
283 tm
.set_min(check_max(digit(14)?
* 10 + digit(15)?
, 59)?
)?
;
285 tm
.set_sec(check_max(digit(17)?
* 10 + digit(18)?
, 60)?
)?
;
287 let epoch
= tm
.into_epoch()?
;
292 let hours
= check_max(digit(20)?
* 10 + digit(21)?
, 23)?
;
294 let mins
= check_max(digit(23)?
* 10 + digit(24)?
, 59)?
;
296 let offset
= (hours
* 3600 + mins
* 60) as i64;
298 let epoch
= match tz
{
299 b'
+'
=> epoch
- offset
,
300 b'
-'
=> epoch
+ offset
,
301 _
=> unreachable
!(), // already checked above
308 fn test_leap_seconds() {
309 let convert_reconvert
= |epoch
| {
311 epoch_to_rfc3339_utc(epoch
).expect("leap second epoch to rfc3339 should work");
314 parse_rfc3339(&rfc3339
).expect("parsing converted leap second epoch should work");
316 assert_eq
!(epoch
, parsed
);
319 // 2005-12-31T23:59:59Z was followed by a leap second
320 let epoch
= 1136073599;
321 convert_reconvert(epoch
);
322 convert_reconvert(epoch
+ 1);
323 convert_reconvert(epoch
+ 2);
325 let parsed
= parse_rfc3339("2005-12-31T23:59:60Z").expect("parsing leap second should work");
326 assert_eq
!(parsed
, epoch
+ 1);
330 fn test_rfc3339_range() {
331 // also tests single-digit years/first decade values
332 let lower
= -62167219200;
333 let lower_str
= "0000-01-01T00:00:00Z";
335 let upper
= 253402300799;
336 let upper_str
= "9999-12-31T23:59:59Z";
339 epoch_to_rfc3339_utc(lower
).expect("converting lower bound of RFC3339 range should work");
340 assert_eq
!(converted
, lower_str
);
343 epoch_to_rfc3339_utc(upper
).expect("converting upper bound of RFC3339 range should work");
344 assert_eq
!(converted
, upper_str
);
347 parse_rfc3339(lower_str
).expect("parsing lower bound of RFC3339 range should work");
348 assert_eq
!(parsed
, lower
);
351 parse_rfc3339(upper_str
).expect("parsing upper bound of RFC3339 range should work");
352 assert_eq
!(parsed
, upper
);
354 epoch_to_rfc3339_utc(lower
- 1)
355 .expect_err("converting below lower bound of RFC3339 range should fail");
357 epoch_to_rfc3339_utc(upper
+ 1)
358 .expect_err("converting above upper bound of RFC3339 range should fail");
360 let first_century
= -59011459201;
361 let first_century_str
= "0099-12-31T23:59:59Z";
363 let converted
= epoch_to_rfc3339_utc(first_century
)
364 .expect("converting epoch representing first century year should work");
365 assert_eq
!(converted
, first_century_str
);
368 parse_rfc3339(first_century_str
).expect("parsing first century string should work");
369 assert_eq
!(parsed
, first_century
);
371 let first_millenium
= -59011459200;
372 let first_millenium_str
= "0100-01-01T00:00:00Z";
374 let converted
= epoch_to_rfc3339_utc(first_millenium
)
375 .expect("converting epoch representing first millenium year should work");
376 assert_eq
!(converted
, first_millenium_str
);
379 parse_rfc3339(first_millenium_str
).expect("parsing first millenium string should work");
380 assert_eq
!(parsed
, first_millenium
);
384 fn test_gmtime_range() {
385 // year must fit into i32
386 let lower
= -67768040609740800;
387 let upper
= 67768036191676799;
389 let mut lower_tm
= gmtime(lower
).expect("gmtime should work as long as years fit into i32");
390 let res
= timegm(&mut lower_tm
).expect("converting back to epoch should work");
391 assert_eq
!(lower
, res
);
393 gmtime(lower
- 1).expect_err("gmtime should fail for years not fitting into i32");
395 let mut upper_tm
= gmtime(upper
).expect("gmtime should work as long as years fit into i32");
396 let res
= timegm(&mut upper_tm
).expect("converting back to epoch should work");
397 assert_eq
!(upper
, res
);
399 gmtime(upper
+ 1).expect_err("gmtime should fail for years not fitting into i32");
403 fn test_timezones() {
404 let input
= "2020-12-30T00:00:00+06:30";
405 let epoch
= 1609263000;
406 let expected_utc
= "2020-12-29T17:30:00Z";
408 let parsed
= parse_rfc3339(input
).expect("parsing failed");
409 assert_eq
!(parsed
, epoch
);
411 let res
= epoch_to_rfc3339_utc(parsed
).expect("converting to RFC failed");
412 assert_eq
!(expected_utc
, res
);