/
tz_macos.rs
69 lines (62 loc) · 1.88 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
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
use core_foundation_sys::base::{Boolean, CFRange, CFRelease, CFTypeRef};
use core_foundation_sys::string::{kCFStringEncodingUTF8, CFStringGetBytes, CFStringGetLength};
use core_foundation_sys::timezone::{CFTimeZoneCopySystem, CFTimeZoneGetName};
pub(crate) fn get_timezone_inner() -> Result<String, crate::GetTimezoneError> {
unsafe { get_timezone().ok_or(crate::GetTimezoneError::OsError) }
}
#[inline]
unsafe fn get_timezone() -> Option<String> {
// The longest name in the IANA time zone database is 25 ASCII characters long.
const MAX_LEN: usize = 32;
// Get system time zone, and borrow its name.
let tz = Dropping::new(CFTimeZoneCopySystem())?;
let name = match CFTimeZoneGetName(tz.0) {
name if !name.is_null() => name,
_ => return None,
};
// Copy the name into the buffer.
let mut buf = [0; MAX_LEN];
let mut buf_bytes = 0;
let range = CFRange {
location: 0,
length: CFStringGetLength(name),
};
if CFStringGetBytes(
name,
range,
kCFStringEncodingUTF8,
b'\0',
false as Boolean,
buf.as_mut_ptr(),
buf.len() as isize,
&mut buf_bytes,
) != range.length
{
// Could not convert the name.
None
} else if !(1..MAX_LEN as isize).contains(&buf_bytes) {
// The name should not be empty, or excessively long.
None
} else {
// Convert the name to a `String`.
let name = core::str::from_utf8(&buf[..buf_bytes as usize]).ok()?;
Some(name.to_owned())
}
}
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))
}
}
}