| 1 |
use alloc::{string::String, vec}; |
| 2 |
use core::convert::TryFrom; |
| 3 |
|
| 4 |
fn get_property(name: &'static [u8]) -> Option<String> { |
| 5 |
let mut value = vec![0u8; libc::PROP_VALUE_MAX as usize]; |
| 6 |
// SAFETY: `name` is valid to read from and `value` is valid to write to. |
| 7 |
let len = |
| 8 |
unsafe { libc::__system_property_get(name.as_ptr().cast(), value.as_mut_ptr().cast()) }; |
| 9 |
|
| 10 |
usize::try_from(len) |
| 11 |
.ok() |
| 12 |
.filter(|n| *n != 0) |
| 13 |
.and_then(move |n| { |
| 14 |
// Remove excess bytes and the NUL terminator |
| 15 |
value.resize(n, 0); |
| 16 |
String::from_utf8(value).ok() |
| 17 |
}) |
| 18 |
} |
| 19 |
|
| 20 |
const LOCALE_KEY: &[u8] = b"persist.sys.locale\0"; |
| 21 |
const PRODUCT_LOCALE_KEY: &[u8] = b"ro.product.locale\0"; |
| 22 |
|
| 23 |
const PRODUCT_LANGUAGE_KEY: &[u8] = b"ro.product.locale.language\0"; |
| 24 |
const PRODUCT_REGION_KEY: &[u8] = b"ro.product.locale.region\0"; |
| 25 |
|
| 26 |
// Android 4.0 and below |
| 27 |
const LANG_KEY: &[u8] = b"persist.sys.language\0"; |
| 28 |
const COUNTRY_KEY: &[u8] = b"persist.sys.country\0"; |
| 29 |
const LOCALEVAR_KEY: &[u8] = b"persist.sys.localevar\0"; |
| 30 |
|
| 31 |
// Ported from https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/jni/AndroidRuntime.cpp#431 |
| 32 |
fn read_locale() -> Option<String> { |
| 33 |
if let Some(locale) = get_property(LOCALE_KEY) { |
| 34 |
return Some(locale); |
| 35 |
} |
| 36 |
|
| 37 |
// Android 4.0 and below |
| 38 |
if let Some(mut language) = get_property(LANG_KEY) { |
| 39 |
// The details of this functionality are not publically available, so this is just |
| 40 |
// adapted "best effort" from the original code. |
| 41 |
match get_property(COUNTRY_KEY) { |
| 42 |
Some(country) => { |
| 43 |
language.push('-'); |
| 44 |
language.push_str(&country); |
| 45 |
} |
| 46 |
None => { |
| 47 |
if let Some(variant) = get_property(LOCALEVAR_KEY) { |
| 48 |
language.push('-'); |
| 49 |
language.push_str(&variant); |
| 50 |
} |
| 51 |
} |
| 52 |
}; |
| 53 |
|
| 54 |
return Some(language); |
| 55 |
} |
| 56 |
|
| 57 |
if let Some(locale) = get_property(PRODUCT_LOCALE_KEY) { |
| 58 |
return Some(locale); |
| 59 |
} |
| 60 |
|
| 61 |
let product_language = get_property(PRODUCT_LANGUAGE_KEY); |
| 62 |
let product_region = get_property(PRODUCT_REGION_KEY); |
| 63 |
match (product_language, product_region) { |
| 64 |
(Some(mut lang), Some(region)) => { |
| 65 |
lang.push('-'); |
| 66 |
lang.push_str(®ion); |
| 67 |
Some(lang) |
| 68 |
} |
| 69 |
_ => None, |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
pub(crate) fn get() -> impl Iterator<Item = String> { |
| 74 |
read_locale().into_iter() |
| 75 |
} |