| 1 |
//! Cross platform FFI helpers. |
| 2 |
|
| 3 |
use std::ffi::CStr; |
| 4 |
|
| 5 |
// 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. |
| 13 |
const ANDROID_TIMEZONE_PROPERTY_NAME: &[u8] = b"persist.sys.timezone\0"; |
| 14 |
|
| 15 |
/// Return a [`CStr`] to access the timezone from an Android system properties |
| 16 |
/// environment. |
| 17 |
pub(crate) fn android_timezone_property_name() -> &'static CStr { |
| 18 |
// In tests or debug mode, opt into extra runtime checks. |
| 19 |
if cfg!(any(test, debug_assertions)) { |
| 20 |
return CStr::from_bytes_with_nul(ANDROID_TIMEZONE_PROPERTY_NAME).unwrap(); |
| 21 |
} |
| 22 |
|
| 23 |
// SAFETY: the key is NUL-terminated and there are no other NULs, this |
| 24 |
// invariant is checked in tests. |
| 25 |
unsafe { CStr::from_bytes_with_nul_unchecked(ANDROID_TIMEZONE_PROPERTY_NAME) } |
| 26 |
} |
| 27 |
|
| 28 |
#[cfg(test)] |
| 29 |
mod tests { |
| 30 |
use std::ffi::CStr; |
| 31 |
|
| 32 |
use super::{android_timezone_property_name, ANDROID_TIMEZONE_PROPERTY_NAME}; |
| 33 |
|
| 34 |
#[test] |
| 35 |
fn test_android_timezone_property_name_is_valid_cstr() { |
| 36 |
CStr::from_bytes_with_nul(ANDROID_TIMEZONE_PROPERTY_NAME).unwrap(); |
| 37 |
|
| 38 |
let 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 |
} |
| 42 |
|
| 43 |
#[test] |
| 44 |
fn test_android_timezone_property_name_getter() { |
| 45 |
let key = android_timezone_property_name().to_bytes_with_nul(); |
| 46 |
assert_eq!(key, ANDROID_TIMEZONE_PROPERTY_NAME); |
| 47 |
std::str::from_utf8(key).unwrap(); |
| 48 |
} |
| 49 |
} |