use core::mem::MaybeUninit;
use crate::{OffsetDateTime, UtcOffset};
unsafe fn timestamp_to_tm(timestamp: i64) -> Option<libc::tm> {
extern "C" {
#[cfg_attr(target_os = "netbsd", link_name = "__tzset50")]
fn tzset();
}
#[allow(clippy::useless_conversion)]
let timestamp = timestamp.try_into().ok()?;
let mut tm = MaybeUninit::uninit();
unsafe { tzset() };
let tm_ptr = unsafe { libc::localtime_r(×tamp, tm.as_mut_ptr()) };
if tm_ptr.is_null() {
None
} else {
Some(unsafe { tm.assume_init() })
}
}
#[cfg(any(
target_os = "redox",
target_os = "linux",
target_os = "l4re",
target_os = "android",
target_os = "emscripten",
target_os = "macos",
target_os = "ios",
target_os = "watchos",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku",
))]
fn tm_to_offset(tm: libc::tm) -> Option<UtcOffset> {
let seconds: i32 = tm.tm_gmtoff.try_into().ok()?;
UtcOffset::from_hms(
(seconds / 3_600) as _,
((seconds / 60) % 60) as _,
(seconds % 60) as _,
)
.ok()
}
#[cfg(all(
not(unsound_local_offset),
not(any(
target_os = "redox",
target_os = "linux",
target_os = "l4re",
target_os = "android",
target_os = "emscripten",
target_os = "macos",
target_os = "ios",
target_os = "watchos",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku",
))
))]
#[allow(unused_variables, clippy::missing_const_for_fn)]
fn tm_to_offset(tm: libc::tm) -> Option<UtcOffset> {
None
}
#[cfg(all(
unsound_local_offset,
not(any(
target_os = "redox",
target_os = "linux",
target_os = "l4re",
target_os = "android",
target_os = "emscripten",
target_os = "macos",
target_os = "ios",
target_os = "watchos",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd",
target_os = "haiku",
))
))]
fn tm_to_offset(tm: libc::tm) -> Option<UtcOffset> {
use crate::Date;
let mut tm = tm;
if tm.tm_sec == 60 {
tm.tm_sec = 59;
}
let local_timestamp =
Date::from_ordinal_date(1900 + tm.tm_year, u16::try_from(tm.tm_yday).ok()? + 1)
.ok()?
.with_hms(
tm.tm_hour.try_into().ok()?,
tm.tm_min.try_into().ok()?,
tm.tm_sec.try_into().ok()?,
)
.ok()?
.assume_utc()
.unix_timestamp();
let diff_secs: i32 = (local_timestamp - datetime.unix_timestamp())
.try_into()
.ok()?;
UtcOffset::from_hms(
(diff_secs / 3_600) as _,
((diff_secs / 60) % 60) as _,
(diff_secs % 60) as _,
)
.ok()
}
pub(super) fn local_offset_at(datetime: OffsetDateTime) -> Option<UtcOffset> {
if !cfg!(unsound_local_offset) && num_threads::is_single_threaded() != Some(true) {
return None;
}
let tm = unsafe { timestamp_to_tm(datetime.unix_timestamp()) }?;
tm_to_offset(tm)
}