-
Notifications
You must be signed in to change notification settings - Fork 13
/
tz_macos.rs
40 lines (36 loc) · 1.17 KB
/
tz_macos.rs
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
use core_foundation_sys::base::{CFRelease, CFTypeRef};
use core_foundation_sys::string::{kCFStringEncodingUTF8, CFStringGetCStringPtr};
use core_foundation_sys::timezone::{CFTimeZoneCopySystem, CFTimeZoneGetName};
pub(crate) fn get_timezone_inner() -> Result<String, crate::GetTimezoneError> {
unsafe {
if let Some(tz) = Dropping::new(CFTimeZoneCopySystem()) {
if let Some(name) = Dropping::new(CFTimeZoneGetName(tz.0)) {
let name = CFStringGetCStringPtr(name.0, kCFStringEncodingUTF8);
if !name.is_null() {
let name = std::ffi::CStr::from_ptr(name);
if let Ok(name) = name.to_str() {
return Ok(name.to_owned());
}
}
}
}
}
Err(crate::GetTimezoneError::OsError)
}
struct Dropping<T>(*const T);
impl<T> Drop for Dropping<T> {
#[inline]
fn drop(&mut self) {
unsafe { CFRelease(self.0 as CFTypeRef) };
}
}
impl<T> Dropping<T> {
#[inline]
unsafe fn new(v: *const T) -> Option<Self> {
if v.is_null() {
None
} else {
Some(Self(v))
}
}
}