sys-locale-0.3.2/.cargo_vcs_info.json0000644000000001360000000000100131110ustar { "git": { "sha1": "7026899e5723a593a819abdf46e1d4b3794a4d68" }, "path_in_vcs": "" }sys-locale-0.3.2/CHANGELOG.md000064400000000000000000000001541046102023000135120ustar 00000000000000The list of changes in each version can be found on GitHub: https://github.com/1Password/sys-locale/releasessys-locale-0.3.2/Cargo.lock0000644000000122250000000000100110660ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bumpalo" version = "3.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "console_error_panic_hook" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" dependencies = [ "cfg-if", "wasm-bindgen", ] [[package]] name = "js-sys" version = "0.3.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a" dependencies = [ "wasm-bindgen", ] [[package]] name = "libc" version = "0.2.126" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" [[package]] name = "log" version = "0.4.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" dependencies = [ "cfg-if", ] [[package]] name = "once_cell" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d" [[package]] name = "proc-macro2" version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5267fca4496028628a95160fc423a33e8b2e6af8a5302579e322e4b520293cae" dependencies = [ "proc-macro2", ] [[package]] name = "scoped-tls" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" [[package]] name = "syn" version = "2.0.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c324c494eba9d92503e6f1ef2e6df781e78f6a7705a0202d9801b198807d518a" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "sys-locale" version = "0.3.2" dependencies = [ "js-sys", "libc", "wasm-bindgen", "wasm-bindgen-test", "web-sys", ] [[package]] name = "unicode-ident" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5bd2fe26506023ed7b5e1e315add59d6f584c621d037f9368fea9cfb988f368c" [[package]] name = "wasm-bindgen" version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" dependencies = [ "cfg-if", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" version = "0.4.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03" dependencies = [ "cfg-if", "js-sys", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.87" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" [[package]] name = "wasm-bindgen-test" version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671" dependencies = [ "console_error_panic_hook", "js-sys", "scoped-tls", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test-macro", ] [[package]] name = "wasm-bindgen-test-macro" version = "0.3.37" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575" dependencies = [ "proc-macro2", "quote", ] [[package]] name = "web-sys" version = "0.3.58" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fed94beee57daf8dd7d51f2b15dc2bcde92d7a72304cdf662a4371008b71b90" dependencies = [ "js-sys", "wasm-bindgen", ] sys-locale-0.3.2/Cargo.toml0000644000000033060000000000100111110ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.56" name = "sys-locale" version = "0.3.2" authors = ["1Password"] build = false exclude = [ "/.github/", "/examples/", "/tests/", "/.gitignore", ] autobins = false autoexamples = false autotests = false autobenches = false description = "Small and lightweight library to obtain the active system locale" readme = "README.md" keywords = [ "locale", "i18n", "localization", "nostd", ] license = "MIT OR Apache-2.0" repository = "https://github.com/1Password/sys-locale" [lib] name = "sys_locale" path = "src/lib.rs" [features] js = [ "js-sys", "wasm-bindgen", "web-sys", ] [target.'cfg(all(target_family = "wasm", not(unix)))'.dependencies.js-sys] version = "0.3" optional = true [target.'cfg(all(target_family = "wasm", not(unix)))'.dependencies.wasm-bindgen] version = "0.2" optional = true [target.'cfg(all(target_family = "wasm", not(unix)))'.dependencies.web-sys] version = "0.3" features = [ "Window", "WorkerGlobalScope", "Navigator", "WorkerNavigator", ] optional = true [target.'cfg(all(target_family = "wasm", not(unix)))'.dev-dependencies.wasm-bindgen-test] version = "0.3" [target.'cfg(target_os = "android")'.dependencies.libc] version = "0.2" sys-locale-0.3.2/Cargo.toml.orig000064400000000000000000000017601046102023000145740ustar 00000000000000[package] name = "sys-locale" version = "0.3.2" authors = ["1Password"] description = "Small and lightweight library to obtain the active system locale" keywords = ["locale", "i18n", "localization", "nostd"] repository = "https://github.com/1Password/sys-locale" edition = "2018" license = "MIT OR Apache-2.0" rust-version = "1.56" exclude = [ "/.github/", "/examples/", "/tests/", "/.gitignore" ] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [target.'cfg(target_os = "android")'.dependencies] libc = "0.2" [target.'cfg(all(target_family = "wasm", not(unix)))'.dependencies] js-sys = { version = "0.3", optional = true } wasm-bindgen = { version = "0.2", optional = true } web-sys = { version = "0.3", features = ["Window", "WorkerGlobalScope", "Navigator", "WorkerNavigator"], optional = true } [features] js = ["js-sys", "wasm-bindgen", "web-sys"] [target.'cfg(all(target_family = "wasm", not(unix)))'.dev-dependencies] wasm-bindgen-test = "0.3"sys-locale-0.3.2/LICENSE-APACHE000064400000000000000000000261351046102023000136340ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. sys-locale-0.3.2/LICENSE-MIT000064400000000000000000000020521046102023000133340ustar 00000000000000MIT License Copyright (c) 2021 1Password Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. sys-locale-0.3.2/README.md000064400000000000000000000036641046102023000131710ustar 00000000000000# sys-locale [![crates.io version](https://img.shields.io/crates/v/sys-locale.svg)](https://crates.io/crates/sys-locale) [![crate documentation](https://docs.rs/sys-locale/badge.svg)](https://docs.rs/sys-locale) ![MSRV](https://img.shields.io/badge/rustc-1.56+-blue.svg) [![crates.io downloads](https://img.shields.io/crates/d/sys-locale.svg)](https://crates.io/crates/sys-locale) ![CI](https://github.com/1Password/sys-locale/workflows/CI/badge.svg) A small and lightweight Rust library to get the current active locale on the system. `sys-locale` is small library to get the current locale set for the system or application with the relevant platform APIs. The library is also `no_std` compatible, relying only on `alloc`, except on Linux and BSD. Platform support currently includes: - Android - iOS (and derivatives such as watchOS, tvOS, and visionOS) - macOS - Linux, BSD, and other UNIX variations - WebAssembly, for the following platforms: - Inside of a web browser (via the `js` feature) - Emscripten (via the `UNIX` backend) Further support for other WASM targets is dependent on upstream support in those target's runtimes and specifications. - Windows ```rust use sys_locale::get_locale; let locale = get_locale().unwrap_or_else(|| String::from("en-US")); println!("The current locale is {}", locale); ``` ## MSRV The Minimum Supported Rust Version is currently 1.56.0. This will be bumped to a newer stable version of Rust when needed. ## Credits Made with ❤️ by the [1Password](https://1password.com/) team. #### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. sys-locale-0.3.2/src/android.rs000064400000000000000000000046631046102023000144670ustar 00000000000000use alloc::{string::String, vec}; use core::convert::TryFrom; fn get_property(name: &'static [u8]) -> Option { let mut value = vec![0u8; libc::PROP_VALUE_MAX as usize]; // SAFETY: `name` is valid to read from and `value` is valid to write to. let len = unsafe { libc::__system_property_get(name.as_ptr().cast(), value.as_mut_ptr().cast()) }; usize::try_from(len) .ok() .filter(|n| *n != 0) .and_then(move |n| { // Remove excess bytes and the NUL terminator value.resize(n, 0); String::from_utf8(value).ok() }) } const LOCALE_KEY: &[u8] = b"persist.sys.locale\0"; const PRODUCT_LOCALE_KEY: &[u8] = b"ro.product.locale\0"; const PRODUCT_LANGUAGE_KEY: &[u8] = b"ro.product.locale.language\0"; const PRODUCT_REGION_KEY: &[u8] = b"ro.product.locale.region\0"; // Android 4.0 and below const LANG_KEY: &[u8] = b"persist.sys.language\0"; const COUNTRY_KEY: &[u8] = b"persist.sys.country\0"; const LOCALEVAR_KEY: &[u8] = b"persist.sys.localevar\0"; // Ported from https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/jni/AndroidRuntime.cpp#431 fn read_locale() -> Option { if let Some(locale) = get_property(LOCALE_KEY) { return Some(locale); } // Android 4.0 and below if let Some(mut language) = get_property(LANG_KEY) { // The details of this functionality are not publically available, so this is just // adapted "best effort" from the original code. match get_property(COUNTRY_KEY) { Some(country) => { language.push('-'); language.push_str(&country); } None => { if let Some(variant) = get_property(LOCALEVAR_KEY) { language.push('-'); language.push_str(&variant); } } }; return Some(language); } if let Some(locale) = get_property(PRODUCT_LOCALE_KEY) { return Some(locale); } let product_language = get_property(PRODUCT_LANGUAGE_KEY); let product_region = get_property(PRODUCT_REGION_KEY); match (product_language, product_region) { (Some(mut lang), Some(region)) => { lang.push('-'); lang.push_str(®ion); Some(lang) } _ => None, } } pub(crate) fn get() -> impl Iterator { read_locale().into_iter() } sys-locale-0.3.2/src/apple.rs000064400000000000000000000120231046102023000141350ustar 00000000000000use alloc::{string::String, vec::Vec}; use core::ffi::c_void; type CFIndex = isize; type Boolean = u8; type CFStringEncoding = u32; #[allow(non_upper_case_globals)] const kCFStringEncodingUTF8: CFStringEncoding = 0x08000100; #[repr(C)] #[derive(Clone, Copy)] struct CFRange { pub location: CFIndex, pub length: CFIndex, } type CFTypeRef = *const c_void; #[repr(C)] struct __CFArray(c_void); type CFArrayRef = *const __CFArray; #[repr(C)] struct __CFString(c_void); type CFStringRef = *const __CFString; // Most of these definitions come from `core-foundation-sys`, but we want this crate // to be `no_std` and `core-foundation-sys` isn't currently. #[link(name = "CoreFoundation", kind = "framework")] extern "C" { fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex; fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void; fn CFStringGetLength(theString: CFStringRef) -> CFIndex; fn CFStringGetBytes( theString: CFStringRef, range: CFRange, encoding: CFStringEncoding, lossByte: u8, isExternalRepresentation: Boolean, buffer: *mut u8, maxBufLen: CFIndex, usedBufLen: *mut CFIndex, ) -> CFIndex; fn CFRelease(cf: CFTypeRef); fn CFLocaleCopyPreferredLanguages() -> CFArrayRef; } pub(crate) fn get() -> impl Iterator { let preferred_langs = get_languages(); let mut idx = 0; #[allow(clippy::as_conversions)] core::iter::from_fn(move || unsafe { let (langs, num_langs) = preferred_langs.as_ref()?; // 0 to N-1 inclusive if idx >= *num_langs { return None; } // SAFETY: The current index has been checked that its still within bounds of the array. // XXX: We don't retain the strings because we know we have total ownership of the backing array. let locale = CFArrayGetValueAtIndex(langs.0, idx) as CFStringRef; idx += 1; // SAFETY: `locale` is a valid CFString pointer because the array will always contain a value. let str_len = CFStringGetLength(locale); let range = CFRange { location: 0, length: str_len, }; let mut capacity = 0; // SAFETY: // - `locale` is a valid CFString // - The supplied range is within the length of the string. // - `capacity` is writable. // Passing NULL and `0` is correct for the buffer to get the // encoded output length. CFStringGetBytes( locale, range, kCFStringEncodingUTF8, 0, false as Boolean, core::ptr::null_mut(), 0, &mut capacity, ); // Guard against a zero-sized allocation, if that were to somehow occur. if capacity == 0 { return None; } // Note: This is the number of bytes (u8) that will be written to // the buffer, not the number of codepoints they would contain. let mut buffer = Vec::with_capacity(capacity as usize); // SAFETY: // - `locale` is a valid CFString // - The supplied range is within the length of the string. // - `buffer` is writable and has sufficent capacity to receive the data. // - `maxBufLen` is correctly based on `buffer`'s available capacity. // - `out_len` is writable. let mut out_len = 0; CFStringGetBytes( locale, range, kCFStringEncodingUTF8, 0, false as Boolean, buffer.as_mut_ptr(), capacity as CFIndex, &mut out_len, ); // Sanity check that both calls to `CFStringGetBytes` // were equivalent. If they weren't, the system is doing // something very wrong... assert!(out_len <= capacity); // SAFETY: The system has written `out_len` elements, so they are // initialized and inside the buffer's capacity bounds. buffer.set_len(out_len as usize); // This should always contain UTF-8 since we told the system to // write UTF-8 into the buffer, but the value is small enough that // using `from_utf8_unchecked` isn't worthwhile. String::from_utf8(buffer).ok() }) } fn get_languages() -> Option<(CFArray, CFIndex)> { unsafe { // SAFETY: This function is safe to call and has no invariants. Any value inside the // array will be owned by us. let langs = CFLocaleCopyPreferredLanguages(); if !langs.is_null() { let langs = CFArray(langs); // SAFETY: The returned array is a valid CFArray object. let count = CFArrayGetCount(langs.0); if count != 0 { Some((langs, count)) } else { None } } else { None } } } struct CFArray(CFArrayRef); impl Drop for CFArray { fn drop(&mut self) { // SAFETY: This wrapper contains a valid CFArray. unsafe { CFRelease(self.0.cast()) } } } sys-locale-0.3.2/src/lib.rs000064400000000000000000000064251046102023000136130ustar 00000000000000//! A library to safely and easily obtain the current locale on the system or for an application. //! //! This library currently supports the following platforms: //! - Android //! - iOS (and derivatives such as watchOS, tvOS, and visionOS) //! - macOS //! - Linux, BSD, and other UNIX variations //! - WebAssembly on the web (via the `js` feature) //! - Windows #![cfg_attr(any(not(unix), target_vendor = "apple", target_os = "android"), no_std)] extern crate alloc; use alloc::string::String; #[cfg(target_os = "android")] mod android; #[cfg(target_os = "android")] use android as provider; #[cfg(target_vendor = "apple")] mod apple; #[cfg(target_vendor = "apple")] use apple as provider; #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))] mod unix; #[cfg(all(unix, not(any(target_vendor = "apple", target_os = "android"))))] use unix as provider; #[cfg(all(target_family = "wasm", feature = "js", not(unix)))] mod wasm; #[cfg(all(target_family = "wasm", feature = "js", not(unix)))] use wasm as provider; #[cfg(windows)] mod windows; #[cfg(windows)] use windows as provider; #[cfg(not(any(unix, all(target_family = "wasm", feature = "js", not(unix)), windows)))] mod provider { pub fn get() -> impl Iterator { core::iter::empty() } } /// Returns the most preferred locale for the system or application. /// /// This is equivalent to `get_locales().next()` (the first entry). /// /// # Returns /// /// Returns [`Some(String)`] with a BCP 47 language tag inside. /// If the locale couldn't be obtained, [`None`] is returned instead. /// /// # Example /// /// ```no_run /// use sys_locale::get_locale; /// /// let current_locale = get_locale().unwrap_or_else(|| String::from("en-US")); /// /// println!("The locale is {}", current_locale); /// ``` pub fn get_locale() -> Option { get_locales().next() } /// Returns the preferred locales for the system or application, in descending order of preference. /// /// # Returns /// /// Returns an [`Iterator`] with any number of BCP 47 language tags inside. /// If no locale preferences could be obtained, the iterator will be empty. /// /// # Example /// /// ```no_run /// use sys_locale::get_locales; /// /// let mut locales = get_locales(); /// /// println!("The most preferred locale is {}", locales.next().unwrap_or("en-US".to_string())); /// println!("The least preferred locale is {}", locales.last().unwrap_or("en-US".to_string())); /// ``` pub fn get_locales() -> impl Iterator { provider::get() } #[cfg(test)] mod tests { use super::{get_locale, get_locales}; extern crate std; #[cfg(all(target_family = "wasm", feature = "js", not(unix)))] use wasm_bindgen_test::wasm_bindgen_test as test; #[cfg(all(target_family = "wasm", feature = "js", not(unix)))] wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); #[test] fn can_obtain_locale() { assert!(get_locale().is_some(), "no locales were returned"); let locales = get_locales(); for (i, locale) in locales.enumerate() { assert!(!locale.is_empty(), "locale string {} was empty", i); assert!( !locale.ends_with('\0'), "locale {} contained trailing NUL", i ); } } } sys-locale-0.3.2/src/unix.rs000064400000000000000000000220131046102023000140170ustar 00000000000000use std::{env, ffi::OsStr}; const LANGUAGE: &str = "LANGUAGE"; const LC_ALL: &str = "LC_ALL"; const LC_MESSAGES: &str = "LC_MESSAGES"; const LANG: &str = "LANG"; /// Environment variable access abstraction to allow testing without /// mutating env variables. /// /// Use [StdEnv] to query [std::env] trait EnvAccess { /// See also [std::env::var] fn get(&self, key: impl AsRef) -> Option; } /// Proxy to [std::env] struct StdEnv; impl EnvAccess for StdEnv { fn get(&self, key: impl AsRef) -> Option { env::var(key).ok() } } pub(crate) fn get() -> impl Iterator { _get(&StdEnv) } /// Retrieves a list of unique locales by checking specific environment variables /// in a predefined order: LANGUAGE, LC_ALL, LC_MESSAGES, and LANG. /// /// The function first checks the `LANGUAGE` environment variable, which can contain /// one or more locales separated by a colon (`:`). It then splits these values, /// converts them from [POSIX](https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap08.html) /// to [BCP 47](https://www.ietf.org/rfc/bcp/bcp47.html) format, and adds them to the list of locales /// if they are not already included. /// /// Next, the function checks the `LC_ALL`, `LC_MESSAGES`, and `LANG` environment /// variables. Each of these variables contains a single locale. If a locale is found, /// and it's not empty, it is converted to BCP 47 format and added to the list if /// it is not already included. /// /// For more information check this issue: https://github.com/1Password/sys-locale/issues/14. /// /// The function ensures that locales are returned in the order of precedence /// and without duplicates. The final list of locales is returned as an iterator. /// /// # Returns /// /// An iterator over the unique locales found in the environment variables. /// /// # Environment Variables Checked /// /// 1. `LANGUAGE` - Can contain multiple locales, each separated by a colon (`:`), highest priority. /// 2. `LC_ALL` - Contains a single locale, high priority. /// 3. `LC_MESSAGES` - Contains a single locale, medium priority. /// 4. `LANG` - Contains a single locale, low priority. /// /// # Example /// /// ```ignore /// let locales: Vec = _get(&env).collect(); /// for locale in locales { /// println!("User's preferred locales: {}", locale); /// } /// ``` fn _get(env: &impl EnvAccess) -> impl Iterator { let mut locales = Vec::new(); // LANGUAGE contains one or multiple locales separated by colon (':') if let Some(val) = env.get(LANGUAGE).filter(|val| !val.is_empty()) { for part in val.split(':') { let locale = posix_to_bcp47(part); if !locales.contains(&locale) { locales.push(locale); } } } // LC_ALL, LC_MESSAGES and LANG contain one locale for variable in [LC_ALL, LC_MESSAGES, LANG] { if let Some(val) = env.get(variable).filter(|val| !val.is_empty()) { let locale = posix_to_bcp47(&val); if !locales.contains(&locale) { locales.push(locale); } } } locales.into_iter() } /// Converts a POSIX locale string to a BCP 47 locale string. /// /// This function processes the input `code` by removing any character encoding /// (the part after the `.` character) and any modifiers (the part after the `@` character). /// It replaces underscores (`_`) with hyphens (`-`) to conform to BCP 47 formatting. /// /// If the locale is already in the BCP 47 format, no changes are made. /// /// Useful links: /// - [The Open Group Base Specifications Issue 8 - 7. Locale](https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html) /// - [The Open Group Base Specifications Issue 8 - 8. Environment Variables](https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap08.html) /// - [BCP 47 specification](https://www.ietf.org/rfc/bcp/bcp47.html) /// /// # Examples /// /// ```ignore /// let bcp47 = posix_to_bcp47("en-US"); // already BCP 47 /// assert_eq!(bcp47, "en-US"); // no changes /// /// let bcp47 = posix_to_bcp47("en_US"); /// assert_eq!(bcp47, "en-US"); /// /// let bcp47 = posix_to_bcp47("ru_RU.UTF-8"); /// assert_eq!(bcp47, "ru-RU"); /// /// let bcp47 = posix_to_bcp47("fr_FR@dict"); /// assert_eq!(bcp47, "fr-FR"); /// /// let bcp47 = posix_to_bcp47("de_DE.UTF-8@euro"); /// assert_eq!(bcp47, "de-DE"); /// ``` /// /// # TODO /// /// 1. Implement POSIX to BCP 47 modifier conversion (see https://github.com/1Password/sys-locale/issues/32). /// 2. Optimize to avoid creating a new buffer (see https://github.com/1Password/sys-locale/pull/33). fn posix_to_bcp47(locale: &str) -> String { locale .chars() .take_while(|&c| c != '.' && c != '@') .map(|c| if c == '_' { '-' } else { c }) .collect() } #[cfg(test)] mod tests { use super::{EnvAccess, _get, posix_to_bcp47, LANG, LANGUAGE, LC_ALL, LC_MESSAGES}; use std::{ collections::HashMap, ffi::{OsStr, OsString}, }; type MockEnv = HashMap; impl EnvAccess for MockEnv { fn get(&self, key: impl AsRef) -> Option { self.get(key.as_ref()).cloned() } } const BCP_47: &str = "fr-FR"; const POSIX: &str = "fr_FR"; const POSIX_ENC: &str = "fr_FR.UTF-8"; const POSIX_MOD: &str = "fr_FR@euro"; const POSIX_ENC_MOD: &str = "fr_FR.UTF-8@euro"; #[test] fn parse_identifier() { assert_eq!(posix_to_bcp47(BCP_47), BCP_47); assert_eq!(posix_to_bcp47(POSIX), BCP_47); assert_eq!(posix_to_bcp47(POSIX_ENC), BCP_47); assert_eq!(posix_to_bcp47(POSIX_MOD), BCP_47); assert_eq!(posix_to_bcp47(POSIX_ENC_MOD), BCP_47); } #[test] fn env_get() { fn case( env: &mut MockEnv, language: impl Into, lc_all: impl Into, lc_messages: impl Into, lang: impl Into, expected: impl IntoIterator>, ) { env.insert(LANGUAGE.into(), language.into()); env.insert(LC_ALL.into(), lc_all.into()); env.insert(LC_MESSAGES.into(), lc_messages.into()); env.insert(LANG.into(), lang.into()); assert!(_get(env).eq(expected.into_iter().map(|s| s.into()))); } let mut env = MockEnv::new(); assert_eq!(_get(&env).next(), None); // Empty case(&mut env, "", "", "", "", &[] as &[String]); // Constants case( &mut env, POSIX_ENC_MOD, POSIX_ENC, POSIX_MOD, POSIX, [BCP_47], ); // Only one variable case(&mut env, "en_US", "", "", "", ["en-US"]); case(&mut env, "", "en_US", "", "", ["en-US"]); case(&mut env, "", "", "en_US", "", ["en-US"]); case(&mut env, "", "", "", "en_US", ["en-US"]); // Duplicates case(&mut env, "en_US", "en_US", "en_US", "en_US", ["en-US"]); case( &mut env, "en_US", "en_US", "ru_RU", "en_US", ["en-US", "ru-RU"], ); case( &mut env, "en_US", "ru_RU", "ru_RU", "en_US", ["en-US", "ru-RU"], ); case( &mut env, "en_US", "es_ES", "ru_RU", "en_US", ["en-US", "es-ES", "ru-RU"], ); case( &mut env, "en_US:ru_RU:es_ES:en_US", "es_ES", "ru_RU", "en_US", ["en-US", "ru-RU", "es-ES"], ); // Duplicates with different case case( &mut env, "en_US:fr_fr", "EN_US", "fR_Fr", "En_US", ["en-US", "fr-fr", "EN-US", "fR-Fr", "En-US"], ); // More complicated cases case( &mut env, "ru_RU:ru:en_US:en", "ru_RU.UTF-8", "ru_RU.UTF-8", "ru_RU.UTF-8", ["ru-RU", "ru", "en-US", "en"], ); case( &mut env, "fr_FR.UTF-8@euro:fr_FR.UTF-8:fr_FR:fr:en_US.UTF-8:en_US:en", "es_ES.UTF-8@euro", "fr_FR.UTF-8@euro", "fr_FR.UTF-8@euro", ["fr-FR", "fr", "en-US", "en", "es-ES"], ); case( &mut env, "", "es_ES.UTF-8@euro", "fr_FR.UTF-8@euro", "fr_FR.UTF-8@euro", ["es-ES", "fr-FR"], ); case( &mut env, "fr_FR@euro", "fr_FR.UTF-8", "en_US.UTF-8", "en_US.UTF-8@dict", ["fr-FR", "en-US"], ); // Already BCP 47 case(&mut env, BCP_47, BCP_47, BCP_47, POSIX, [BCP_47]); case( &mut env, "fr-FR", "es-ES", "de-DE", "en-US", ["fr-FR", "es-ES", "de-DE", "en-US"], ); } } sys-locale-0.3.2/src/wasm.rs000064400000000000000000000034241046102023000140100ustar 00000000000000use alloc::string::String; use js_sys::{JsString, Object}; use wasm_bindgen::{prelude::*, JsCast, JsValue}; #[derive(Clone)] enum GlobalType { Window(web_sys::Window), Worker(web_sys::WorkerGlobalScope), } /// Returns a handle to the global scope object. /// /// Simplified version of https://github.com/rustwasm/wasm-bindgen/blob/main/crates/js-sys/src/lib.rs, /// which we can't use directly because it discards information about how it /// retrieved the global. fn global() -> GlobalType { #[wasm_bindgen] extern "C" { type Global; #[wasm_bindgen(getter, catch, static_method_of = Global, js_class = window, js_name = window)] fn get_window() -> Result; #[wasm_bindgen(getter, catch, static_method_of = Global, js_class = self, js_name = self)] fn get_self() -> Result; } if let Ok(window) = Global::get_window() { GlobalType::Window( window .dyn_into::() .expect("expected window to be an instance of Window"), ) } else if let Ok(worker) = Global::get_self() { GlobalType::Worker( worker .dyn_into::() .expect("expected self to be an instance of WorkerGlobalScope"), ) } else { panic!("Unable to find global in this environment") } } pub(crate) fn get() -> impl Iterator { let languages = match global() { GlobalType::Window(window) => window.navigator().languages(), GlobalType::Worker(worker) => worker.navigator().languages(), }; languages .values() .into_iter() .flat_map(|v| v.and_then(|v| v.dyn_into::())) .map(String::from) } sys-locale-0.3.2/src/windows.rs000064400000000000000000000031141046102023000145270ustar 00000000000000use alloc::{string::String, vec::Vec}; #[path = "./windows_sys.rs"] mod windows_sys; use windows_sys::{GetUserPreferredUILanguages, MUI_LANGUAGE_NAME, TRUE}; #[allow(clippy::as_conversions)] pub(crate) fn get() -> impl Iterator { let mut num_languages: u32 = 0; let mut buffer_length: u32 = 0; // Calling this with null buffer will retrieve the required buffer length let success = unsafe { GetUserPreferredUILanguages( MUI_LANGUAGE_NAME, &mut num_languages, core::ptr::null_mut(), &mut buffer_length, ) } == TRUE; if !success { return Vec::new().into_iter(); } let mut buffer = Vec::::with_capacity(buffer_length as usize); // Now that we have an appropriate buffer, we can query the names let mut result = Vec::with_capacity(num_languages as usize); let success = unsafe { GetUserPreferredUILanguages( MUI_LANGUAGE_NAME, &mut num_languages, buffer.as_mut_ptr(), &mut buffer_length, ) } == TRUE; if success { // SAFETY: Windows wrote the required length worth of UTF-16 into our buffer, which initialized it. unsafe { buffer.set_len(buffer_length as usize) }; // The buffer contains names split by null char (0), and ends with two null chars (00) for part in buffer.split(|i| *i == 0).filter(|p| !p.is_empty()) { if let Ok(locale) = String::from_utf16(part) { result.push(locale); } } } result.into_iter() } sys-locale-0.3.2/src/windows_sys.rs000064400000000000000000000010111046102023000154170ustar 00000000000000// Bindings generated by `windows-bindgen` 0.51.1 #![allow( non_snake_case, non_upper_case_globals, non_camel_case_types, dead_code, clippy::all )] #[link(name = "kernel32")] extern "system" { pub fn GetUserPreferredUILanguages( dwflags: u32, pulnumlanguages: *mut u32, pwszlanguagesbuffer: PWSTR, pcchlanguagesbuffer: *mut u32, ) -> BOOL; } pub type BOOL = i32; pub const MUI_LANGUAGE_NAME: u32 = 8u32; pub type PWSTR = *mut u16; pub const TRUE: BOOL = 1i32;