os_str_bytes-7.1.0/.cargo_vcs_info.json0000644000000001360000000000100135600ustar { "git": { "sha1": "8e9c684a9eba3b656731d62b1fd72228134d626a" }, "path_in_vcs": "" }os_str_bytes-7.1.0/COPYRIGHT000064400000000000000000000004161046102023000136440ustar 00000000000000Copyright (c) 2019 dylni (https://github.com/dylni) Licensed under the Apache License, Version 2.0 or the MIT license , at your option. All files in this project may not be copied, modified, or distributed except according to those terms. os_str_bytes-7.1.0/Cargo.lock0000644000000127210000000000100115360ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bitflags" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "errno" version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" [[package]] name = "getrandom" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" dependencies = [ "cfg-if", "libc", "wasi", "windows-targets", ] [[package]] name = "lazy_static" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" version = "0.2.169" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" [[package]] name = "linux-raw-sys" version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" [[package]] name = "memchr" version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "once_cell" version = "1.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e" [[package]] name = "os_str_bytes" version = "7.1.0" dependencies = [ "fastrand", "lazy_static", "memchr", "tempfile", ] [[package]] name = "rustix" version = "0.38.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "tempfile" version = "3.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22e5a0acb1f3f55f65cc4a866c361b2fb2a0ff6366785ae6fbb5f85df07ba230" dependencies = [ "cfg-if", "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "wasi" version = "0.13.3+wasi-0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "wit-bindgen-rt" version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ "bitflags", ] os_str_bytes-7.1.0/Cargo.toml0000644000000032450000000000100115620ustar # 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 = "2021" rust-version = "1.74.0" name = "os_str_bytes" version = "7.1.0" authors = ["dylni"] build = false exclude = [ ".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ Lossless functionality for platform-native strings """ readme = "README.md" keywords = [ "bytes", "osstr", "osstring", "path", "windows", ] categories = [ "command-line-interface", "development-tools::ffi", "encoding", "os", "rust-patterns", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dylni/os_str_bytes" [package.metadata.docs.rs] all-features = true rustc-args = [ "--cfg", "os_str_bytes_docs_rs", ] rustdoc-args = [ "--cfg", "os_str_bytes_docs_rs", ] [lib] name = "os_str_bytes" path = "src/lib.rs" [dependencies.memchr] version = "2.3.5" optional = true [dev-dependencies.fastrand] version = "2.0" [dev-dependencies.lazy_static] version = "1.0.3" [dev-dependencies.tempfile] version = "3.8" [features] checked_conversions = ["conversions"] conversions = [] default = [ "memchr", "raw_os_str", ] raw_os_str = [] os_str_bytes-7.1.0/Cargo.toml.orig000064400000000000000000000016311046102023000152400ustar 00000000000000[package] name = "os_str_bytes" version = "7.1.0" authors = ["dylni"] edition = "2021" rust-version = "1.74.0" description = """ Lossless functionality for platform-native strings """ readme = "README.md" repository = "https://github.com/dylni/os_str_bytes" license = "MIT OR Apache-2.0" keywords = ["bytes", "osstr", "osstring", "path", "windows"] categories = ["command-line-interface", "development-tools::ffi", "encoding", "os", "rust-patterns"] exclude = [".*", "tests.rs", "/rustfmt.toml", "/src/bin", "/tests"] [package.metadata.docs.rs] all-features = true rustc-args = ["--cfg", "os_str_bytes_docs_rs"] rustdoc-args = ["--cfg", "os_str_bytes_docs_rs"] [dependencies] memchr = { version = "2.3.5", optional = true } [dev-dependencies] fastrand = "2.0" lazy_static = "1.0.3" tempfile = "3.8" [features] default = ["memchr", "raw_os_str"] checked_conversions = ["conversions"] conversions = [] raw_os_str = [] os_str_bytes-7.1.0/LICENSE-APACHE000064400000000000000000000236751046102023000143110ustar 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 os_str_bytes-7.1.0/LICENSE-MIT000064400000000000000000000021011046102023000137760ustar 00000000000000MIT License Copyright (c) 2019 dylni (https://github.com/dylni) 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. os_str_bytes-7.1.0/README.md000064400000000000000000000062251046102023000136340ustar 00000000000000# OsStr Bytes This crate provides additional functionality for [`OsStr`] and [`OsString`], without resorting to panics or corruption for invalid UTF-8. Thus, familiar methods from [`str`] and [`String`] can be used. [![GitHub Build Status](https://github.com/dylni/os_str_bytes/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/dylni/os_str_bytes/actions/workflows/build.yml?query=branch%3Amaster) ## Usage Add the following lines to your "Cargo.toml" file: ```toml [dependencies] os_str_bytes = "7.1" ``` See the [documentation] for available functionality and examples. ## Rust version support The minimum supported Rust toolchain version depends on the platform:
Target Target Triple Minimum Version
Fortanix *-fortanix-*-sgx nightly (sgx_platform)
HermitCore *-*-hermit nightly (rust-toolchain.toml)
SOLID *-*-solid_asp3(-*) 1.74.0
UEFI *-*-uefi nightly (uefi_std)
Unix Unix 1.74.0
WASI *-wasi* 1.74.0
WebAssembly wasm32-*-unknown 1.74.0
Windows *-*-windows-* 1.74.0
Xous *-*-xous-* 1.74.0
Minor version updates may increase these version requirements. However, the previous two Rust releases will always be supported. If the minimum Rust version must not be increased, use a tilde requirement to prevent updating this crate's minor version: ```toml [dependencies] os_str_bytes = "~7.1" ``` ## License Licensing terms are specified in [COPYRIGHT]. Unless you explicitly state otherwise, any contribution submitted for inclusion in this crate, as defined in [LICENSE-APACHE], shall be licensed according to [COPYRIGHT], without any additional terms or conditions. [COPYRIGHT]: https://github.com/dylni/os_str_bytes/blob/master/COPYRIGHT [documentation]: https://docs.rs/os_str_bytes [LICENSE-APACHE]: https://github.com/dylni/os_str_bytes/blob/master/LICENSE-APACHE [`OsStr`]: https://doc.rust-lang.org/std/ffi/struct.OsStr.html [`OsString`]: https://doc.rust-lang.org/std/ffi/struct.OsString.html [`str`]: https://doc.rust-lang.org/std/primitive.str.html [`String`]: https://doc.rust-lang.org/std/string/struct.String.html os_str_bytes-7.1.0/src/common/convert.rs000064400000000000000000000013151046102023000164550ustar 00000000000000use std::borrow::Cow; use std::convert::Infallible; use std::ffi::OsStr; use std::ffi::OsString; use std::result; use super::os::ffi::OsStrExt; use super::os::ffi::OsStringExt; pub(crate) type EncodingError = Infallible; pub(crate) type Result = result::Result; pub(crate) fn os_str_from_bytes(string: &[u8]) -> Result> { Ok(Cow::Borrowed(OsStr::from_bytes(string))) } pub(crate) fn os_str_to_bytes(string: &OsStr) -> Cow<'_, [u8]> { Cow::Borrowed(string.as_bytes()) } pub(crate) fn os_string_from_vec(string: Vec) -> Result { Ok(OsString::from_vec(string)) } pub(crate) fn os_string_into_vec(string: OsString) -> Vec { string.into_vec() } os_str_bytes-7.1.0/src/common/convert_io.rs000064400000000000000000000013651046102023000171510ustar 00000000000000use std::borrow::Cow; use std::ffi::OsStr; use std::ffi::OsString; use super::os::ffi::OsStrExt; use super::os::ffi::OsStringExt; pub(crate) fn os_str_from_bytes(string: &[u8]) -> Option<&OsStr> { Some(OsStr::from_bytes(string)) } pub(crate) fn os_str_to_bytes(string: &OsStr) -> Option<&'_ [u8]> { Some(string.as_bytes()) } pub(crate) fn os_str_to_bytes_lossy(string: &OsStr) -> Cow<'_, [u8]> { Cow::Borrowed(string.as_bytes()) } pub(crate) fn os_string_from_vec(string: Vec) -> Option { Some(OsString::from_vec(string)) } pub(crate) fn os_string_into_vec(string: OsString) -> Option> { Some(string.into_vec()) } pub(crate) fn os_string_into_vec_lossy(string: OsString) -> Vec { string.into_vec() } os_str_bytes-7.1.0/src/common/mod.rs000064400000000000000000000007401046102023000155550ustar 00000000000000#[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] use std::os::fortanix_sgx as os; #[cfg(target_os = "hermit")] use std::os::hermit as os; #[cfg(target_os = "solid_asp3")] use std::os::solid as os; #[cfg(unix)] use std::os::unix as os; #[cfg(target_os = "wasi")] use std::os::wasi as os; #[cfg(target_os = "xous")] use std::os::xous as os; pub(super) mod convert_io; if_conversions! { pub(super) mod convert; if_raw_str! { pub(super) mod raw; } } os_str_bytes-7.1.0/src/common/raw.rs000064400000000000000000000003031046102023000155620ustar 00000000000000pub(crate) fn ends_with(string: &[u8], suffix: &[u8]) -> bool { string.ends_with(suffix) } pub(crate) fn starts_with(string: &[u8], prefix: &[u8]) -> bool { string.starts_with(prefix) } os_str_bytes-7.1.0/src/ext.rs000064400000000000000000000527621046102023000143210ustar 00000000000000use std::ffi::OsStr; use std::ffi::OsString; use std::iter; use std::mem; use std::ops::Range; use std::ops::RangeFrom; use std::ops::RangeFull; use std::ops::RangeInclusive; use std::ops::RangeTo; use std::ops::RangeToInclusive; use std::str; use super::iter::RSplit; use super::iter::Split; use super::iter::Utf8Chunks; use super::pattern::Encoded as EncodedPattern; use super::util; use super::util::MAX_UTF8_LENGTH; use super::OsStrBytes; use super::Pattern; if_conversions! { use super::imp::raw; } fn is_boundary(string: &OsStr, index: usize) -> bool { let string = string.as_encoded_bytes(); debug_assert!(index < string.len()); if index == 0 { return true; } let byte = string[index]; if byte.is_ascii() { return true; } if !util::is_continuation(byte) { let bytes = &string[index..]; if !str::from_utf8(&bytes[..bytes.len().min(MAX_UTF8_LENGTH)]) .is_err_and(|x| x.valid_up_to() == 0) { return true; } } (0..index) .rev() .take(MAX_UTF8_LENGTH) .find(|&x| !util::is_continuation(string[x])) .is_some_and(|x| str::from_utf8(&string[x..index]).is_ok()) } #[track_caller] pub(super) fn check_bound(string: &OsStr, index: usize) { assert!( index >= string.as_encoded_bytes().len() || is_boundary(string, index), "byte index {} is not a valid boundary", index, ); } macro_rules! r#impl { ( $($name:ident),+ ) => { $( #[cfg(feature = "memchr")] use memchr::memmem::$name; #[cfg(not(feature = "memchr"))] fn $name(string: &[u8], pat: &[u8]) -> Option { (pat.len()..=string.len()) .$name(|&x| string[..x].ends_with(pat)) .map(|x| x - pat.len()) } )+ }; } r#impl!(find, rfind); pub(super) unsafe fn os_str(string: &[u8]) -> &OsStr { // SAFETY: This function has equivalent safety requirements. unsafe { OsStr::from_encoded_bytes_unchecked(string) } } fn split_once<'a, 'b, P>( string: &'a OsStr, pat: &'b P, find_fn: fn(&OsStr, &'b str) -> Option, ) -> Option<(&'a OsStr, &'a OsStr)> where P: EncodedPattern, { let pat = pat.__as_str(); let index = find_fn(string, pat)?; let string = string.as_encoded_bytes(); let prefix = &string[..index]; let suffix = &string[index + pat.len()..]; // SAFETY: These substrings were separated by a UTF-8 string. Some(unsafe { (os_str(prefix), os_str(suffix)) }) } fn trim_matches<'a, 'b, P>( mut string: &'a OsStr, pat: &'b P, strip_fn: for<'c> fn(&'c OsStr, &'b str) -> Option<&'c OsStr>, ) -> &'a OsStr where P: EncodedPattern, { let pat = pat.__as_str(); if !pat.is_empty() { while let Some(substring) = strip_fn(string, pat) { string = substring; } } string } fn trim_end_matches<'a, P>(string: &'a OsStr, pat: &P) -> &'a OsStr where P: EncodedPattern, { trim_matches(string, pat, OsStrBytesExt::strip_suffix) } fn trim_start_matches<'a, P>(string: &'a OsStr, pat: &P) -> &'a OsStr where P: EncodedPattern, { trim_matches(string, pat, OsStrBytesExt::strip_prefix) } /// An extension trait providing additional methods to [`OsStr`]. /// /// In most cases, this trait will prevent needing to call /// [`OsStr::as_encoded_bytes`] and potentially violating invariants of the /// internal encoding for [`OsStr`]. /// /// # Indices /// /// Methods of this struct that accept indices require that the index lie on a /// UTF-8 boundary. Although it is possible to manipulate platform strings /// based on other indices, this crate currently does not support them for /// slicing methods. They are not currently possible to support safely and are /// generally not necessary. However, all indices returned by this trait can be /// passed to other methods. /// /// # Complexity /// /// All searching methods have worst-case multiplicative time complexity (i.e., /// `O(self.len() * pat.len())`). Enabling the "memchr" feature allows these /// methods to instead run in linear time in the worst case (documented for /// [`memchr::memmem::find`][memchr_complexity]). /// /// [memchr_complexity]: ::memchr::memmem::find#complexity #[cfg_attr(not(feature = "conversions"), allow(private_bounds))] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] pub trait OsStrBytesExt: OsStrBytes { /// Equivalent to [`str::contains`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert!(os_string.contains("oo")); /// assert!(!os_string.contains("of")); /// ``` #[must_use] fn contains

(&self, pat: P) -> bool where P: Pattern; /// Equivalent to [`str::ends_with`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert!(os_string.ends_with("bar")); /// assert!(!os_string.ends_with("foo")); /// ``` #[must_use] fn ends_with

(&self, pat: P) -> bool where P: Pattern; if_conversions! { /// Equivalent to [`str::ends_with`] but accepts this type for the /// pattern. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert!(os_string.ends_with_os(OsStr::new("bar"))); /// assert!(!os_string.ends_with_os(OsStr::new("foo"))); /// ``` #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "conversions")) )] #[must_use] fn ends_with_os(&self, pat: &Self) -> bool; } /// Equivalent to [`str::find`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!(Some(1), os_string.find("o")); /// assert_eq!(None, os_string.find("of")); /// ``` #[must_use] fn find

(&self, pat: P) -> Option where P: Pattern; /// Equivalent to [`str::get_unchecked`]. /// /// # Safety /// /// The index must be a [valid boundary]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!("foo", unsafe { os_string.get_unchecked(..3) }); /// assert_eq!("bar", unsafe { os_string.get_unchecked(3..) }); /// ``` /// /// [valid boundary]: #indices #[must_use] #[track_caller] unsafe fn get_unchecked(&self, index: I) -> &Self where I: SliceIndex; /// Equivalent to the [`Index::index`] implementation for [`prim@str`]. /// /// # Panics /// /// Panics if the index is not a [valid boundary]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!("foo", os_string.index(..3)); /// assert_eq!("bar", os_string.index(3..)); /// ``` /// /// [`Index::index`]: ::std::ops::Index::index /// [valid boundary]: #indices #[must_use] #[track_caller] fn index(&self, index: I) -> &Self where I: SliceIndex; /// Equivalent to [`str::repeat`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foo"); /// assert_eq!("foofoofoo", os_string.repeat(3)); /// ``` #[must_use] fn repeat(&self, n: usize) -> Self::Owned; /// Equivalent to [`str::rfind`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!(Some(2), os_string.rfind("o")); /// assert_eq!(None, os_string.rfind("of")); /// ``` #[must_use] fn rfind

(&self, pat: P) -> Option where P: Pattern; /// Equivalent to [`str::rsplit`], but empty patterns are not accepted. /// /// # Panics /// /// Panics if the pattern is empty. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.rsplit("o").eq(["bar", "", "f"])); /// ``` #[track_caller] fn rsplit

(&self, pat: P) -> RSplit<'_, P> where P: Pattern; /// Equivalent to [`str::rsplit_once`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!( /// Some((OsStr::new("fo"), OsStr::new("bar"))), /// os_string.rsplit_once("o"), /// ); /// assert_eq!(None, os_string.rsplit_once("of")); /// ``` #[must_use] fn rsplit_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern; /// Equivalent to [`str::split`], but empty patterns are not accepted. /// /// # Panics /// /// Panics if the pattern is empty. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.split("o").eq(["f", "", "bar"])); /// ``` #[track_caller] fn split

(&self, pat: P) -> Split<'_, P> where P: Pattern; /// Equivalent to [`str::split_at`]. /// /// # Panics /// /// Panics if the index is not a [valid boundary]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!( /// (OsStr::new("fo"), OsStr::new("obar")), /// os_string.split_at(2), /// ); /// ``` /// /// [valid boundary]: #indices #[must_use] #[track_caller] fn split_at(&self, mid: usize) -> (&Self, &Self); /// Equivalent to [`str::split_once`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert_eq!( /// Some((OsStr::new("f"), OsStr::new("obar"))), /// os_string.split_once("o"), /// ); /// assert_eq!(None, os_string.split_once("of")); /// ``` #[must_use] fn split_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern; /// Equivalent to [`str::starts_with`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert!(os_string.starts_with("foo")); /// assert!(!os_string.starts_with("bar")); /// ``` #[must_use] fn starts_with

(&self, pat: P) -> bool where P: Pattern; if_conversions! { /// Equivalent to [`str::starts_with`] but accepts this type for the /// pattern. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("foobar"); /// assert!(os_string.starts_with_os(OsStr::new("foo"))); /// assert!(!os_string.starts_with_os(OsStr::new("bar"))); /// ``` #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "conversions")) )] #[must_use] fn starts_with_os(&self, pat: &Self) -> bool; } /// Equivalent to [`str::strip_prefix`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("111foo1bar111"); /// assert_eq!( /// Some(OsStr::new("11foo1bar111")), /// os_string.strip_prefix("1"), /// ); /// assert_eq!(None, os_string.strip_prefix("o")); /// ``` #[must_use] fn strip_prefix

(&self, pat: P) -> Option<&Self> where P: Pattern; /// Equivalent to [`str::strip_suffix`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("111foo1bar111"); /// assert_eq!( /// Some(OsStr::new("111foo1bar11")), /// os_string.strip_suffix("1"), /// ); /// assert_eq!(None, os_string.strip_suffix("o")); /// ``` #[must_use] fn strip_suffix

(&self, pat: P) -> Option<&Self> where P: Pattern; /// Equivalent to [`str::trim_end_matches`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("111foo1bar111"); /// assert_eq!("111foo1bar", os_string.trim_end_matches("1")); /// assert_eq!("111foo1bar111", os_string.trim_end_matches("o")); /// ``` #[must_use] fn trim_end_matches

(&self, pat: P) -> &Self where P: Pattern; /// Equivalent to [`str::trim_matches`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("111foo1bar111"); /// assert_eq!("foo1bar", os_string.trim_matches("1")); /// assert_eq!("111foo1bar111", os_string.trim_matches("o")); /// ``` #[must_use] fn trim_matches

(&self, pat: P) -> &Self where P: Pattern; /// Equivalent to [`str::trim_start_matches`]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// let os_string = OsStr::new("111foo1bar111"); /// assert_eq!("foo1bar111", os_string.trim_start_matches("1")); /// assert_eq!("111foo1bar111", os_string.trim_start_matches("o")); /// ``` #[must_use] fn trim_start_matches

(&self, pat: P) -> &Self where P: Pattern; /// Splits this string into platform and UTF-8 substrings. /// /// The iterator returned by this method is very similar to /// [`str::Utf8Chunks`]. However, the [`OsStr`] portion of each chunk /// precedes the [`prim@str`] portion and has no length restrictions. /// /// The [`OsStr`] portion of each chunk can be empty only at the start of a /// string, and the [`prim@str`] portion at the end of a string. They will /// never be empty simultaneously. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytesExt; /// /// fn to_str_lossy(os_string: &OsStr, mut push: F) /// where /// F: FnMut(&str), /// { /// for (invalid, string) in os_string.utf8_chunks() { /// if !invalid.as_os_str().is_empty() { /// push("\u{FFFD}"); /// } /// /// push(string); /// } /// } /// ``` fn utf8_chunks(&self) -> Utf8Chunks<'_>; } impl OsStrBytesExt for OsStr { #[inline] fn contains

(&self, pat: P) -> bool where P: Pattern, { self.find(pat).is_some() } #[inline] fn ends_with

(&self, pat: P) -> bool where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); self.as_encoded_bytes().ends_with(pat) } if_conversions! { #[inline] fn ends_with_os(&self, pat: &Self) -> bool { raw::ends_with(&self.to_raw_bytes(), &pat.to_raw_bytes()) } } #[inline] fn find

(&self, pat: P) -> Option where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); find(self.as_encoded_bytes(), pat) } #[inline] unsafe fn get_unchecked(&self, index: I) -> &Self where I: SliceIndex, { // SAFETY: This method has equivalent safety requirements. unsafe { index.get_unchecked(self) } } #[inline] fn index(&self, index: I) -> &Self where I: SliceIndex, { index.index(self) } #[inline] fn repeat(&self, n: usize) -> Self::Owned { let mut string = OsString::new(); string.extend(iter::repeat(self).take(n)); string } #[inline] fn rfind

(&self, pat: P) -> Option where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); rfind(self.as_encoded_bytes(), pat) } #[inline] fn rsplit

(&self, pat: P) -> RSplit<'_, P> where P: Pattern, { RSplit::new(self, pat) } #[inline] fn rsplit_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern, { split_once(self, &pat.__encode(), Self::rfind) } #[inline] fn split

(&self, pat: P) -> Split<'_, P> where P: Pattern, { Split::new(self, pat) } #[inline] fn split_at(&self, mid: usize) -> (&Self, &Self) { check_bound(self, mid); let (prefix, suffix) = self.as_encoded_bytes().split_at(mid); // SAFETY: These substrings were separated by a valid boundary. unsafe { (os_str(prefix), os_str(suffix)) } } #[inline] fn split_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern, { split_once(self, &pat.__encode(), Self::find) } #[inline] fn starts_with

(&self, pat: P) -> bool where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); self.as_encoded_bytes().starts_with(pat) } if_conversions! { #[inline] fn starts_with_os(&self, pat: &Self) -> bool { raw::starts_with(&self.to_raw_bytes(), &pat.to_raw_bytes()) } } #[inline] fn strip_prefix

(&self, pat: P) -> Option<&Self> where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); // SAFETY: This substring was separated by a UTF-8 string. self.as_encoded_bytes() .strip_prefix(pat) .map(|x| unsafe { os_str(x) }) } #[inline] fn strip_suffix

(&self, pat: P) -> Option<&Self> where P: Pattern, { let pat = pat.__encode(); let pat = pat.__as_bytes(); // SAFETY: This substring was separated by a UTF-8 string. self.as_encoded_bytes() .strip_suffix(pat) .map(|x| unsafe { os_str(x) }) } #[inline] fn trim_end_matches

(&self, pat: P) -> &Self where P: Pattern, { trim_end_matches(self, &pat.__encode()) } #[inline] fn trim_matches

(&self, pat: P) -> &Self where P: Pattern, { let pat = pat.__encode(); trim_end_matches(trim_start_matches(self, &pat), &pat) } #[inline] fn trim_start_matches

(&self, pat: P) -> &Self where P: Pattern, { trim_start_matches(self, &pat.__encode()) } #[inline] fn utf8_chunks(&self) -> Utf8Chunks<'_> { Utf8Chunks::new(self) } } pub trait SliceIndex { unsafe fn get_unchecked(self, string: &OsStr) -> &OsStr; fn index(self, string: &OsStr) -> &OsStr; } macro_rules! r#impl { ( $type:ty $(, $var:ident , $($bound:expr),+)? ) => { impl SliceIndex for $type { #[inline] unsafe fn get_unchecked(self, string: &OsStr) -> &OsStr { // SAFETY: This method has equivalent safety requirements. unsafe { os_str(string.as_encoded_bytes().get_unchecked(self)) } } #[inline] fn index(self, string: &OsStr) -> &OsStr { $( let $var = &self; $(check_bound(string, $bound);)+ )? // SAFETY: This substring is separated by valid boundaries. unsafe { os_str(&string.as_encoded_bytes()[self]) } } } }; } r#impl!(Range, x, x.start, x.end); r#impl!(RangeFrom, x, x.start); r#impl!(RangeFull); // [usize::MAX] will always be a valid inclusive end index. #[rustfmt::skip] r#impl!(RangeInclusive, x, *x.start(), x.end().wrapping_add(1)); r#impl!(RangeTo, x, x.end); r#impl!(RangeToInclusive, x, x.end.wrapping_add(1)); /// A container for platform strings containing no unicode characters. /// /// Instances can only be constructed using [`Utf8Chunks`]. #[derive(Debug)] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] #[repr(transparent)] pub struct NonUnicodeOsStr(OsStr); impl NonUnicodeOsStr { unsafe fn from_inner(string: &OsStr) -> &Self { // SAFETY: This struct has a layout that makes this operation safe. unsafe { mem::transmute(string) } } pub(super) unsafe fn new_unchecked(string: &[u8]) -> &Self { // SAFETY: This method has stricter safety requirements. unsafe { Self::from_inner(os_str(string)) } } /// Converts this representation back to a platform-native string, without /// copying or encoding conversion. #[inline] #[must_use] pub fn as_os_str(&self) -> &OsStr { &self.0 } } impl AsRef for NonUnicodeOsStr { #[inline] fn as_ref(&self) -> &OsStr { &self.0 } } os_str_bytes-7.1.0/src/iter.rs000064400000000000000000000145741046102023000144630ustar 00000000000000//! Iterators provided by this crate. #![cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] use std::ffi::OsStr; use std::fmt; use std::fmt::Debug; use std::fmt::Formatter; use std::iter::FusedIterator; use std::mem; use std::str; use super::ext; use super::pattern::Encoded; use super::NonUnicodeOsStr; use super::OsStrBytesExt; use super::Pattern; use super::RawOsStr; macro_rules! r#impl { ( $(#[ $attr:meta ])* $name:ident , $(#[ $raw_attr:meta ])* $raw_name:ident , $split_method:ident , $reverse:expr , ) => { // [memchr::memmem::FindIter] would make this struct self-referential. #[must_use] $(#[$attr])* pub struct $name<'a, P> where P: Pattern, { string: Option<&'a OsStr>, pat: P::__Encoded, } impl<'a, P> $name<'a, P> where P: Pattern, { #[track_caller] pub(super) fn new(string: &'a OsStr, pat: P) -> Self { let pat = pat.__encode(); assert!( !pat.__as_str().is_empty(), "cannot split using an empty pattern", ); Self { string: Some(string), pat, } } } impl

Clone for $name<'_, P> where P: Pattern, { #[inline] fn clone(&self) -> Self { Self { string: self.string, pat: self.pat.clone(), } } } impl

Debug for $name<'_, P> where P: Pattern, { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct(stringify!($name)) .field("string", &self.string) .field("pat", &self.pat) .finish() } } impl

FusedIterator for $name<'_, P> where P: Pattern {} impl<'a, P> Iterator for $name<'a, P> where P: Pattern, { type Item = &'a OsStr; #[inline] fn next(&mut self) -> Option { self.string? .$split_method(self.pat.__as_str()) .map(|(mut substring, mut string)| { if $reverse { mem::swap(&mut substring, &mut string); } self.string = Some(string); substring }) .or_else(|| self.string.take()) } } #[must_use] $(#[$raw_attr])* pub struct $raw_name<'a, P>($name<'a, P>) where P: Pattern; impl<'a, P> $raw_name<'a, P> where P: Pattern, { #[track_caller] pub(super) fn new(string: &'a RawOsStr, pat: P) -> Self { Self($name::new(string.as_os_str(), pat)) } } impl

Clone for $raw_name<'_, P> where P: Pattern, { #[inline] fn clone(&self) -> Self { Self(self.0.clone()) } } impl

Debug for $raw_name<'_, P> where P: Pattern, { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_tuple(stringify!($raw_name)).field(&self.0).finish() } } impl

FusedIterator for $raw_name<'_, P> where P: Pattern {} impl<'a, P> Iterator for $raw_name<'a, P> where P: Pattern, { type Item = &'a RawOsStr; #[inline] fn next(&mut self) -> Option { self.0.next().map(RawOsStr::new) } } }; } r#impl!( /// The iterator returned by [`OsStrBytesExt::split`]. Split, /// The iterator returned by [`RawOsStr::split`]. RawSplit, split_once, false, ); r#impl!( /// The iterator returned by [`OsStrBytesExt::rsplit`]. RSplit, /// The iterator returned by [`RawOsStr::rsplit`]. RawRSplit, rsplit_once, true, ); /// The iterator returned by [`OsStrBytesExt::utf8_chunks`]. /// /// [`OsStrBytesExt::utf8_chunks`]: super::OsStrBytesExt::utf8_chunks #[derive(Clone, Debug)] #[must_use] pub struct Utf8Chunks<'a> { string: &'a OsStr, invalid_length: usize, } impl<'a> Utf8Chunks<'a> { pub(super) fn new(string: &'a OsStr) -> Self { Self { string, invalid_length: 0, } } } impl FusedIterator for Utf8Chunks<'_> {} impl<'a> Iterator for Utf8Chunks<'a> { type Item = (&'a NonUnicodeOsStr, &'a str); fn next(&mut self) -> Option { let string = self.string.as_encoded_bytes(); if string.is_empty() { debug_assert_eq!(0, self.invalid_length); return None; } loop { let (invalid, substring) = string.split_at(self.invalid_length); let valid = match str::from_utf8(substring) { Ok(valid) => { self.string = OsStr::new(""); self.invalid_length = 0; valid } Err(error) => { let (valid, substring) = substring.split_at(error.valid_up_to()); let invalid_length = error.error_len().unwrap_or_else(|| substring.len()); if valid.is_empty() { self.invalid_length += invalid_length; continue; } // SAFETY: This substring was separated by a UTF-8 string. self.string = unsafe { ext::os_str(substring) }; self.invalid_length = invalid_length; // SAFETY: This slice was validated to be UTF-8. unsafe { str::from_utf8_unchecked(valid) } } }; // SAFETY: This substring was separated by a UTF-8 string and // validated to not be UTF-8. let invalid = unsafe { NonUnicodeOsStr::new_unchecked(invalid) }; return Some((invalid, valid)); } } } os_str_bytes-7.1.0/src/lib.rs000064400000000000000000000654311046102023000142640ustar 00000000000000//! This crate provides additional functionality for [`OsStr`] and //! [`OsString`], without resorting to panics or corruption for invalid UTF-8. //! Thus, familiar methods from [`str`] and [`String`] can be used. //! //! # Usage //! //! The most important trait included is [`OsStrBytesExt`], which provides //! methods analagous to those of [`str`] but for [`OsStr`]. These methods will //! never panic for invalid UTF-8 in a platform string, so they can be used to //! manipulate [`OsStr`] values with the same simplicity possible for [`str`]. //! //! Additionally, the following wrappers are provided. They are primarily //! legacy types from when this crate needed to perform more frequent encoding //! conversions. However, they may be useful for their trait implementations. //! - [`RawOsStr`] is a wrapper for [`OsStr`]. //! - [`RawOsString`] is a wrapper for [`OsString`]. //! //! # User Input //! //! Most methods in this crate should not be used to convert byte sequences //! that did not originate from [`OsStr`] or a related struct. The encoding //! used by this crate is an implementation detail, so it does not make sense //! to expose it to users. //! //! For user input with an unknown encoding similar to UTF-8, use the following //! IO-safe methods, which avoid errors when [writing to streams on //! Windows][windows_considerations]. These methods will not accept or return //! byte sequences that are invalid for input and output streams. Therefore, //! they can be used to convert between bytes strings exposed to users and //! platform strings. //! - [`OsStrBytes::from_io_bytes`] //! - [`OsStrBytes::to_io_bytes`] //! - [`OsStrBytes::to_io_bytes_lossy`] //! - [`OsStringBytes::from_io_vec`] //! - [`OsStringBytes::into_io_vec`] //! - [`OsStringBytes::into_io_vec_lossy`] //! //! # Features //! //! These features are optional and can be enabled or disabled in a //! "Cargo.toml" file. //! //! ### Default Features //! //! - **memchr** - //! Changes the implementation to use crate [memchr] for better performance. //! This feature is useless when the "raw\_os\_str" feature is disabled. //! //! For more information, see [`OsStrBytesExt`][memchr_complexity]. //! //! - **raw\_os\_str** - //! Provides: //! - [`iter`] //! - [`NonUnicodeOsStr`] //! - [`OsStrBytesExt`] //! - [`Pattern`] //! - [`RawOsStr`] //! - [`RawOsStrCow`] //! - [`RawOsString`] //! //! ### Optional Features //! //! - **checked\_conversions** - //! Provides: //! - [`EncodingError`] //! - [`OsStrBytes::from_raw_bytes`] //! - [`OsStringBytes::from_raw_vec`] //! - [`RawOsStr::cow_from_raw_bytes`] //! - [`RawOsString::from_raw_vec`] //! //! Because this feature should not be used in libraries, the //! "OS\_STR\_BYTES\_CHECKED\_CONVERSIONS" environment variable must be //! defined during compilation. //! //! - **conversions** - //! Provides methods that require encoding conversion and may be expensive: //! - [`OsStrBytesExt::ends_with_os`] //! - [`OsStrBytesExt::starts_with_os`] //! - [`RawOsStr::assert_cow_from_raw_bytes`] //! - [`RawOsStr::ends_with_os`] //! - [`RawOsStr::starts_with_os`] //! - [`RawOsStr::to_raw_bytes`] //! - [`RawOsString::assert_from_raw_vec`] //! - [`RawOsString::into_raw_vec`] //! - [`OsStrBytes::assert_from_raw_bytes`] //! - [`OsStrBytes::to_raw_bytes`] //! - [`OsStringBytes::assert_from_raw_vec`] //! - [`OsStringBytes::into_raw_vec`] //! //! For more information, see [Encoding Conversions]. //! //! # Implementation //! //! Some methods return [`Cow`] to account for platform differences. However, //! no guarantee is made that the same variant of that enum will always be //! returned for the same platform. Whichever can be constructed most //! efficiently will be returned. //! //! All traits are [sealed], meaning that they can only be implemented by this //! crate. Otherwise, backward compatibility would be more difficult to //! maintain for new features. //! //! # Encoding Conversions //! //! Methods provided by the "conversions" feature use an intentionally //! unspecified encoding. It may vary for different platforms, so defining it //! would run contrary to the goal of generic string handling. However, the //! following invariants will always be upheld: //! //! - The encoding will be compatible with UTF-8. In particular, splitting an //! encoded byte sequence by a UTF-8–encoded character always produces //! other valid byte sequences. They can be re-encoded without error using //! [`RawOsString::into_os_string`] and similar methods. //! //! - All characters valid in platform strings are representable. [`OsStr`] and //! [`OsString`] can always be losslessly reconstructed from extracted bytes. //! //! Note that the chosen encoding may not match how [`OsStr`] stores these //! strings internally, which is undocumented. For instance, the result of //! calling [`OsStr::len`] will not necessarily match the number of bytes this //! crate uses to represent the same string. However, unlike the encoding used //! by [`OsStr`], the encoding used by this crate can be validated safely using //! the following methods: //! - [`OsStrBytes::assert_from_raw_bytes`] //! - [`RawOsStr::assert_cow_from_raw_bytes`] //! - [`RawOsString::assert_from_raw_vec`] //! //! Concatenation may yield unexpected results without a UTF-8 separator. If //! two platform strings need to be concatenated, the only safe way to do so is //! using [`OsString::push`]. This limitation also makes it undesirable to use //! the bytes in interchange. //! //! Since this encoding can change between versions and platforms, it should //! not be used for storage. The standard library provides implementations of //! [`OsStrExt`] and [`OsStringExt`] for various platforms, which should be //! preferred for that use case. //! //! # Related Crates //! //! - [print\_bytes] - //! Used to print byte and platform strings as losslessly as possible. //! //! - [uniquote] - //! Used to display paths using escapes instead of replacement characters. //! //! # Examples //! //! ``` //! # use std::io; //! # //! # #[cfg(feature = "raw_os_str")] //! # { //! # #[cfg(any())] //! use std::env; //! use std::fs; //! # use std::path::Path; //! //! use os_str_bytes::OsStrBytesExt; //! //! # mod env { //! # use std::ffi::OsString; //! # use std::iter; //! # //! # use tempfile::NamedTempFile; //! # //! # pub(super) fn args_os() -> impl Iterator { //! # let file = NamedTempFile::with_prefix("os_str_bytes_").unwrap(); //! # iter::from_fn(move || Some(file.path().as_os_str().to_owned())) //! # .take(2) //! # } //! # } //! # //! for file in env::args_os().skip(1) { //! if !file.starts_with('-') { //! let string = "Hello, world!"; //! # assert!(Path::new(&file).exists()); //! fs::write(&file, string)?; //! assert_eq!(string, fs::read_to_string(file)?); //! } //! } //! # } //! # //! # Ok::<_, io::Error>(()) //! ``` //! //! [Encoding Conversions]: #encoding-conversions //! [memchr]: https://crates.io/crates/memchr //! [memchr_complexity]: OsStrBytesExt#complexity //! [`OsStrExt`]: ::std::os::unix::ffi::OsStrExt //! [`OsStringExt`]: ::std::os::unix::ffi::OsStringExt //! [print\_bytes]: https://crates.io/crates/print_bytes //! [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed //! [uniquote]: https://crates.io/crates/uniquote //! [windows_considerations]: https://doc.rust-lang.org/std/io/struct.Stdout.html#note-windows-portability-considerations // Only require a nightly compiler when building documentation for docs.rs. // This is a private option that should not be used. // https://github.com/rust-lang/docs.rs/issues/147#issuecomment-389544407 // https://github.com/dylni/os_str_bytes/issues/2 #![cfg_attr(os_str_bytes_docs_rs, feature(doc_cfg))] #![cfg_attr( all(target_vendor = "fortanix", target_env = "sgx"), feature(sgx_platform) )] #![cfg_attr(target_os = "uefi", feature(uefi_std))] #![cfg_attr(all(target_os = "wasi", target_env = "p2"), feature(wasip2))] #![warn(unused_results)] use std::borrow::Cow; use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; macro_rules! if_checked_conversions { ( $($item:item)+ ) => { $( #[cfg(feature = "checked_conversions")] $item )+ }; } if_checked_conversions! { use std::error::Error; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; use std::result; } #[cfg(not(os_str_bytes_docs_rs))] if_checked_conversions! { const _: &str = env!( "OS_STR_BYTES_CHECKED_CONVERSIONS", "The 'OS_STR_BYTES_CHECKED_CONVERSIONS' environment variable must be \ defined to use the 'checked_conversions' feature.", ); } #[cfg(all(feature = "memchr", not(feature = "raw_os_str")))] const _: &str = env!( "__OS_STR_BYTES_CI", concat!( "The 'memchr' feature is useless when 'raw_os_str' is disabled; it \ should be disabled too.", ), ); macro_rules! if_conversions { ( $($item:item)+ ) => { $( #[cfg(feature = "conversions")] $item )+ }; } if_conversions! { macro_rules! expect_encoded { ( $result:expr ) => { $result.expect("invalid raw bytes") }; } } macro_rules! if_raw_str { ( $($item:item)+ ) => { $( #[cfg(feature = "raw_os_str")] $item )+ }; } #[cfg_attr( all(target_family = "wasm", target_os = "unknown"), path = "wasm/mod.rs" )] #[cfg_attr(any(target_os = "uefi", windows), path = "windows/mod.rs")] #[cfg_attr( not(any( all(target_family = "wasm", target_os = "unknown"), target_os = "uefi", windows, )), path = "common/mod.rs" )] mod imp; use imp::convert_io; if_conversions! { use imp::convert; } #[cfg(any( all(feature = "conversions", any(target_os = "uefi", windows)), feature = "raw_os_str", ))] mod util; if_raw_str! { mod ext; pub use ext::NonUnicodeOsStr; pub use ext::OsStrBytesExt; pub mod iter; mod pattern; pub use pattern::Pattern; mod raw_str; pub use raw_str::RawOsStr; pub use raw_str::RawOsStrCow; pub use raw_str::RawOsString; } if_checked_conversions! { /// The error that occurs when a byte sequence is not representable in the /// platform encoding. /// /// [`Result::unwrap`] should almost always be called on results containing /// this error. It should be known whether or not byte sequences are /// properly encoded for the platform, since [the module-level /// documentation][encoding] discourages using encoded bytes in /// interchange. Results are returned primarily to make panicking behavior /// explicit. /// /// On Unix, this error is never returned, but [`OsStrExt`] or /// [`OsStringExt`] should be used instead if that needs to be guaranteed. /// /// [encoding]: self#encoding-conversions /// [`OsStrExt`]: ::std::os::unix::ffi::OsStrExt /// [`OsStringExt`]: ::std::os::unix::ffi::OsStringExt /// [`Result::unwrap`]: ::std::result::Result::unwrap #[derive(Clone, Debug, PartialEq)] #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "checked_conversions")) )] pub struct EncodingError(convert::EncodingError); impl Display for EncodingError { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } impl Error for EncodingError {} } if_checked_conversions! { type Result = result::Result; } if_conversions! { fn from_raw_bytes<'a, S>(string: S) -> convert::Result> where S: Into>, { match string.into() { Cow::Borrowed(string) => convert::os_str_from_bytes(string), Cow::Owned(string) => { convert::os_string_from_vec(string).map(Cow::Owned) } } } } if_conversions! { fn cow_os_str_into_path(string: Cow<'_, OsStr>) -> Cow<'_, Path> { match string { Cow::Borrowed(string) => Cow::Borrowed(Path::new(string)), Cow::Owned(string) => Cow::Owned(string.into()), } } } /// A platform agnostic variant of [`OsStrExt`]. /// /// For more information, see [the module-level documentation][module]. /// /// [module]: self /// [`OsStrExt`]: ::std::os::unix::ffi::OsStrExt pub trait OsStrBytes: private::Sealed + ToOwned { if_conversions! { /// Converts a byte string into an equivalent platform-native string. /// /// # Panics /// /// Panics if the string is not valid for the [unspecified encoding] /// used by this crate. /// /// # Examples /// /// ``` /// use std::env; /// use std::ffi::OsStr; /// # use std::io; /// /// use os_str_bytes::OsStrBytes; /// /// let os_string = env::current_exe()?; /// let os_bytes = os_string.to_raw_bytes(); /// assert_eq!(os_string, OsStr::assert_from_raw_bytes(os_bytes)); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [unspecified encoding]: self#encoding-conversions #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[must_use = "method should not be used for validation"] #[track_caller] fn assert_from_raw_bytes<'a, S>(string: S) -> Cow<'a, Self> where S: Into>; } /// Converts a byte string into an equivalent platform-native string, if it /// is [IO-safe]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// use std::io; /// use std::io::Read; /// /// use os_str_bytes::OsStrBytes; /// /// let mut io_string = Vec::new(); /// let _ = io::stdin().read_to_end(&mut io_string)?; /// let os_string = OsStr::from_io_bytes(&io_string).ok_or_else(|| { /// io::Error::new(io::ErrorKind::InvalidInput, "invalid input") /// })?; /// println!("{:?}", os_string); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input #[must_use] fn from_io_bytes(string: &[u8]) -> Option<&Self>; if_checked_conversions! { /// Converts a byte string into an equivalent platform-native string. /// /// [`assert_from_raw_bytes`] should almost always be used instead. For /// more information, see [`EncodingError`]. /// /// # Errors /// /// See documentation for [`EncodingError`]. /// /// # Examples /// /// ``` /// use std::env; /// use std::ffi::OsStr; /// # use std::io; /// /// use os_str_bytes::OsStrBytes; /// /// let os_string = env::current_exe()?; /// let os_bytes = os_string.to_raw_bytes(); /// assert_eq!(os_string, OsStr::from_raw_bytes(os_bytes).unwrap()); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`assert_from_raw_bytes`]: Self::assert_from_raw_bytes #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "checked_conversions")) )] fn from_raw_bytes<'a, S>(string: S) -> Result> where S: Into>; } /// Converts a platform-native string into an equivalent byte string, if it /// is [IO-safe]. /// /// # Examples /// /// ``` /// use std::env; /// use std::io; /// use std::io::Write; /// /// use os_str_bytes::OsStrBytes; /// /// let os_string = env::current_exe()?; /// let io_string = os_string.to_io_bytes().ok_or_else(|| { /// io::Error::new(io::ErrorKind::InvalidInput, "invalid input") /// })?; /// io::stdout().write_all(io_string)?; /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input #[must_use] fn to_io_bytes(&self) -> Option<&'_ [u8]>; /// Converts a platform-native string into an equivalent byte string. /// /// If the string is not [IO-safe], invalid characters will be replaced /// with [`REPLACEMENT_CHARACTER`]. /// /// # Examples /// /// ``` /// use std::env; /// use std::io; /// use std::io::Write; /// /// use os_str_bytes::OsStrBytes; /// /// let os_string = env::current_exe()?; /// let io_string = os_string.to_io_bytes_lossy(); /// io::stdout().write_all(&io_string)?; /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input /// [`REPLACEMENT_CHARACTER`]: char::REPLACEMENT_CHARACTER #[must_use] fn to_io_bytes_lossy(&self) -> Cow<'_, [u8]>; if_conversions! { /// Converts a platform-native string into an equivalent byte string. /// /// The returned string will use an [unspecified encoding]. /// /// # Examples /// /// ``` /// use std::ffi::OsStr; /// /// use os_str_bytes::OsStrBytes; /// /// let string = "foobar"; /// let os_string = OsStr::new(string); /// assert_eq!(string.as_bytes(), &*os_string.to_raw_bytes()); /// ``` /// /// [unspecified encoding]: self#encoding-conversions #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[must_use] fn to_raw_bytes(&self) -> Cow<'_, [u8]>; } } impl OsStrBytes for OsStr { if_conversions! { #[inline] fn assert_from_raw_bytes<'a, S>(string: S) -> Cow<'a, Self> where S: Into>, { expect_encoded!(from_raw_bytes(string)) } } #[inline] fn from_io_bytes(string: &[u8]) -> Option<&Self> { convert_io::os_str_from_bytes(string) } if_checked_conversions! { #[inline] fn from_raw_bytes<'a, S>(string: S) -> Result> where S: Into>, { from_raw_bytes(string).map_err(EncodingError) } } #[inline] fn to_io_bytes(&self) -> Option<&'_ [u8]> { convert_io::os_str_to_bytes(self) } #[inline] fn to_io_bytes_lossy(&self) -> Cow<'_, [u8]> { convert_io::os_str_to_bytes_lossy(self) } if_conversions! { #[inline] fn to_raw_bytes(&self) -> Cow<'_, [u8]> { convert::os_str_to_bytes(self) } } } impl OsStrBytes for Path { if_conversions! { #[inline] fn assert_from_raw_bytes<'a, S>(string: S) -> Cow<'a, Self> where S: Into>, { cow_os_str_into_path(OsStr::assert_from_raw_bytes(string)) } } #[inline] fn from_io_bytes(string: &[u8]) -> Option<&Self> { OsStr::from_io_bytes(string).map(Self::new) } if_checked_conversions! { #[inline] fn from_raw_bytes<'a, S>(string: S) -> Result> where S: Into>, { OsStr::from_raw_bytes(string).map(cow_os_str_into_path) } } #[inline] fn to_io_bytes(&self) -> Option<&'_ [u8]> { self.as_os_str().to_io_bytes() } #[inline] fn to_io_bytes_lossy(&self) -> Cow<'_, [u8]> { self.as_os_str().to_io_bytes_lossy() } if_conversions! { #[inline] fn to_raw_bytes(&self) -> Cow<'_, [u8]> { self.as_os_str().to_raw_bytes() } } } /// A platform agnostic variant of [`OsStringExt`]. /// /// For more information, see [the module-level documentation][module]. /// /// [module]: self /// [`OsStringExt`]: ::std::os::unix::ffi::OsStringExt pub trait OsStringBytes: private::Sealed + Sized { if_conversions! { /// Converts a byte string into an equivalent platform-native string. /// /// # Panics /// /// Panics if the string is not valid for the [unspecified encoding] /// used by this crate. /// /// # Examples /// /// ``` /// use std::env; /// use std::ffi::OsString; /// # use std::io; /// /// use os_str_bytes::OsStringBytes; /// /// let os_string = env::current_exe()?; /// let os_bytes = os_string.clone().into_raw_vec(); /// assert_eq!(os_string, OsString::assert_from_raw_vec(os_bytes)); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [unspecified encoding]: self#encoding-conversions #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[must_use = "method should not be used for validation"] #[track_caller] fn assert_from_raw_vec(string: Vec) -> Self; } /// Converts a byte string into an equivalent platform-native string, if it /// is [IO-safe]. /// /// # Examples /// /// ``` /// use std::ffi::OsString; /// use std::io; /// use std::io::Read; /// /// use os_str_bytes::OsStringBytes; /// /// let mut io_string = Vec::new(); /// let _ = io::stdin().read_to_end(&mut io_string)?; /// let os_string = OsString::from_io_vec(io_string).ok_or_else(|| { /// io::Error::new(io::ErrorKind::InvalidInput, "invalid input") /// })?; /// println!("{:?}", os_string); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input #[must_use] fn from_io_vec(string: Vec) -> Option; if_checked_conversions! { /// Converts a byte string into an equivalent platform-native string. /// /// [`assert_from_raw_vec`] should almost always be used instead. For /// more information, see [`EncodingError`]. /// /// # Errors /// /// See documentation for [`EncodingError`]. /// /// # Examples /// /// ``` /// use std::env; /// use std::ffi::OsString; /// # use std::io; /// /// use os_str_bytes::OsStringBytes; /// /// let os_string = env::current_exe()?; /// let os_bytes = os_string.clone().into_raw_vec(); /// assert_eq!( /// os_string, /// OsString::from_raw_vec(os_bytes).unwrap(), /// ); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [`assert_from_raw_vec`]: Self::assert_from_raw_vec #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "checked_conversions")) )] fn from_raw_vec(string: Vec) -> Result; } /// Converts a platform-native string into an equivalent byte string, if it /// is [IO-safe]. /// /// # Examples /// /// ``` /// use std::env; /// use std::io; /// use std::io::Write; /// /// use os_str_bytes::OsStringBytes; /// /// let os_string = env::current_exe()?; /// let io_string = os_string.into_io_vec().ok_or_else(|| { /// io::Error::new(io::ErrorKind::InvalidInput, "invalid input") /// })?; /// io::stdout().write_all(&io_string)?; /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input #[must_use] fn into_io_vec(self) -> Option>; /// Converts a platform-native string into an equivalent byte string. /// /// If the string is not [IO-safe], invalid characters will be replaced /// with [`REPLACEMENT_CHARACTER`]. /// /// # Examples /// /// ``` /// use std::env; /// use std::io; /// use std::io::Write; /// /// use os_str_bytes::OsStringBytes; /// /// let os_string = env::current_exe()?; /// let io_string = os_string.into_io_vec_lossy(); /// io::stdout().write_all(&io_string)?; /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [IO-safe]: self#user-input /// [`REPLACEMENT_CHARACTER`]: char::REPLACEMENT_CHARACTER #[must_use] fn into_io_vec_lossy(self) -> Vec; if_conversions! { /// Converts a platform-native string into an equivalent byte string. /// /// The returned string will use an [unspecified encoding]. /// /// # Examples /// /// ``` /// use std::ffi::OsString; /// /// use os_str_bytes::OsStringBytes; /// /// let string = "foobar".to_owned(); /// let os_string: OsString = string.clone().into(); /// assert_eq!(string.into_bytes(), os_string.into_raw_vec()); /// ``` /// /// [unspecified encoding]: self#encoding-conversions #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[must_use] fn into_raw_vec(self) -> Vec; } } impl OsStringBytes for OsString { if_conversions! { #[inline] fn assert_from_raw_vec(string: Vec) -> Self { expect_encoded!(convert::os_string_from_vec(string)) } } if_checked_conversions! { #[inline] fn from_raw_vec(string: Vec) -> Result { convert::os_string_from_vec(string).map_err(EncodingError) } } #[inline] fn from_io_vec(string: Vec) -> Option { convert_io::os_string_from_vec(string) } #[inline] fn into_io_vec(self) -> Option> { convert_io::os_string_into_vec(self) } #[inline] fn into_io_vec_lossy(self) -> Vec { convert_io::os_string_into_vec_lossy(self) } if_conversions! { #[inline] fn into_raw_vec(self) -> Vec { convert::os_string_into_vec(self) } } } impl OsStringBytes for PathBuf { if_conversions! { #[inline] fn assert_from_raw_vec(string: Vec) -> Self { OsString::assert_from_raw_vec(string).into() } } if_checked_conversions! { #[inline] fn from_raw_vec(string: Vec) -> Result { OsString::from_raw_vec(string).map(Into::into) } } #[inline] fn from_io_vec(string: Vec) -> Option { OsString::from_io_vec(string).map(Into::into) } #[inline] fn into_io_vec(self) -> Option> { self.into_os_string().into_io_vec() } #[inline] fn into_io_vec_lossy(self) -> Vec { self.into_os_string().into_io_vec_lossy() } if_conversions! { #[inline] fn into_raw_vec(self) -> Vec { self.into_os_string().into_raw_vec() } } } mod private { use std::ffi::OsStr; use std::ffi::OsString; use std::path::Path; use std::path::PathBuf; if_raw_str! { use std::borrow::Cow; use super::RawOsStr; } pub trait Sealed {} impl Sealed for char {} impl Sealed for OsStr {} impl Sealed for OsString {} impl Sealed for Path {} impl Sealed for PathBuf {} impl Sealed for &str {} impl Sealed for &String {} if_raw_str! { impl Sealed for Cow<'_, RawOsStr> {} } } os_str_bytes-7.1.0/src/pattern.rs000064400000000000000000000033211046102023000151610ustar 00000000000000use std::fmt::Debug; use std::str; use super::private; use super::util::MAX_UTF8_LENGTH; pub trait Encoded { fn __as_bytes(&self) -> &[u8] { self.__as_str().as_bytes() } fn __as_str(&self) -> &str; } #[derive(Clone, Debug)] pub struct EncodedChar { buffer: [u8; MAX_UTF8_LENGTH], length: usize, } impl Encoded for EncodedChar { fn __as_str(&self) -> &str { // SAFETY: This slice was encoded from a character. unsafe { str::from_utf8_unchecked(&self.buffer[..self.length]) } } } impl Encoded for &str { fn __as_str(&self) -> &str { self } } /// Allows a type to be used for searching by [`RawOsStr`] and [`RawOsString`]. /// /// This trait is very similar to [`str::pattern::Pattern`], but its methods /// are private and it is implemented for different types. /// /// [`RawOsStr`]: super::RawOsStr /// [`RawOsString`]: super::RawOsString #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] pub trait Pattern: private::Sealed { #[doc(hidden)] type __Encoded: Clone + Debug + Encoded; #[doc(hidden)] fn __encode(self) -> Self::__Encoded; } impl Pattern for char { type __Encoded = EncodedChar; fn __encode(self) -> Self::__Encoded { let mut encoded = EncodedChar { buffer: [0; MAX_UTF8_LENGTH], length: 0, }; encoded.length = self.encode_utf8(&mut encoded.buffer).len(); encoded } } impl Pattern for &str { type __Encoded = Self; fn __encode(self) -> Self::__Encoded { self } } impl<'a> Pattern for &'a String { type __Encoded = <&'a str as Pattern>::__Encoded; fn __encode(self) -> Self::__Encoded { (**self).__encode() } } os_str_bytes-7.1.0/src/raw_str.rs000064400000000000000000001126201046102023000151700ustar 00000000000000use std::borrow::Borrow; use std::borrow::Cow; use std::borrow::ToOwned; use std::ffi::OsStr; use std::ffi::OsString; use std::fmt; use std::fmt::Debug; use std::fmt::Formatter; use std::mem; use std::ops::Deref; use std::ops::Index; use std::result; use std::str; use super::ext; use super::ext::SliceIndex; use super::iter::RawRSplit; use super::iter::RawSplit; use super::iter::Utf8Chunks; use super::private; use super::OsStrBytesExt; use super::Pattern; if_checked_conversions! { use super::Result; } if_conversions! { use super::OsStrBytes; use super::OsStringBytes; } #[allow(clippy::missing_safety_doc)] unsafe trait TransmuteBox { fn transmute_box(self: Box) -> Box where R: ?Sized + TransmuteBox, { let value = Box::into_raw(self); // SAFETY: This trait is only implemented for types that can be // transmuted. unsafe { Box::from_raw(mem::transmute_copy(&value)) } } } // SAFETY: This struct has a layout that makes this operation safe. unsafe impl TransmuteBox for RawOsStr {} unsafe impl TransmuteBox for [u8] {} /// A container providing additional functionality for [`OsStr`]. /// /// For more information, see [`OsStrBytesExt`]. #[derive(Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] #[repr(transparent)] pub struct RawOsStr([u8]); impl RawOsStr { /// Wraps a platform-native string, without copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// println!("{:?}", RawOsStr::new(&os_string)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] #[must_use] pub fn new(string: &S) -> &Self where S: AsRef + ?Sized, { let string = string.as_ref().as_encoded_bytes(); // SAFETY: [OsStr] prevents violating the invariants of its internal // encoding. unsafe { Self::from_encoded_bytes_unchecked(string) } } fn from_tuple<'a, 'b>( (prefix, suffix): (&'a OsStr, &'b OsStr), ) -> (&'a Self, &'b Self) { (Self::new(prefix), Self::new(suffix)) } /// Wraps a platform-native string, without copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// println!("{:?}", RawOsStr::from_os_str(&os_string)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[deprecated(since = "7.0.0", note = "use `new` instead")] #[inline] #[must_use] pub fn from_os_str(string: &OsStr) -> &Self { Self::new(string) } /// Wraps a string, without copying or encoding conversion. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let string = "foobar"; /// let raw = RawOsStr::from_str(string); /// assert_eq!(string, raw); /// ``` #[allow(clippy::should_implement_trait)] #[deprecated(since = "7.0.0", note = "use `new` instead")] #[inline] #[must_use] pub fn from_str(string: &str) -> &Self { Self::new(string) } /// Equivalent to [`OsStr::from_encoded_bytes_unchecked`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// let raw_bytes = raw.as_encoded_bytes(); /// assert_eq!(raw, unsafe { /// RawOsStr::from_encoded_bytes_unchecked(raw_bytes) /// }); /// # /// # Ok::<_, io::Error>(()) /// ``` #[allow(clippy::missing_safety_doc)] #[inline] #[must_use] pub unsafe fn from_encoded_bytes_unchecked(string: &[u8]) -> &Self { // SAFETY: This struct has a layout that makes this operation safe. unsafe { mem::transmute(string) } } if_conversions! { /// Equivalent to [`OsStrBytes::assert_from_raw_bytes`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// let raw_bytes = raw.to_raw_bytes(); /// assert_eq!(raw, &*RawOsStr::assert_cow_from_raw_bytes(&raw_bytes)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use = "method should not be used for validation"] #[track_caller] pub fn assert_cow_from_raw_bytes(string: &[u8]) -> Cow<'_, Self> { Cow::from_os_str(OsStr::assert_from_raw_bytes(string)) } } if_checked_conversions! { /// Equivalent to [`OsStrBytes::from_raw_bytes`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// let raw_bytes = raw.to_raw_bytes(); /// assert_eq!( /// Ok(raw), /// RawOsStr::cow_from_raw_bytes(&raw_bytes).as_deref(), /// ); /// # /// # Ok::<_, io::Error>(()) /// ``` #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "checked_conversions")) )] #[inline] pub fn cow_from_raw_bytes(string: &[u8]) -> Result> { OsStr::from_raw_bytes(string).map(Cow::from_os_str) } } if_conversions! { /// Converts and wraps a byte string. /// /// # Safety /// /// The string must be valid for the [unspecified encoding] used by /// this crate. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// let raw_bytes = raw.to_raw_bytes(); /// assert_eq!(raw, unsafe { /// &*RawOsStr::cow_from_raw_bytes_unchecked(&raw_bytes) /// }); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [unspecified encoding]: super#encoding-conversions #[deprecated( since = "6.6.0", note = "use `assert_cow_from_raw_bytes` or `from_encoded_bytes_unchecked` instead", )] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] #[track_caller] pub unsafe fn cow_from_raw_bytes_unchecked( string: &[u8], ) -> Cow<'_, Self> { Self::assert_cow_from_raw_bytes(string) } } /// Equivalent to [`OsStr::as_encoded_bytes`]. /// /// The returned string will not use the [unspecified encoding]. It can /// only be passed to methods accepting the internal encoding of [`OsStr`], /// such as [`from_encoded_bytes_unchecked`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let string = "foobar"; /// let raw = RawOsStr::new(string); /// assert_eq!(string.as_bytes(), raw.as_encoded_bytes()); /// ``` /// /// [`from_encoded_bytes_unchecked`]: Self::from_encoded_bytes_unchecked /// [unspecified encoding]: super#encoding-conversions #[inline] #[must_use] pub fn as_encoded_bytes(&self) -> &[u8] { &self.0 } /// Converts this representation back to a platform-native string, without /// copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// assert_eq!(os_string, raw.as_os_str()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] #[must_use] pub fn as_os_str(&self) -> &OsStr { // SAFETY: This wrapper prevents violating the invariants of the // internal encoding for [OsStr]. unsafe { ext::os_str(&self.0) } } /// Equivalent to [`OsStrBytesExt::contains`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.contains("oo")); /// assert!(!raw.contains("of")); /// ``` #[inline] #[must_use] pub fn contains

(&self, pat: P) -> bool where P: Pattern, { self.as_os_str().contains(pat) } /// Equivalent to [`OsStrBytesExt::ends_with`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.ends_with("bar")); /// assert!(!raw.ends_with("foo")); /// ``` #[inline] #[must_use] pub fn ends_with

(&self, pat: P) -> bool where P: Pattern, { self.as_os_str().ends_with(pat) } if_conversions! { /// Equivalent to [`OsStrBytesExt::ends_with_os`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.ends_with_os(RawOsStr::new("bar"))); /// assert!(!raw.ends_with_os(RawOsStr::new("foo"))); /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] pub fn ends_with_os(&self, pat: &Self) -> bool { self.as_os_str().ends_with_os(pat.as_os_str()) } } /// Equivalent to [`OsStrBytesExt::find`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!(Some(1), raw.find("o")); /// assert_eq!(None, raw.find("of")); /// ``` #[inline] #[must_use] pub fn find

(&self, pat: P) -> Option where P: Pattern, { self.as_os_str().find(pat) } /// Equivalent to [`OsStrBytesExt::get_unchecked`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!("foo", unsafe { raw.get_unchecked(..3) }); /// assert_eq!("bar", unsafe { raw.get_unchecked(3..) }); /// ``` #[allow(clippy::missing_safety_doc)] #[inline] #[must_use] pub unsafe fn get_unchecked(&self, index: I) -> &Self where I: SliceIndex, { let string = self.as_os_str(); // SAFETY: This method has equivalent safety requirements. Self::new(unsafe { string.get_unchecked(index) }) } /// Equivalent to [`OsStr::is_empty`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// assert!(RawOsStr::new("").is_empty()); /// assert!(!RawOsStr::new("foobar").is_empty()); /// ``` #[inline] #[must_use] pub fn is_empty(&self) -> bool { self.as_os_str().is_empty() } /// Equivalent to [`OsStrBytesExt::repeat`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foo"); /// assert_eq!("foofoofoo", raw.repeat(3)); /// ``` #[inline] #[must_use] pub fn repeat(&self, n: usize) -> RawOsString { RawOsString::new(self.as_os_str().repeat(n)) } /// Equivalent to [`OsStrBytesExt::rfind`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!(Some(2), raw.rfind("o")); /// assert_eq!(None, raw.rfind("of")); /// ``` #[inline] #[must_use] pub fn rfind

(&self, pat: P) -> Option where P: Pattern, { self.as_os_str().rfind(pat) } /// Equivalent to [`OsStrBytesExt::rsplit`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.rsplit("o").eq(["bar", "", "f"])); /// ``` #[inline] #[track_caller] pub fn rsplit

(&self, pat: P) -> RawRSplit<'_, P> where P: Pattern, { RawRSplit::new(self, pat) } /// Equivalent to [`OsStrBytesExt::rsplit_once`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!( /// Some((RawOsStr::new("fo"), RawOsStr::new("bar"))), /// raw.rsplit_once("o"), /// ); /// assert_eq!(None, raw.rsplit_once("of")); /// ``` #[inline] #[must_use] pub fn rsplit_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern, { self.as_os_str().rsplit_once(pat).map(Self::from_tuple) } /// Equivalent to [`OsStrBytesExt::split`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.split("o").eq(["f", "", "bar"])); /// ``` #[inline] #[track_caller] pub fn split

(&self, pat: P) -> RawSplit<'_, P> where P: Pattern, { RawSplit::new(self, pat) } /// Equivalent to [`OsStrBytesExt::split_at`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!( /// (RawOsStr::new("fo"), RawOsStr::new("obar")), /// raw.split_at(2), /// ); /// ``` #[inline] #[must_use] #[track_caller] pub fn split_at(&self, mid: usize) -> (&Self, &Self) { Self::from_tuple(self.as_os_str().split_at(mid)) } /// Equivalent to [`OsStrBytesExt::split_once`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert_eq!( /// Some((RawOsStr::new("f"), RawOsStr::new("obar"))), /// raw.split_once("o"), /// ); /// assert_eq!(None, raw.split_once("of")); /// ``` #[inline] #[must_use] pub fn split_once

(&self, pat: P) -> Option<(&Self, &Self)> where P: Pattern, { self.as_os_str().split_once(pat).map(Self::from_tuple) } /// Equivalent to [`OsStrBytesExt::starts_with`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.starts_with("foo")); /// assert!(!raw.starts_with("bar")); /// ``` #[inline] #[must_use] pub fn starts_with

(&self, pat: P) -> bool where P: Pattern, { self.as_os_str().starts_with(pat) } if_conversions! { /// Equivalent to [`OsStrBytesExt::starts_with_os`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("foobar"); /// assert!(raw.starts_with_os(RawOsStr::new("foo"))); /// assert!(!raw.starts_with_os(RawOsStr::new("bar"))); /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] pub fn starts_with_os(&self, pat: &Self) -> bool { self.as_os_str().starts_with_os(pat.as_os_str()) } } /// Equivalent to [`OsStrBytesExt::strip_prefix`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("111foo1bar111"); /// assert_eq!(Some(RawOsStr::new("11foo1bar111")), raw.strip_prefix("1")); /// assert_eq!(None, raw.strip_prefix("o")); /// ``` #[inline] #[must_use] pub fn strip_prefix

(&self, pat: P) -> Option<&Self> where P: Pattern, { self.as_os_str().strip_prefix(pat).map(Self::new) } /// Equivalent to [`OsStrBytesExt::strip_suffix`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("111foo1bar111"); /// assert_eq!(Some(RawOsStr::new("111foo1bar11")), raw.strip_suffix("1")); /// assert_eq!(None, raw.strip_suffix("o")); /// ``` #[inline] #[must_use] pub fn strip_suffix

(&self, pat: P) -> Option<&Self> where P: Pattern, { self.as_os_str().strip_suffix(pat).map(Self::new) } /// Converts this representation back to a platform-native string. /// /// When possible, use [`RawOsStrCow::into_os_str`] for a more efficient /// conversion on some platforms. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// assert_eq!(os_string, raw.to_os_str()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[deprecated(since = "6.6.0", note = "use `as_os_str` instead")] #[inline] #[must_use] pub fn to_os_str(&self) -> Cow<'_, OsStr> { Cow::Borrowed(self.as_os_str()) } if_conversions! { /// Equivalent to [`OsStrBytes::to_raw_bytes`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let string = "foobar"; /// let raw = RawOsStr::new(string); /// assert_eq!(string.as_bytes(), &*raw.to_raw_bytes()); /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] pub fn to_raw_bytes(&self) -> Cow<'_, [u8]> { self.as_os_str().to_raw_bytes() } } /// Equivalent to [`OsStr::to_str`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let string = "foobar"; /// let raw = RawOsStr::new(string); /// assert_eq!(Some(string), raw.to_str()); /// ``` #[inline] #[must_use] pub fn to_str(&self) -> Option<&str> { self.as_os_str().to_str() } /// Equivalent to [`OsStr::to_string_lossy`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsStr::new(&os_string); /// println!("{}", raw.to_str_lossy()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] #[must_use] pub fn to_str_lossy(&self) -> Cow<'_, str> { self.as_os_str().to_string_lossy() } /// Equivalent to [`OsStrBytesExt::trim_end_matches`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("111foo1bar111"); /// assert_eq!("111foo1bar", raw.trim_end_matches("1")); /// assert_eq!("111foo1bar111", raw.trim_end_matches("o")); /// ``` #[inline] #[must_use] pub fn trim_end_matches

(&self, pat: P) -> &Self where P: Pattern, { Self::new(self.as_os_str().trim_end_matches(pat)) } /// Equivalent to [`OsStrBytesExt::trim_matches`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("111foo1bar111"); /// assert_eq!("foo1bar", raw.trim_matches("1")); /// assert_eq!("111foo1bar111", raw.trim_matches("o")); /// ``` #[inline] #[must_use] pub fn trim_matches

(&self, pat: P) -> &Self where P: Pattern, { Self::new(self.as_os_str().trim_matches(pat)) } /// Equivalent to [`OsStrBytesExt::trim_start_matches`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// let raw = RawOsStr::new("111foo1bar111"); /// assert_eq!("foo1bar111", raw.trim_start_matches("1")); /// assert_eq!("111foo1bar111", raw.trim_start_matches("o")); /// ``` #[inline] #[must_use] pub fn trim_start_matches

(&self, pat: P) -> &Self where P: Pattern, { Self::new(self.as_os_str().trim_start_matches(pat)) } /// Equivalent to [`OsStrBytesExt::utf8_chunks`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsStr; /// /// fn to_str_lossy(raw: &RawOsStr, mut push: F) /// where /// F: FnMut(&str), /// { /// for (invalid, string) in raw.utf8_chunks() { /// if !invalid.as_os_str().is_empty() { /// push("\u{FFFD}"); /// } /// /// push(string); /// } /// } /// ``` #[inline] pub fn utf8_chunks(&self) -> Utf8Chunks<'_> { Utf8Chunks::new(self.as_os_str()) } } impl AsRef for RawOsStr { #[inline] fn as_ref(&self) -> &Self { self } } impl AsRef for RawOsStr { #[inline] fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl AsRef for OsStr { #[inline] fn as_ref(&self) -> &RawOsStr { RawOsStr::new(self) } } impl AsRef for OsString { #[inline] fn as_ref(&self) -> &RawOsStr { (**self).as_ref() } } impl AsRef for str { #[inline] fn as_ref(&self) -> &RawOsStr { RawOsStr::new(self) } } impl AsRef for String { #[inline] fn as_ref(&self) -> &RawOsStr { (**self).as_ref() } } impl Default for &RawOsStr { #[inline] fn default() -> Self { RawOsStr::new("") } } impl<'a> From<&'a RawOsStr> for Cow<'a, RawOsStr> { #[inline] fn from(value: &'a RawOsStr) -> Self { Cow::Borrowed(value) } } impl From> for Box { #[inline] fn from(value: Box) -> Self { value.into_boxed_bytes().transmute_box() } } impl Index for RawOsStr where Idx: SliceIndex, { type Output = Self; #[inline] fn index(&self, index: Idx) -> &Self::Output { Self::new(self.as_os_str().index(index)) } } impl ToOwned for RawOsStr { type Owned = RawOsString; #[inline] fn to_owned(&self) -> Self::Owned { RawOsString(self.0.to_owned()) } } /// Extensions to [`Cow`] for additional conversions. /// /// [`Cow`]: Cow #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] pub trait RawOsStrCow<'a>: private::Sealed { /// Converts a platform-native string back to this representation, without /// copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::borrow::Cow; /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// use os_str_bytes::RawOsStrCow; /// /// let os_string = Cow::Owned(env::current_exe()?.into_os_string()); /// println!("{:?}", Cow::from_os_str(os_string)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[must_use] fn from_os_str(string: Cow<'a, OsStr>) -> Self; /// Converts this representation back to a platform-native string, without /// copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::borrow::Cow; /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsStr; /// use os_str_bytes::RawOsStrCow; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = Cow::Borrowed(RawOsStr::new(&os_string)); /// assert_eq!(os_string, raw.into_os_str()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[must_use] fn into_os_str(self) -> Cow<'a, OsStr>; } impl<'a> RawOsStrCow<'a> for Cow<'a, RawOsStr> { #[inline] fn from_os_str(string: Cow<'a, OsStr>) -> Self { match string { Cow::Borrowed(string) => Cow::Borrowed(RawOsStr::new(string)), Cow::Owned(string) => Cow::Owned(RawOsString::new(string)), } } #[inline] fn into_os_str(self) -> Cow<'a, OsStr> { match self { Cow::Borrowed(string) => Cow::Borrowed(string.as_os_str()), Cow::Owned(string) => Cow::Owned(string.into_os_string()), } } } /// A container for owned byte strings converted by this crate. /// /// For more information, see [`RawOsStr`]. #[derive(Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "raw_os_str")))] pub struct RawOsString(Vec); impl RawOsString { /// Wraps a platform-native string, without copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// println!("{:?}", RawOsString::new(os_string)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] #[must_use] pub fn new(string: S) -> Self where S: Into, { Self(string.into().into_encoded_bytes()) } /// Wraps a string, without copying or encoding conversion. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let raw = RawOsString::from_string(string.clone()); /// assert_eq!(string, raw); /// ``` #[deprecated(since = "7.0.0", note = "use `new` instead")] #[inline] #[must_use] pub fn from_string(string: String) -> Self { Self(string.into_bytes()) } /// Equivalent to [`OsString::from_encoded_bytes_unchecked`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsString::new(os_string); /// let raw_bytes = raw.clone().into_encoded_vec(); /// assert_eq!(raw, unsafe { /// RawOsString::from_encoded_vec_unchecked(raw_bytes) /// }); /// # /// # Ok::<_, io::Error>(()) /// ``` #[allow(clippy::missing_safety_doc)] #[inline] #[must_use] pub unsafe fn from_encoded_vec_unchecked(string: Vec) -> Self { Self(string) } if_conversions! { /// Equivalent to [`OsStringBytes::assert_from_raw_vec`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsString::new(os_string); /// let raw_bytes = raw.clone().into_raw_vec(); /// assert_eq!(raw, RawOsString::assert_from_raw_vec(raw_bytes)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use = "method should not be used for validation"] #[track_caller] pub fn assert_from_raw_vec(string: Vec) -> Self { Self::new(OsString::assert_from_raw_vec(string)) } } if_checked_conversions! { /// Equivalent to [`OsStringBytes::from_raw_vec`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsString::new(os_string); /// let raw_bytes = raw.clone().into_raw_vec(); /// assert_eq!(Ok(raw), RawOsString::from_raw_vec(raw_bytes)); /// # /// # Ok::<_, io::Error>(()) /// ``` #[cfg_attr( os_str_bytes_docs_rs, doc(cfg(feature = "checked_conversions")) )] #[inline] pub fn from_raw_vec(string: Vec) -> Result { OsString::from_raw_vec(string).map(Self::new) } } if_conversions! { /// Converts and wraps a byte string. /// /// # Safety /// /// The string must be valid for the [unspecified encoding] used by /// this crate. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsString::new(os_string); /// let raw_bytes = raw.clone().into_raw_vec(); /// assert_eq!(raw, unsafe { /// RawOsString::from_raw_vec_unchecked(raw_bytes) /// }); /// # /// # Ok::<_, io::Error>(()) /// ``` /// /// [unspecified encoding]: super#encoding-conversions #[deprecated( since = "6.6.0", note = "use `assert_from_raw_vec` or `from_encoded_vec_unchecked` instead", )] #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] #[track_caller] pub unsafe fn from_raw_vec_unchecked(string: Vec) -> Self { Self::assert_from_raw_vec(string) } } /// Equivalent to [`String::clear`]. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let mut raw = RawOsString::new(os_string); /// raw.clear(); /// assert!(raw.is_empty()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] pub fn clear(&mut self) { self.0.clear(); } /// Equivalent to [`String::into_boxed_str`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let raw = RawOsString::new(string.clone()); /// assert_eq!(string, *raw.into_box()); /// ``` #[inline] #[must_use] pub fn into_box(self) -> Box { self.0.into_boxed_slice().transmute_box() } /// Equivalent to [`OsString::into_encoded_bytes`]. /// /// The returned string will not use the [unspecified encoding]. It can /// only be passed to methods accepting the internal encoding of [`OsStr`], /// such as [`from_encoded_vec_unchecked`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let raw = RawOsString::new(string.clone()); /// assert_eq!(string.into_bytes(), raw.into_encoded_vec()); /// ``` /// /// [`from_encoded_vec_unchecked`]: Self::from_encoded_vec_unchecked /// [unspecified encoding]: super#encoding-conversions #[inline] #[must_use] pub fn into_encoded_vec(self) -> Vec { self.0 } /// Converts this representation back to a platform-native string, without /// copying or encoding conversion. /// /// # Examples /// /// ``` /// use std::env; /// # use std::io; /// /// use os_str_bytes::RawOsString; /// /// let os_string = env::current_exe()?.into_os_string(); /// let raw = RawOsString::new(os_string.clone()); /// assert_eq!(os_string, raw.into_os_string()); /// # /// # Ok::<_, io::Error>(()) /// ``` #[inline] #[must_use] pub fn into_os_string(self) -> OsString { // SAFETY: This wrapper prevents violating the invariants of the // internal encoding for [OsStr]. unsafe { OsString::from_encoded_bytes_unchecked(self.0) } } if_conversions! { /// Equivalent to [`OsStringBytes::into_raw_vec`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let raw = RawOsString::new(string.clone()); /// assert_eq!(string.into_bytes(), raw.into_raw_vec()); /// ``` #[cfg_attr(os_str_bytes_docs_rs, doc(cfg(feature = "conversions")))] #[inline] #[must_use] pub fn into_raw_vec(self) -> Vec { self.into_os_string().into_raw_vec() } } /// Equivalent to [`OsString::into_string`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let raw = RawOsString::new(string.clone()); /// assert_eq!(Ok(string), raw.into_string()); /// ``` #[inline] pub fn into_string(self) -> result::Result { String::from_utf8(self.0).map_err(|x| Self(x.into_bytes())) } /// Equivalent to [`String::shrink_to_fit`]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let string = "foobar".to_owned(); /// let mut raw = RawOsString::new(string.clone()); /// raw.shrink_to_fit(); /// assert_eq!(string, raw); /// ``` #[inline] pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit(); } #[track_caller] fn check_bound(&self, index: usize) { ext::check_bound(self.as_os_str(), index); } /// Equivalent to [`String::split_off`]. /// /// # Panics /// /// Panics if the index is not a [valid boundary]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let mut raw = RawOsString::new("foobar".to_owned()); /// assert_eq!("bar", raw.split_off(3)); /// assert_eq!("foo", raw); /// ``` /// /// [valid boundary]: OsStrBytesExt#indices #[inline] #[must_use] #[track_caller] pub fn split_off(&mut self, at: usize) -> Self { self.check_bound(at); Self(self.0.split_off(at)) } /// Equivalent to [`String::truncate`]. /// /// # Panics /// /// Panics if the index is not a [valid boundary]. /// /// # Examples /// /// ``` /// use os_str_bytes::RawOsString; /// /// let mut raw = RawOsString::new("foobar".to_owned()); /// raw.truncate(3); /// assert_eq!("foo", raw); /// ``` /// /// [valid boundary]: OsStrBytesExt#indices #[inline] #[track_caller] pub fn truncate(&mut self, new_len: usize) { self.check_bound(new_len); self.0.truncate(new_len); } } impl AsRef for RawOsString { #[inline] fn as_ref(&self) -> &OsStr { (**self).as_ref() } } impl AsRef for RawOsString { #[inline] fn as_ref(&self) -> &RawOsStr { self } } impl Borrow for RawOsString { #[inline] fn borrow(&self) -> &RawOsStr { self } } impl Deref for RawOsString { type Target = RawOsStr; #[inline] fn deref(&self) -> &Self::Target { // SAFETY: This wrapper prevents violating the invariants of the // internal encoding for [OsStr]. unsafe { RawOsStr::from_encoded_bytes_unchecked(&self.0) } } } impl From for Box { #[inline] fn from(value: RawOsString) -> Self { value.into_box() } } impl From> for RawOsString { #[inline] fn from(value: Box) -> Self { Self(value.transmute_box::<[_]>().into_vec()) } } impl From for Cow<'_, RawOsStr> { #[inline] fn from(value: RawOsString) -> Self { Cow::Owned(value) } } impl From for RawOsString { #[inline] fn from(value: OsString) -> Self { Self::new(value) } } impl From for OsString { #[inline] fn from(value: RawOsString) -> Self { value.into_os_string() } } impl From for RawOsString { #[inline] fn from(value: String) -> Self { Self::new(value) } } macro_rules! r#impl { ( $type:ty ) => { impl Debug for $type { #[inline] fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_tuple(stringify!($type)) .field(&self.as_os_str()) .finish() } } }; } r#impl!(RawOsStr); r#impl!(RawOsString); impl Index for RawOsString where Idx: SliceIndex, { type Output = >::Output; #[inline] fn index(&self, index: Idx) -> &Self::Output { &(**self)[index] } } macro_rules! r#impl { ( $type:ty , $other_type:ty ) => { impl PartialEq<$other_type> for $type { #[inline] fn eq(&self, other: &$other_type) -> bool { let raw: &OsStr = self.as_ref(); let other: &OsStr = other.as_ref(); raw == other } } impl PartialEq<$type> for $other_type { #[inline] fn eq(&self, other: &$type) -> bool { other == self } } }; } r#impl!(RawOsStr, OsStr); r#impl!(RawOsStr, OsString); r#impl!(RawOsStr, RawOsString); r#impl!(RawOsStr, str); r#impl!(RawOsStr, String); r#impl!(&RawOsStr, OsString); r#impl!(&RawOsStr, RawOsString); r#impl!(&RawOsStr, String); r#impl!(RawOsString, OsStr); r#impl!(RawOsString, &OsStr); r#impl!(RawOsString, OsString); r#impl!(RawOsString, str); r#impl!(RawOsString, &str); r#impl!(RawOsString, String); os_str_bytes-7.1.0/src/util.rs000064400000000000000000000004271046102023000144650ustar 00000000000000pub(super) const BYTE_SHIFT: u8 = 6; pub(super) const CONT_MASK: u8 = (1 << BYTE_SHIFT) - 1; pub(super) const CONT_TAG: u8 = 0b1000_0000; pub(super) const fn is_continuation(byte: u8) -> bool { byte & !CONT_MASK == CONT_TAG } pub(super) const MAX_UTF8_LENGTH: usize = 4; os_str_bytes-7.1.0/src/wasm/convert.rs000064400000000000000000000024631046102023000161410ustar 00000000000000use std::borrow::Cow; use std::error::Error; use std::ffi::OsStr; use std::ffi::OsString; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; use std::result; use std::str; use std::str::Utf8Error; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct EncodingError(Utf8Error); impl Display for EncodingError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl Error for EncodingError {} pub(crate) type Result = result::Result; macro_rules! expect_utf8 { ( $result:expr ) => { $result.expect( "platform string contains invalid UTF-8, which should not be \ possible", ) }; } pub(crate) fn os_str_from_bytes(string: &[u8]) -> Result> { str::from_utf8(string) .map(|x| Cow::Borrowed(OsStr::new(x))) .map_err(EncodingError) } pub(crate) fn os_str_to_bytes(string: &OsStr) -> Cow<'_, [u8]> { Cow::Borrowed(expect_utf8!(string.to_str()).as_bytes()) } pub(crate) fn os_string_from_vec(string: Vec) -> Result { String::from_utf8(string) .map(Into::into) .map_err(|x| EncodingError(x.utf8_error())) } pub(crate) fn os_string_into_vec(string: OsString) -> Vec { expect_utf8!(string.into_string()).into_bytes() } os_str_bytes-7.1.0/src/wasm/mod.rs000064400000000000000000000003131046102023000152300ustar 00000000000000#[path = "../windows/convert_io.rs"] pub(super) mod convert_io; if_conversions! { pub(super) mod convert; if_raw_str! { #[path = "../common/raw.rs"] pub(super) mod raw; } } os_str_bytes-7.1.0/src/windows/convert/mod.rs000064400000000000000000000060541046102023000174430ustar 00000000000000// These functions are necessarily inefficient, because they must revert // encoding conversions performed by the standard library. However, there is // currently no better alternative. use std::borrow::Cow; use std::error::Error; use std::ffi::OsStr; use std::ffi::OsString; use std::fmt; use std::fmt::Display; use std::fmt::Formatter; use std::ops::Not; use std::result; use std::str; use super::os::ffi::OsStrExt; use super::os::ffi::OsStringExt; mod wtf8; use wtf8::DecodeWide; if_raw_str! { if_conversions! { pub(crate) use wtf8::ends_with; pub(crate) use wtf8::starts_with; } } #[cfg(test)] mod tests; #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum EncodingError { Byte(u8), CodePoint(u32), End(), } impl EncodingError { fn position(&self) -> Cow<'_, str> { match self { Self::Byte(byte) => Cow::Owned(format!("byte b'\\x{:02X}'", byte)), Self::CodePoint(code_point) => { Cow::Owned(format!("code point U+{:04X}", code_point)) } Self::End() => Cow::Borrowed("end of string"), } } } impl Display for EncodingError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!( f, "byte sequence is not representable in the platform encoding; \ error at {}", self.position(), ) } } impl Error for EncodingError {} pub(crate) type Result = result::Result; fn from_bytes(string: &[u8]) -> Result> { let mut encoder = wtf8::encode_wide(string); // Collecting an iterator into a result ignores the size hint: // https://github.com/rust-lang/rust/issues/48994 let mut encoded_string = Vec::with_capacity(encoder.size_hint().0); for wchar in &mut encoder { encoded_string.push(wchar?); } debug_assert_eq!(str::from_utf8(string).is_ok(), encoder.is_still_utf8()); Ok(encoder .is_still_utf8() .not() .then(|| OsString::from_wide(&encoded_string))) } fn to_bytes(string: &OsStr) -> Vec { let encoder = string.encode_wide(); let mut string = Vec::with_capacity(encoder.size_hint().0); string.extend(DecodeWide::new(encoder)); string } pub(crate) fn os_str_from_bytes(string: &[u8]) -> Result> { from_bytes(string).map(|result| { result.map(Cow::Owned).unwrap_or_else(|| { // SAFETY: This slice was validated to be UTF-8. Cow::Borrowed(OsStr::new(unsafe { str::from_utf8_unchecked(string) })) }) }) } pub(crate) fn os_str_to_bytes(string: &OsStr) -> Cow<'_, [u8]> { Cow::Owned(to_bytes(string)) } pub(crate) fn os_string_from_vec(string: Vec) -> Result { from_bytes(&string).map(|result| { result.unwrap_or_else(|| { // SAFETY: This slice was validated to be UTF-8. unsafe { String::from_utf8_unchecked(string) }.into() }) }) } pub(crate) fn os_string_into_vec(string: OsString) -> Vec { to_bytes(&string) } os_str_bytes-7.1.0/src/windows/convert/wtf8/code_points.rs000064400000000000000000000064101046102023000220560ustar 00000000000000use std::iter::FusedIterator; use std::iter::Peekable; use std::mem; use crate::util::is_continuation; use crate::util::BYTE_SHIFT; use crate::util::CONT_MASK; use super::EncodingError; use super::Result; pub(super) struct CodePoints where I: Iterator, { iter: Peekable, surrogate: bool, still_utf8: bool, } impl CodePoints where I: Iterator, { pub(super) fn new(string: S) -> Self where S: IntoIterator, { Self { iter: string.into_iter().peekable(), surrogate: false, still_utf8: true, } } pub(super) const fn is_still_utf8(&self) -> bool { self.still_utf8 } fn consume_next(&mut self, code_point: &mut u32) -> Result<()> { let &byte = self.iter.peek().ok_or(EncodingError::End())?; if !is_continuation(byte) { self.surrogate = false; // Not consuming this byte will be useful if this crate ever offers // a way to encode lossily. return Err(EncodingError::Byte(byte)); } *code_point = (*code_point << BYTE_SHIFT) | u32::from(byte & CONT_MASK); let removed = self.iter.next(); debug_assert_eq!(Some(byte), removed); Ok(()) } pub(super) fn inner_size_hint(&self) -> (usize, Option) { self.iter.size_hint() } } impl FusedIterator for CodePoints where I: FusedIterator + Iterator { } impl Iterator for CodePoints where I: Iterator, { type Item = Result; fn next(&mut self) -> Option { let byte = self.iter.next()?; let mut code_point: u32 = byte.into(); macro_rules! consume_next { () => {{ if let Err(error) = self.consume_next(&mut code_point) { return Some(Err(error)); } }}; } let prev_surrogate = mem::replace(&mut self.surrogate, false); let mut invalid = false; if !byte.is_ascii() { if byte < 0xC2 { return Some(Err(EncodingError::Byte(byte))); } if byte < 0xE0 { code_point &= 0x1F; } else { code_point &= 0x0F; consume_next!(); if byte >= 0xF0 { if code_point.wrapping_sub(0x10) >= 0x100 { invalid = true; } consume_next!(); // This condition is optimized to detect surrogate code points. } else if code_point & 0xFE0 == 0x360 { self.still_utf8 = false; if code_point & 0x10 == 0 { self.surrogate = true; } else if prev_surrogate { // Decoding a broken surrogate pair would be lossy. invalid = true; } } if code_point < 0x20 { invalid = true; } } consume_next!(); } if invalid { return Some(Err(EncodingError::CodePoint(code_point))); } Some(Ok(code_point)) } } os_str_bytes-7.1.0/src/windows/convert/wtf8/convert.rs000064400000000000000000000110631046102023000212300ustar 00000000000000use std::char; use std::char::DecodeUtf16; use std::iter::FusedIterator; use std::num::NonZeroU16; use crate::util::BYTE_SHIFT; use crate::util::CONT_MASK; use crate::util::CONT_TAG; use crate::util::MAX_UTF8_LENGTH; use super::CodePoints; use super::Result; const MIN_HIGH_SURROGATE: u16 = 0xD800; const MIN_LOW_SURROGATE: u16 = 0xDC00; const MIN_SURROGATE_CODE: u32 = (u16::MAX as u32) + 1; const MAX_WTF8_LENGTH: usize = MAX_UTF8_LENGTH; macro_rules! static_assert { ( $condition:expr ) => { const _: () = assert!($condition, "static assertion failed"); }; } pub(in super::super) struct DecodeWide where I: Iterator, { iter: DecodeUtf16, code_point: u32, shifts: u8, } impl DecodeWide where I: Iterator, { pub(in super::super) fn new(string: S) -> Self where S: IntoIterator, { Self { iter: char::decode_utf16(string), code_point: 0, shifts: 0, } } #[inline(always)] const fn get_raw_byte(&self) -> u8 { (self.code_point >> (self.shifts * BYTE_SHIFT)) as u8 } } impl Iterator for DecodeWide where I: Iterator, { type Item = u8; fn next(&mut self) -> Option { if let Some(shifts) = self.shifts.checked_sub(1) { self.shifts = shifts; return Some((self.get_raw_byte() & CONT_MASK) | CONT_TAG); } self.code_point = self .iter .next()? .map(Into::into) .unwrap_or_else(|x| x.unpaired_surrogate().into()); macro_rules! decode { ( $tag:expr ) => { Some(self.get_raw_byte() | $tag) }; } macro_rules! try_decode { ( $tag:expr , $upper_bound:expr ) => { if self.code_point < $upper_bound { return decode!($tag); } self.shifts += 1; }; } try_decode!(0, 0x80); try_decode!(0xC0, 0x800); try_decode!(0xE0, MIN_SURROGATE_CODE); decode!(0xF0) } fn size_hint(&self) -> (usize, Option) { let (low, high) = self.iter.size_hint(); let shifts = self.shifts.into(); ( low.saturating_add(shifts), high.and_then(|x| x.checked_mul(MAX_WTF8_LENGTH)) .and_then(|x| x.checked_add(shifts)), ) } } pub(in super::super) struct EncodeWide where I: Iterator, { iter: CodePoints, surrogate: Option, } impl EncodeWide where I: Iterator, { fn new(string: S) -> Self where S: IntoIterator, { Self { iter: CodePoints::new(string), surrogate: None, } } pub(in super::super) const fn is_still_utf8(&self) -> bool { self.iter.is_still_utf8() } } impl FusedIterator for EncodeWide where I: FusedIterator + Iterator { } impl Iterator for EncodeWide where I: Iterator, { type Item = Result; fn next(&mut self) -> Option { if let Some(surrogate) = self.surrogate.take() { return Some(Ok(surrogate.get())); } self.iter.next().map(|code_point| { code_point.map(|code_point| { code_point .checked_sub(MIN_SURROGATE_CODE) .map(|offset| { static_assert!(MIN_LOW_SURROGATE != 0); // SAFETY: The above static assertion guarantees that // this value will not be zero. self.surrogate = Some(unsafe { NonZeroU16::new_unchecked( (offset & 0x3FF) as u16 | MIN_LOW_SURROGATE, ) }); (offset >> 10) as u16 | MIN_HIGH_SURROGATE }) .unwrap_or(code_point as u16) }) }) } fn size_hint(&self) -> (usize, Option) { let (low, high) = self.iter.inner_size_hint(); let additional = self.surrogate.is_some().into(); ( (low.saturating_add(2) / 3).saturating_add(additional), high.and_then(|x| x.checked_add(additional)), ) } } pub(in super::super) fn encode_wide( string: &[u8], ) -> EncodeWide> { EncodeWide::new(string.iter().copied()) } os_str_bytes-7.1.0/src/windows/convert/wtf8/mod.rs000064400000000000000000000006561046102023000203350ustar 00000000000000// This module implements the WTF-8 encoding specification: // https://simonsapin.github.io/wtf-8/ use super::EncodingError; use super::Result; mod code_points; use code_points::CodePoints; mod convert; pub(super) use convert::encode_wide; pub(super) use convert::DecodeWide; if_raw_str! { if_conversions! { mod string; pub(crate) use string::ends_with; pub(crate) use string::starts_with; } } os_str_bytes-7.1.0/src/windows/convert/wtf8/string.rs000064400000000000000000000040751046102023000210630ustar 00000000000000use crate::util; const SURROGATE_LENGTH: usize = 3; pub(crate) fn ends_with(string: &[u8], mut suffix: &[u8]) -> bool { let Some(index) = string.len().checked_sub(suffix.len()) else { return false; }; if let Some(&byte) = string.get(index) { if util::is_continuation(byte) { let index = expect_encoded!(index.checked_sub(1)); let mut wide_surrogate = if let Some(surrogate) = suffix.get(..SURROGATE_LENGTH) { super::encode_wide(surrogate) } else { return false; }; let surrogate_wchar = wide_surrogate .next() .expect("failed decoding non-empty suffix"); if wide_surrogate.next().is_some() || super::encode_wide(&string[index..]) .take_while(Result::is_ok) .nth(1) != Some(surrogate_wchar) { return false; } suffix = &suffix[SURROGATE_LENGTH..]; } } string.ends_with(suffix) } pub(crate) fn starts_with(string: &[u8], mut prefix: &[u8]) -> bool { if let Some(&byte) = string.get(prefix.len()) { if util::is_continuation(byte) { let Some(index) = prefix.len().checked_sub(SURROGATE_LENGTH) else { return false; }; let (substring, surrogate) = prefix.split_at(index); let mut wide_surrogate = super::encode_wide(surrogate); let surrogate_wchar = wide_surrogate .next() .expect("failed decoding non-empty prefix"); if surrogate_wchar.is_err() || wide_surrogate.next().is_some() || super::encode_wide(&string[index..]) .next() .expect("failed decoding non-empty substring") != surrogate_wchar { return false; } prefix = substring; } } string.starts_with(prefix) } os_str_bytes-7.1.0/src/windows/convert_io.rs000064400000000000000000000022221046102023000173440ustar 00000000000000use std::borrow::Cow; use std::ffi::OsStr; use std::ffi::OsString; use std::str; pub(crate) fn os_str_from_bytes(string: &[u8]) -> Option<&OsStr> { str::from_utf8(string).map(OsStr::new).ok() } pub(crate) fn os_str_to_bytes(string: &OsStr) -> Option<&'_ [u8]> { string.to_str().map(str::as_bytes) } pub(crate) fn os_str_to_bytes_lossy(string: &OsStr) -> Cow<'_, [u8]> { match string.to_string_lossy() { Cow::Borrowed(string) => Cow::Borrowed(string.as_bytes()), Cow::Owned(string) => Cow::Owned(string.into_bytes()), } } pub(crate) fn os_string_from_vec(string: Vec) -> Option { String::from_utf8(string).ok().map(Into::into) } pub(crate) fn os_string_into_vec(string: OsString) -> Option> { string.into_string().ok().map(String::into_bytes) } pub(crate) fn os_string_into_vec_lossy(string: OsString) -> Vec { let string = string.into_encoded_bytes(); match String::from_utf8_lossy(&string) { // SAFETY: This slice was validated to be UTF-8. Cow::Borrowed(_) => unsafe { String::from_utf8_unchecked(string) }, Cow::Owned(string) => string, } .into_bytes() } os_str_bytes-7.1.0/src/windows/mod.rs000064400000000000000000000004061046102023000157560ustar 00000000000000if_conversions! { #[cfg(target_os = "uefi")] use std::os::uefi as os; #[cfg(windows)] use std::os::windows as os; } pub(super) mod convert_io; if_conversions! { pub(super) mod convert; if_raw_str! { pub(super) mod raw; } } os_str_bytes-7.1.0/src/windows/raw.rs000064400000000000000000000001261046102023000157670ustar 00000000000000pub(crate) use super::convert::ends_with; pub(crate) use super::convert::starts_with;