sys-locale-0.3.1/.cargo_vcs_info.json0000644000000001360000000000100131100ustar { "git": { "sha1": "62e206f6f7d6c1c17208bbb6cbdd3c01f6b39c43" }, "path_in_vcs": "" }sys-locale-0.3.1/.github/workflows/audit.yml000064400000000000000000000006331046102023000171300ustar 00000000000000name: Security audit permissions: contents: read on: schedule: - cron: '0 0 * * 0' push: paths: - '**/Cargo.toml' - '**/Cargo.lock' pull_request: jobs: audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/audit-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }}sys-locale-0.3.1/.github/workflows/ci.yml000064400000000000000000000112101046102023000164060ustar 00000000000000on: push: branches: - main pull_request: name: CI permissions: contents: read jobs: clippy: name: Clippy ${{ matrix.rust }} / ${{ matrix.triple.target }} runs-on: ${{ matrix.triple.os }} strategy: matrix: # Borrowed from https://github.com/GuillaumeGomez/sysinfo/blob/master/.github/workflows/CI.yml#L45 triple: - { os: 'ubuntu-latest', target: 'x86_64-unknown-linux-gnu', cross: false } - { os: 'ubuntu-latest', target: 'i686-unknown-linux-gnu', cross: true } - { os: 'macos-latest', target: 'x86_64-apple-darwin', cross: false } - { os: 'windows-latest', target: 'x86_64-pc-windows-msvc', cross: false } # iOS - { os: 'macos-latest', target: 'aarch64-apple-ios', cross: true } - { os: 'macos-latest', target: 'x86_64-apple-ios', cross: true } ## ARM64 - { os: 'ubuntu-latest', target: 'aarch64-unknown-linux-gnu', cross: true } - { os: 'ubuntu-latest', target: 'aarch64-unknown-linux-musl', cross: true } ## ARMv7 - { os: 'ubuntu-latest', target: 'armv7-unknown-linux-gnueabihf', cross: true } - { os: 'ubuntu-latest', target: 'armv7-unknown-linux-musleabihf', cross: true } ## ARMv6 - { os: 'ubuntu-latest', target: 'arm-unknown-linux-gnueabihf', cross: true } - { os: 'ubuntu-latest', target: 'arm-unknown-linux-musleabihf', cross: true } # Android - { os: 'ubuntu-latest', target: 'aarch64-linux-android', cross: true } - { os: 'ubuntu-latest', target: 'armv7-linux-androideabi', cross: true } - { os: 'ubuntu-latest', target: 'x86_64-linux-android', cross: true } - { os: 'ubuntu-latest', target: 'i686-linux-android', cross: true } # WASM - { os: 'ubuntu-latest', target: 'wasm32-unknown-unknown', cross: false, always_install_target: true } rust: - stable # MSRV - 1.48.0 steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.rust }} components: clippy - name: Install cross-target if: matrix.triple.cross || matrix.triple.always_install_target run: rustup target add ${{ matrix.triple.target }} - uses: actions-rs/cargo@v1 with: command: clippy args: --target=${{ matrix.triple.target }} --manifest-path=Cargo.toml -- -D clippy::dbg_macro -D warnings -D missing_docs -F unused_must_use use-cross: ${{ matrix.triple.cross }} test: name: Test Desktop OSes strategy: matrix: os: - ubuntu-latest - macos-latest - windows-latest runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable - uses: actions-rs/cargo@v1 with: command: test test_wasm: name: Test wasm32-unknown-unknown runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable - name: Install wasm-pack run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh - name: Test wasm32 run: | rustup target add wasm32-unknown-unknown wasm-pack test --firefox --headless -- --features "js" test_fallback: name: Check fallback implementation runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable - name: "Clippy" # Install a target that is obviously not supported and then check it to ensure # the fallback target stays in sync with the other platforms. run: | rustup target add x86_64-unknown-none cargo clippy --target x86_64-unknown-none -- -D clippy::dbg_macro -D warnings -D missing_docs -F unused_must_use fmt: name: Rustfmt runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: persist-credentials: false - uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: stable components: rustfmt - uses: actions-rs/cargo@v1 with: command: fmt args: --all -- --check sys-locale-0.3.1/.gitignore000064400000000000000000000000341046102023000136650ustar 00000000000000/target /*/target Cargo.locksys-locale-0.3.1/CHANGELOG.md000064400000000000000000000043711046102023000135160ustar 00000000000000# sys-locale changelog Notable changes to this project will be documented in the [keep a changelog](https://keepachangelog.com/en/1.0.0/) format. ## [Unreleased] ## [0.3.1] - 2023-08-27 ### Added - Added support for getting a list of user locales in their preferred order via `get_locales`. - Additional locales are currently supported on iOS, macOS, WASM, and Windows. Other platforms will only return a single locale like `get_locale` does. ### Changed - Removed `windows-sys` dependency ## [0.3.0] - 2023-04-04 ### Changed - The crate now only uses `wasm-bindgen` when targeting WebAssembly on the web. Use the new `js` feature to target the web. ### Fixed - The crate now compiles for unsupported platforms. - Cleaned up typos and grammar in README. # [0.2.4] - 2023-03-07 ### Changed - Removed dependency on the `winapi` crate in favor of `windows-sys`, following more of the wider ecosystem. ## [0.2.3] - 2022-11-06 ### Fixed - Re-release 0.2.2 and correctly maintain `no_std` compatibility on Apple targets. ## [0.2.2] - 2022-11-06 ### Changed - The Apple backend has been rewritten in pure Rust instead of Objective-C. ### Fixed - The locale returned on UNIX systems is now always a correctly formatted BCP-47 tag. ## [0.2.1] - 2022-06-16 ### Added - The crate now supports being used via WASM in a WebWorker environment. ## [0.2.0] - 2022-03-01 ### Fixed - Fixed a soundness issue on Linux and BSDs by querying the environment directly instead of using libc setlocale. The libc setlocale is not safe for use in a multi-threaded context. ### Changed - No longer `no_std` on Linux and BSDs ## [0.1.0] - 2021-05-13 Initial release [Unreleased]: https://github.com/1Password/sys-locale/compare/v0.3.1...HEAD [0.1.0]: https://github.com/1Password/sys-locale/releases/tag/v0.1.0 [0.2.0]: https://github.com/1Password/sys-locale/releases/tag/v0.2.0 [0.2.1]: https://github.com/1Password/sys-locale/releases/tag/v0.2.1 [0.2.2]: https://github.com/1Password/sys-locale/releases/tag/v0.2.2 [0.2.3]: https://github.com/1Password/sys-locale/releases/tag/v0.2.3 [0.2.4]: https://github.com/1Password/sys-locale/releases/tag/v0.2.4 [0.3.0]: https://github.com/1Password/sys-locale/releases/tag/v0.3.0 [0.3.1]: https://github.com/1Password/sys-locale/releases/tag/v0.3.1 sys-locale-0.3.1/Cargo.lock0000644000000122250000000000100110650ustar # 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.1" 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.1/Cargo.toml0000644000000027360000000000100111160ustar # 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" name = "sys-locale" version = "0.3.1" authors = ["1Password"] 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" [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.1/Cargo.toml.orig000064400000000000000000000016231046102023000145710ustar 00000000000000[package] name = "sys-locale" version = "0.3.1" 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" # 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.1/LICENSE-APACHE000064400000000000000000000261351046102023000136330ustar 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.1/LICENSE-MIT000064400000000000000000000020521046102023000133330ustar 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.1/README.md000064400000000000000000000036011046102023000131570ustar 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.48+-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 - 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.48.0. This will be bumped to the latest 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.1/examples/get_locale.rs000064400000000000000000000004751046102023000161700ustar 00000000000000//! A small example to run on your computer to see what locale the library returns. #![allow(unknown_lints)] #![allow(clippy::uninlined_format_args)] use sys_locale::get_locale; fn main() { let locale = get_locale().unwrap_or_else(|| String::from("en-US")); println!("The current locale is {}", locale); } sys-locale-0.3.1/src/android.rs000064400000000000000000000046631046102023000144660ustar 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.1/src/apple.rs000064400000000000000000000120231046102023000141340ustar 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.1/src/lib.rs000064400000000000000000000065761046102023000136210ustar 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 //! - macOS //! - Linux, BSD, and other UNIX variations //! - WebAssembly on the web (via the `js` feature) //! - Windows #![cfg_attr( any( not(unix), target_os = "macos", target_os = "ios", 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(any(target_os = "macos", target_os = "ios"))] mod apple; #[cfg(any(target_os = "macos", target_os = "ios"))] use apple as provider; #[cfg(all( unix, not(any(target_os = "macos", target_os = "ios", target_os = "android")) ))] mod unix; #[cfg(all( unix, not(any(target_os = "macos", target_os = "ios", 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 active locale for the system or application. /// /// This may be equivalent to `get_locales().next()` (the first entry), /// depending on the platform. /// /// # 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 a `Vec` with any number of BCP-47 language tags inside. /// If no locale preferences could be obtained, the vec 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.1/src/unix.rs000064400000000000000000000054341046102023000140260ustar 00000000000000#![allow(unknown_lints)] use std::{env, ffi::OsStr}; const LC_ALL: &str = "LC_ALL"; const LC_CTYPE: &str = "LC_CTYPE"; 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).into_iter() } fn _get(env: &impl EnvAccess) -> Option { let code = env .get(LC_ALL) .or_else(|| env.get(LC_CTYPE)) .or_else(|| env.get(LANG))?; parse_locale_code(&code) } fn parse_locale_code(code: &str) -> Option { // Some locales are returned with the char encoding too: `en_US.UTF-8` // TODO: Once we bump MSRV >= 1.52, remove this allow and clean up #[allow(clippy::manual_split_once)] #[allow(clippy::needless_splitn)] code.splitn(2, '.').next().map(|s| s.replace('_', "-")) } #[cfg(test)] mod tests { use super::{parse_locale_code, EnvAccess, _get, LANG, LC_ALL, LC_CTYPE}; 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 PARSE_LOCALE: &str = "fr-FR"; const LANG_PARSE_LOCALE: &str = "fr_FR"; #[test] fn parse_identifier() { let identifier = "fr_FR.UTF-8"; assert_eq!(parse_locale_code(identifier).as_deref(), Some(PARSE_LOCALE)); } #[test] fn parse_non_suffixed_identifier() { assert_eq!( parse_locale_code(PARSE_LOCALE).as_deref(), Some(PARSE_LOCALE) ); assert_eq!( parse_locale_code(LANG_PARSE_LOCALE).as_deref(), Some(PARSE_LOCALE) ); } #[test] fn env_priority() { let mut env = MockEnv::new(); assert_eq!(_get(&env), None); // These locale names are technically allowed and some systems may still // defined aliases such as these but the glibc sources mention that this // should be considered deprecated env.insert(LANG.into(), "invalid".to_owned()); assert_eq!(_get(&env).as_deref(), Some("invalid")); env.insert(LC_CTYPE.into(), "invalid-also".to_owned()); assert_eq!(_get(&env).as_deref(), Some("invalid-also")); env.insert(LC_ALL.into(), "invalid-again".to_owned()); assert_eq!(_get(&env).as_deref(), Some("invalid-again")); } } sys-locale-0.3.1/src/wasm.rs000064400000000000000000000034241046102023000140070ustar 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.1/src/windows.rs000064400000000000000000000026631046102023000145360ustar 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::::new(); buffer.resize(buffer_length as usize, 0); // 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 { // 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.1/src/windows_sys.rs000064400000000000000000000010111046102023000154160ustar 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; sys-locale-0.3.1/tests/wasm_worker.rs000064400000000000000000000007361046102023000157560ustar 00000000000000#![cfg(all(target_family = "wasm", feature = "js", not(unix)))] use wasm_bindgen_test::wasm_bindgen_test as test; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_worker); use sys_locale::{get_locale, get_locales}; #[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); } }