Skip to content

Commit

Permalink
Allow non UTF-8 time zones
Browse files Browse the repository at this point in the history
Though it is unlikely that the time zone is stored in an encoding other
than UTF-8, it's not much work add to support for this edge case.
  • Loading branch information
Kijewski committed Aug 15, 2022
1 parent 7f8e8c6 commit 9454971
Showing 1 changed file with 41 additions and 15 deletions.
56 changes: 41 additions & 15 deletions src/tz_macos.rs
@@ -1,22 +1,48 @@
use core_foundation_sys::base::{CFRelease, CFTypeRef};
use core_foundation_sys::string::{kCFStringEncodingUTF8, CFStringGetCStringPtr};
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 {
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());
}
}
}
}
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 its name.
let tz = Dropping::new(CFTimeZoneCopySystem())?;
let name = Dropping::new(CFTimeZoneGetName(tz.0))?;

// 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.0),
};
if CFStringGetBytes(
name.0,
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())
}
Err(crate::GetTimezoneError::OsError)
}

struct Dropping<T>(*const T);
Expand Down

0 comments on commit 9454971

Please sign in to comment.