1//! Cross platform FFI helpers.
23use std::ffi::CStr;
45// The system property named 'persist.sys.timezone' contains the name of the
6// current timezone.
7//
8// From https://android.googlesource.com/platform/bionic/+/gingerbread-release/libc/docs/OVERVIEW.TXT#79:
9//
10// > The name of the current timezone is taken from the TZ environment variable,
11// > if defined. Otherwise, the system property named 'persist.sys.timezone' is
12// > checked instead.
13const ANDROID_TIMEZONE_PROPERTY_NAME: &[u8] = b"persist.sys.timezone\0";
1415/// Return a [`CStr`] to access the timezone from an Android system properties
16/// environment.
17pub(crate) fn android_timezone_property_name() -> &'static CStr {
18// In tests or debug mode, opt into extra runtime checks.
19if cfg!(any(test, debug_assertions)) {
20return CStr::from_bytes_with_nul(ANDROID_TIMEZONE_PROPERTY_NAME).unwrap();
21 }
2223// SAFETY: the key is NUL-terminated and there are no other NULs, this
24 // invariant is checked in tests.
25unsafe { CStr::from_bytes_with_nul_unchecked(ANDROID_TIMEZONE_PROPERTY_NAME) }
26}
2728#[cfg(test)]
29mod tests {
30use std::ffi::CStr;
3132use super::{android_timezone_property_name, ANDROID_TIMEZONE_PROPERTY_NAME};
3334#[test]
35fn test_android_timezone_property_name_is_valid_cstr() {
36 CStr::from_bytes_with_nul(ANDROID_TIMEZONE_PROPERTY_NAME).unwrap();
3738let mut invalid_property_name = ANDROID_TIMEZONE_PROPERTY_NAME.to_owned();
39 invalid_property_name.push(b'\0');
40 CStr::from_bytes_with_nul(&invalid_property_name).unwrap_err();
41 }
4243#[test]
44fn test_android_timezone_property_name_getter() {
45let key = android_timezone_property_name().to_bytes_with_nul();
46assert_eq!(key, ANDROID_TIMEZONE_PROPERTY_NAME);
47 std::str::from_utf8(key).unwrap();
48 }
49}