camino-1.0.5/.cargo_vcs_info.json0000644000000001120000000000000122760ustar { "git": { "sha1": "8aa72052754a3b8d3b9ec1fe95391fb06365608c" } } camino-1.0.5/.gitignore000064400000000000000000000000230000000000000130350ustar 00000000000000/target Cargo.lock camino-1.0.5/CHANGELOG.md000064400000000000000000000037300000000000000126660ustar 00000000000000# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.5] - 2021-07-27 ### Added - `Utf8PathBuf::into_std_path_buf` converts a `Utf8PathBuf` to a `PathBuf`; equivalent to the `From for PathBuf` impl, but may aid in type inference. - `Utf8Path::as_std_path` converts a `Utf8Path` to a `Path`; equivalent to the `AsRef<&Path> for &Utf8Path` impl, but may aid in type inference. ## [1.0.4] - 2021-03-19 ### Fixed - `Hash` impls for `Utf8PathBuf` and `Utf8Path` now match as required by the `Borrow` contract ([#9]). [#9]: https://github.com/withoutboats/camino/issues/9 ## [1.0.3] - 2021-03-11 ### Added - `TryFrom for Utf8PathBuf` and `TryFrom<&Path> for &Utf8Path`, both of which return new error types ([#6]). - `AsRef`, `AsRef`, `AsRef` and `AsRef` impls for `Utf8Components`, `Utf8Component` and `Iter`. [#6]: https://github.com/withoutboats/camino/issues/6 ## [1.0.2] - 2021-03-02 ### Added - `From` impls for converting a `&Utf8Path` or a `Utf8PathBuf` into `Box`, `Rc`, `Arc` and `Cow<'a, Path>`. - `PartialEq` and `PartialOrd` implementations comparing `Utf8Path` and `Utf8PathBuf` with `Path`, `PathBuf` and its variants, and comparing `OsStr`, `OsString` and its variants. ## [1.0.1] - 2021-02-25 ### Added - More `PartialEq` and `PartialOrd` implementations. - MSRV lowered to 1.34. ## [1.0.0] - 2021-02-23 Initial release. [1.0.5]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.5 [1.0.4]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.4 [1.0.3]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.3 [1.0.2]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.2 [1.0.1]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.1 [1.0.0]: https://github.com/withoutboats/camino/releases/tag/camino-1.0.0 camino-1.0.5/CODE_OF_CONDUCT.md000064400000000000000000000126610000000000000136570ustar 00000000000000# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at the email address: [codeofconduct@sunshowers.io](mailto:codeofconduct@sunshowers.io). All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at [https://www.contributor-covenant.org/version/2/0/code_of_conduct.html][v2.0]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.0]: https://www.contributor-covenant.org/version/2/0/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations camino-1.0.5/Cargo.lock0000644000000160530000000000000102640ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "ansi_term" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" dependencies = [ "winapi", ] [[package]] name = "anyhow" version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "afddf7f520a80dbf76e6f50a35bca42a2331ef227a28b3b6dc5c2e2338d114b1" [[package]] name = "atty" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" dependencies = [ "hermit-abi", "libc", "winapi", ] [[package]] name = "bitflags" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" [[package]] name = "camino" version = "1.0.5" dependencies = [ "anyhow", "serde", "serde_json", "structopt", ] [[package]] name = "clap" version = "2.33.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" dependencies = [ "ansi_term", "atty", "bitflags", "strsim", "textwrap", "unicode-width", "vec_map", ] [[package]] name = "heck" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87cbf45460356b7deeb5e3415b5563308c0a9b057c85e12b06ad551f98d0a6ac" dependencies = [ "unicode-segmentation", ] [[package]] name = "hermit-abi" version = "0.1.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" dependencies = [ "libc", ] [[package]] name = "itoa" version = "0.4.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" version = "0.2.90" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba4aede83fc3617411dc6993bc8c70919750c1c257c6ca6a502aed6e0e2394ae" [[package]] name = "proc-macro-error" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", "proc-macro2", "quote", "syn", "version_check", ] [[package]] name = "proc-macro-error-attr" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ "proc-macro2", "quote", "version_check", ] [[package]] name = "proc-macro2" version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71" dependencies = [ "unicode-xid", ] [[package]] name = "quote" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" dependencies = [ "proc-macro2", ] [[package]] name = "ryu" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" [[package]] name = "serde" version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd761ff957cb2a45fbb9ab3da6512de9de55872866160b23c25f1a841e99d29f" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.124" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1800f7693e94e186f5e25a28291ae1570da908aff7d97a095dec1e56ff99069b" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "strsim" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" [[package]] name = "structopt" version = "0.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5277acd7ee46e63e5168a80734c9f6ee81b1367a7d8772a2d765df2a3705d28c" dependencies = [ "clap", "lazy_static", "structopt-derive", ] [[package]] name = "structopt-derive" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ba9cdfda491b814720b6b06e0cac513d922fc407582032e8706e9f137976f90" dependencies = [ "heck", "proc-macro-error", "proc-macro2", "quote", "syn", ] [[package]] name = "syn" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fd9d1e9976102a03c542daa2eff1b43f9d72306342f3f8b3ed5fb8908195d6f" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "textwrap" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" dependencies = [ "unicode-width", ] [[package]] name = "unicode-segmentation" version = "1.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0d2e7be6ae3a5fa87eed5fb451aff96f2573d2694942e40543ae0bbe19c796" [[package]] name = "unicode-width" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" [[package]] name = "unicode-xid" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564" [[package]] name = "vec_map" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" [[package]] name = "version_check" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" camino-1.0.5/Cargo.toml0000644000000026330000000000000103060ustar # 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "camino" version = "1.0.5" authors = ["Without Boats ", "Ashley Williams ", "Steve Klabnik ", "Rain "] exclude = [".cargo/**/*", ".github/**/*"] description = "UTF-8 paths" documentation = "https://docs.rs/camino" readme = "README.md" keywords = ["paths", "utf8", "unicode", "filesystem"] categories = ["development-tools", "filesystem", "os"] license = "MIT OR Apache-2.0" repository = "https://github.com/withoutboats/camino" [package.metadata.docs.rs] all-features = true [[example]] name = "serde" required-features = ["serde1"] [dependencies.serde] version = "1" features = ["derive"] optional = true [dev-dependencies.anyhow] version = "1.0.38" [dev-dependencies.serde_json] version = "1.0.62" [dev-dependencies.structopt] version = "0.3.21" [features] serde1 = ["serde"] camino-1.0.5/Cargo.toml.orig000064400000000000000000000016300000000000000137410ustar 00000000000000[package] name = "camino" description = "UTF-8 paths" version = "1.0.5" license = "MIT OR Apache-2.0" readme = "README.md" keywords = [ "paths", "utf8", "unicode", "filesystem", ] categories = [ "development-tools", "filesystem", "os", ] repository = "https://github.com/withoutboats/camino" documentation = "https://docs.rs/camino" authors = [ "Without Boats ", "Ashley Williams ", "Steve Klabnik ", "Rain " ] edition = "2018" exclude = [ ".cargo/**/*", ".github/**/*", ] [package.metadata.docs.rs] all-features = true [dependencies] serde = { version = "1", features = ["derive"], optional = true } [dev-dependencies] anyhow = "1.0.38" structopt = "0.3.21" serde_json = "1.0.62" [features] serde1 = ["serde"] [[example]] name = "serde" required-features = ["serde1"] camino-1.0.5/LICENSE-APACHE000064400000000000000000000251370000000000000130060ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. camino-1.0.5/LICENSE-MIT000064400000000000000000000017770000000000000125220ustar 00000000000000Permission 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. camino-1.0.5/README.md000064400000000000000000000170060000000000000123350ustar 00000000000000# camino - UTF-8 encoded paths [![camino on crates.io](https://img.shields.io/crates/v/camino)](https://crates.io/crates/camino) [![crates.io download count](https://img.shields.io/crates/d/camino)](https://crates.io/crates/camino) [![Documentation (latest release)](https://docs.rs/camino/badge.svg)](https://docs.rs/camino) [![License](https://img.shields.io/badge/license-Apache-green.svg)](LICENSE-APACHE) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE-MIT) This repository contains the source code for `camino`, an extension of the `std::path` module that adds new [`Utf8PathBuf`] and [`Utf8Path`] types. ## What is camino? `camino`'s [`Utf8PathBuf`] and [`Utf8Path`] types are like the standard library's [`PathBuf`] and [`Path`] types, except they are guaranteed to only contain UTF-8 encoded data. Therefore, they expose the ability to get their contents as strings, they implement `Display`, etc. The `std::path` types are not guaranteed to be valid UTF-8. This is the right decision for the standard library, since it must be as general as possible. However, on all platforms, non-Unicode paths are vanishingly uncommon for a number of reasons: * Unicode won. There are still some legacy codebases that store paths in encodings like [Shift JIS], but most have been converted to Unicode at this point. * Unicode is the common subset of supported paths across Windows and Unix platforms. (On Windows, Rust stores paths as [an extension to UTF-8](https://simonsapin.github.io/wtf-8/), and converts them to UTF-16 at Win32 API boundaries.) * There are already many systems, such as Cargo, that only support UTF-8 paths. If your own tool interacts with any such system, you can assume that paths are valid UTF-8 without creating any additional burdens on consumers. * The ["makefile problem"](https://www.mercurial-scm.org/wiki/EncodingStrategy#The_.22makefile_problem.22) asks: given a Makefile or other metadata file (such as `Cargo.toml`) that lists the names of other files, how should the names in the Makefile be matched with the ones on disk? This has *no general, cross-platform solution* in systems that support non-UTF-8 paths. However, restricting paths to UTF-8 eliminates this problem. [Shift JIS]: https://en.wikipedia.org/wiki/Shift_JIS Therefore, many programs that want to manipulate paths *do* assume they contain UTF-8 data, and convert them to `str`s as necessary. However, because this invariant is not encoded in the `Path` type, conversions such as `path.to_str().unwrap()` need to be repeated again and again, creating a frustrating experience. Instead, `camino` allows you to check that your paths are UTF-8 *once*, and then manipulate them as valid UTF-8 from there on, avoiding repeated lossy and confusing conversions. ## Examples The documentation for [`Utf8PathBuf`] and [`Utf8Path`] contains several examples. For examples of how to use `camino` with other libraries like `serde` and `structopt`, see the [`examples`] directory. ## API design `camino` is a very thin wrapper around `std::path`. [`Utf8Path`] and [`Utf8PathBuf`] are drop-in replacements for [`Path`] and [`PathBuf`]. Most APIs are the same, but those at the boundary with `str` are different. Some examples: * `Path::to_str() -> Option<&str>` has been renamed to `Utf8Path::as_str() -> &str`. * [`Utf8Path`] implements `Display`, and `Path::display()` has been removed. * Iterating over a [`Utf8Path`] returns `&str`, not `&OsStr`. Every [`Utf8Path`] is a valid [`Path`], so [`Utf8Path`] implements `AsRef`. Any APIs that accept `impl AsRef` will continue to work with [`Utf8Path`] instances. ## Should you use camino? `camino` trades off some utility for a great deal of simplicity. Whether `camino` is appropriate for a project or not is ultimately a case-by-case decision. Here are some general guidelines that may help. *You should consider using camino if...* * **You're building portable, cross-platform software.** While both Unix and Windows platforms support different kinds of non-Unicode paths, Unicode is the common subset that's supported across them. * **Your system has files that contain the names of other files.** If you don't use UTF-8 paths, you will run into the makefile problem described above, which has no general, cross-platform solution. * **You're interacting with existing systems that already assume UTF-8 paths.** In that case you won't be adding any new burdens on downstream consumers. * **You're building something brand new and are willing to ask your users to rename their paths if necessary.** Projects that don't have to worry about legacy compatibility have more flexibility in choosing what paths they support. *You should **NOT** use camino, if...* * **You're writing a core system utility.** If you're writing, say, an `mv` or `cat` replacement, you should **not** use camino. Instead, use [`std::path::Path`] and add extensive tests for non-UTF-8 paths. * **You have legacy compatibility constraints.** For example, Git supports non-UTF-8 paths. If your tool needs to handle arbitrary Git repositories, it should use its own path type that's a wrapper around `Vec`. * [`std::path::Path`] supports arbitrary bytestrings [on Unix] but not on Windows. * **There's some other reason you need to support non-UTF-8 paths.** Some tools like disk recovery utilities need to handle potentially corrupt filenames: only being able to handle UTF-8 paths would greatly diminish their utility. [on Unix]: https://doc.rust-lang.org/std/os/unix/ffi/index.html ## Optional features By default, `camino` has **no dependencies** other than `std`. There are some optional features that enable dependencies: * `serde1` adds serde [`Serialize`] and [`Deserialize`] impls for [`Utf8PathBuf`] and [`Utf8Path`] (zero-copy). ## Rust version support The minimum supported Rust version (MSRV) for `camino` with default features is **1.34**. This project is tested in CI against the latest stable version of Rust and the MSRV. * *Stable APIs* added in later Rust versions are supported through conditional compilation in `build.rs`. * *Deprecations* are kept in sync with the version of Rust they're added in. * *Unstable APIs* are currently not supported. Please [file an issue on GitHub](https://github.com/withoutboats/camino/issues/new) if you need an unstable API. `camino` is designed to be a core library and has a conservative MSRV policy. MSRV increases will only happen for a compelling enough reason, and will involve at least a minor version bump. Optional features may pull in dependencies that require a newer version of Rust. ## License This project is available under the terms of either the [Apache 2.0 license](LICENSE-APACHE) or the [MIT license](LICENSE-MIT). This project's documentation is adapted from [The Rust Programming Language](https://github.com/rust-lang/rust/), which is available under the terms of either the [Apache 2.0 license](https://github.com/rust-lang/rust/blob/master/LICENSE-APACHE) or the [MIT license](https://github.com/rust-lang/rust/blob/master/LICENSE-MIT). [`Utf8PathBuf`]: https://docs.rs/camino/*/camino/struct.Utf8PathBuf.html [`Utf8Path`]: https://docs.rs/camino/*/camino/struct.Utf8Path.html [`PathBuf`]: https://doc.rust-lang.org/std/path/struct.PathBuf.html [`Path`]: https://doc.rust-lang.org/std/path/struct.Path.html [`std::path::Path`]: https://doc.rust-lang.org/std/path/struct.Path.html [`Serialize`]: https://docs.rs/serde/1/serde/trait.Serialize.html [`Deserialize`]: https://docs.rs/serde/1/serde/trait.Deserialize.html [`examples`]: https://github.com/withoutboats/camino/tree/master/examples camino-1.0.5/build.rs000064400000000000000000000023270000000000000125230ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Adapted from //! https://github.com/dtolnay/syn/blob/a54fb0098c6679f1312113ae2eec0305c51c7390/build.rs. use std::{env, process::Command, str}; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn main() { let compiler = match rustc_version() { Some(compiler) => compiler, None => return, }; // NOTE: // Adding a new cfg gated by Rust version MUST be accompanied by an addition to the matrix in // .github/workflows/ci.yml. if compiler.minor >= 44 { println!("cargo:rustc-cfg=path_buf_capacity"); } } struct Compiler { minor: u32, } fn rustc_version() -> Option { let rustc = env::var_os("RUSTC")?; let output = Command::new(rustc).arg("--version").output().ok()?; let version = str::from_utf8(&output.stdout).ok()?; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } let minor = pieces.next()?.parse().ok()?; Some(Compiler { minor }) } camino-1.0.5/clippy.toml000064400000000000000000000000200000000000000132370ustar 00000000000000msrv = "1.34.0" camino-1.0.5/examples/serde.rs000064400000000000000000000045410000000000000143440ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use anyhow::Result; use camino::{Utf8Path, Utf8PathBuf}; use serde::{Deserialize, Serialize}; use std::borrow::Cow; /// This example demonstrates how to use a `Utf8Path` in a `serde` struct. /// /// With the `serde1` feature, `camino` paths can be used as targets for `serde` serialization and /// deserialization. (Note that serde itself [does not support] parsing non-UTF-8 `PathBuf`s, so /// there is no loss of generality in switching to `Utf8PathBuf` instances.) /// /// To run this example, run `cargo run --features serde1 --example serde`. /// /// [does not support]: https://docs.rs/crate/serde/1.0.123/source/src/de/impls.rs #[derive(Serialize, Deserialize)] struct MyStruct { input: Utf8PathBuf, output: Utf8PathBuf, } /// A borrowed version of `MyStruct`, to demonstrate zero-copy deserialization to `Utf8Path`s. #[derive(Serialize, Deserialize)] struct MyStructBorrowed<'a> { #[serde(borrow)] input: &'a Utf8Path, // Note: This always deserializes to an owned string because of // https://github.com/serde-rs/serde/issues/1852. In the future we may add a `camino-utils` // library with a `CowUtf8Path<'a>` wrapper which can deserialize to the borrowed implementation // if possible. #[serde(borrow)] output: Cow<'a, Utf8Path>, } static JSON_STR: &str = "{ \"input\": \"/foo/bar\", \"output\": \"/baz\\\\/quux\" }"; pub fn main() -> Result<()> { println!("*** json string: {}", JSON_STR); println!("*** Trying deserialize..."); // Deserialize to MyStruct. let deserialized: MyStruct = serde_json::from_str(JSON_STR)?; assert_eq!(deserialized.input, "/foo/bar"); assert_eq!(deserialized.output, "/baz\\/quux"); println!("*** Trying serialize..."); let serialized = serde_json::to_string_pretty(&deserialized)?; println!("serialize output: {}", serialized); println!("*** Trying zero-copy deserialize..."); // Zero-copy deserialize to MyStructBorrowed. let zero_copy: MyStructBorrowed<'_> = serde_json::from_str(JSON_STR)?; assert_eq!(zero_copy.input, "/foo/bar"); assert_eq!(zero_copy.output.as_str(), "/baz\\/quux"); println!("*** Trying zero-copy serialize..."); let serialized = serde_json::to_string_pretty(&zero_copy)?; println!("serialize output: {}", serialized); Ok(()) } camino-1.0.5/examples/structopt.rs000064400000000000000000000016150000000000000153100ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use camino::Utf8PathBuf; use structopt::StructOpt; /// This example shows how a `Utf8Path` can be used with `structopt` argument parsing. /// /// Using a `Utf8Path` in argument parsing in this manner means that non-UTF-8 paths can be rejected /// at the boundaries of your program. /// /// To run this example, run `cargo run --example structopt`. #[derive(StructOpt)] #[structopt(rename_all = "kebab-case")] struct Opt { /// Input file input: Utf8PathBuf, /// Output file output: Option, } pub fn main() { // Parse the arguments. let opt = Opt::from_args(); // Print the input and output files. println!("input file: {}", opt.input); match &opt.output { Some(output) => println!("output file: {}", output), None => println!("no output file"), } } camino-1.0.5/rustfmt.toml000064400000000000000000000000610000000000000134500ustar 00000000000000edition = "2018" use_field_init_shorthand = true camino-1.0.5/src/lib.rs000064400000000000000000002237670000000000000127760ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 #![warn(missing_docs)] //! UTF-8 encoded paths. //! //! `camino` is an extension of the `std::path` module that adds new `Utf8PathBuf` and `Utf8Path` //! types. These are like the standard library's [`PathBuf`] and [`Path`] types, except they are //! guaranteed to only contain UTF-8 encoded data. Therefore, they expose the ability to get their //! contents as strings, they implement `Display`, etc. //! //! The `std::path` types are not guaranteed to be valid UTF-8. This is the right decision for the standard library, //! since it must be as general as possible. However, on all platforms, non-Unicode paths are vanishingly uncommon for a //! number of reasons: //! * Unicode won. There are still some legacy codebases that store paths in encodings like Shift-JIS, but most //! have been converted to Unicode at this point. //! * Unicode is the common subset of supported paths across Windows and Unix platforms. (On Windows, Rust stores paths //! as [an extension to UTF-8](https://simonsapin.github.io/wtf-8/), and converts them to UTF-16 at Win32 //! API boundaries.) //! * There are already many systems, such as Cargo, that only support UTF-8 paths. If your own tool interacts with any such //! system, you can assume that paths are valid UTF-8 without creating any additional burdens on consumers. //! * The ["makefile problem"](https://www.mercurial-scm.org/wiki/EncodingStrategy#The_.22makefile_problem.22) //! (which also applies to `Cargo.toml`, and any other metadata file that lists the names of other files) has *no general, //! cross-platform solution* in systems that support non-UTF-8 paths. However, restricting paths to UTF-8 eliminates //! this problem. //! //! Therefore, many programs that want to manipulate paths *do* assume they contain UTF-8 data, and convert them to `str`s //! as necessary. However, because this invariant is not encoded in the `Path` type, conversions such as //! `path.to_str().unwrap()` need to be repeated again and again, creating a frustrating experience. //! //! Instead, `camino` allows you to check that your paths are UTF-8 *once*, and then manipulate them //! as valid UTF-8 from there on, avoiding repeated lossy and confusing conversions. use std::{ borrow::{Borrow, Cow}, cmp::Ordering, convert::{Infallible, TryFrom}, error, ffi::{OsStr, OsString}, fmt, fs, hash::{Hash, Hasher}, io, iter::FusedIterator, ops::Deref, path::*, rc::Rc, str::FromStr, sync::Arc, }; #[cfg(feature = "serde1")] mod serde_impls; #[cfg(test)] mod tests; /// An owned, mutable UTF-8 path (akin to [`String`]). /// /// This type provides methods like [`push`] and [`set_extension`] that mutate /// the path in place. It also implements [`Deref`] to [`Utf8Path`], meaning that /// all methods on [`Utf8Path`] slices are available on `Utf8PathBuf` values as well. /// /// [`push`]: Utf8PathBuf::push /// [`set_extension`]: Utf8PathBuf::set_extension /// /// # Examples /// /// You can use [`push`] to build up a `Utf8PathBuf` from /// components: /// /// ``` /// use camino::Utf8PathBuf; /// /// let mut path = Utf8PathBuf::new(); /// /// path.push(r"C:\"); /// path.push("windows"); /// path.push("system32"); /// /// path.set_extension("dll"); /// ``` /// /// However, [`push`] is best used for dynamic situations. This is a better way /// to do this when you know all of the components ahead of time: /// /// ``` /// use camino::Utf8PathBuf; /// /// let path: Utf8PathBuf = [r"C:\", "windows", "system32.dll"].iter().collect(); /// ``` /// /// We can still do better than this! Since these are all strings, we can use /// `From::from`: /// /// ``` /// use camino::Utf8PathBuf; /// /// let path = Utf8PathBuf::from(r"C:\windows\system32.dll"); /// ``` /// /// Which method works best depends on what kind of situation you're in. // NB: Internal PathBuf must only contain utf8 data #[derive(Clone, Default)] #[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "serde1", serde(transparent))] #[repr(transparent)] pub struct Utf8PathBuf(PathBuf); impl Utf8PathBuf { /// Allocates an empty `Utf8PathBuf`. /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// /// let path = Utf8PathBuf::new(); /// ``` pub fn new() -> Utf8PathBuf { Utf8PathBuf(PathBuf::new()) } /// Creates a new `Utf8PathBuf` from a `PathBuf` containing valid UTF-8 characters. /// /// Errors with the original `PathBuf` if it is not valid UTF-8. /// /// For a version that returns a type that implements [`std::error::Error`], use the /// `TryFrom` impl. /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// use std::ffi::OsStr; /// # #[cfg(unix)] /// use std::os::unix::ffi::OsStrExt; /// use std::path::PathBuf; /// /// let unicode_path = PathBuf::from("/valid/unicode"); /// Utf8PathBuf::from_path_buf(unicode_path).expect("valid Unicode path succeeded"); /// /// // Paths on Unix can be non-UTF-8. /// # #[cfg(unix)] /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF"); /// # #[cfg(unix)] /// let non_unicode_path = PathBuf::from(non_unicode_str); /// # #[cfg(unix)] /// Utf8PathBuf::from_path_buf(non_unicode_path).expect_err("non-Unicode path failed"); /// ``` pub fn from_path_buf(path: PathBuf) -> Result { match path.into_os_string().into_string() { Ok(string) => Ok(Utf8PathBuf::from(string)), Err(os_string) => Err(PathBuf::from(os_string)), } } /// Converts a `Utf8PathBuf` to a [`PathBuf`]. /// /// This is equivalent to the `From for PathBuf` impl, but may aid in type /// inference. /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// use std::path::PathBuf; /// /// let utf8_path_buf = Utf8PathBuf::from("foo.txt"); /// let std_path_buf = utf8_path_buf.into_std_path_buf(); /// assert_eq!(std_path_buf.to_str(), Some("foo.txt")); /// /// // Convert back to a Utf8PathBuf. /// let new_utf8_path_buf = Utf8PathBuf::from_path_buf(std_path_buf).unwrap(); /// assert_eq!(new_utf8_path_buf, "foo.txt"); /// ``` pub fn into_std_path_buf(self) -> PathBuf { self.into() } /// Creates a new `Utf8PathBuf` with a given capacity used to create the internal [`PathBuf`]. /// See [`with_capacity`] defined on [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// /// let mut path = Utf8PathBuf::with_capacity(10); /// let capacity = path.capacity(); /// /// // This push is done without reallocating /// path.push(r"C:\"); /// /// assert_eq!(capacity, path.capacity()); /// ``` /// /// [`with_capacity`]: PathBuf::with_capacity #[cfg(path_buf_capacity)] pub fn with_capacity(capacity: usize) -> Utf8PathBuf { Utf8PathBuf(PathBuf::with_capacity(capacity)) } /// Coerces to a [`Utf8Path`] slice. /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let p = Utf8PathBuf::from("/test"); /// assert_eq!(Utf8Path::new("/test"), p.as_path()); /// ``` pub fn as_path(&self) -> &Utf8Path { // SAFETY: every Utf8PathBuf constructor ensures that self is valid UTF-8 unsafe { Utf8Path::assume_utf8(&*self.0) } } /// Extends `self` with `path`. /// /// If `path` is absolute, it replaces the current path. /// /// On Windows: /// /// * if `path` has a root but no prefix (e.g., `\windows`), it /// replaces everything except for the prefix (if any) of `self`. /// * if `path` has a prefix but no root, it replaces `self`. /// /// # Examples /// /// Pushing a relative path extends the existing path: /// /// ``` /// use camino::Utf8PathBuf; /// /// let mut path = Utf8PathBuf::from("/tmp"); /// path.push("file.bk"); /// assert_eq!(path, Utf8PathBuf::from("/tmp/file.bk")); /// ``` /// /// Pushing an absolute path replaces the existing path: /// /// ``` /// use camino::Utf8PathBuf; /// /// let mut path = Utf8PathBuf::from("/tmp"); /// path.push("/etc"); /// assert_eq!(path, Utf8PathBuf::from("/etc")); /// ``` pub fn push(&mut self, path: impl AsRef) { self.0.push(&path.as_ref().0) } /// Truncates `self` to [`self.parent`]. /// /// Returns `false` and does nothing if [`self.parent`] is [`None`]. /// Otherwise, returns `true`. /// /// [`self.parent`]: Utf8Path::parent /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let mut p = Utf8PathBuf::from("/spirited/away.rs"); /// /// p.pop(); /// assert_eq!(Utf8Path::new("/spirited"), p); /// p.pop(); /// assert_eq!(Utf8Path::new("/"), p); /// ``` pub fn pop(&mut self) -> bool { self.0.pop() } /// Updates [`self.file_name`] to `file_name`. /// /// If [`self.file_name`] was [`None`], this is equivalent to pushing /// `file_name`. /// /// Otherwise it is equivalent to calling [`pop`] and then pushing /// `file_name`. The new path will be a sibling of the original path. /// (That is, it will have the same parent.) /// /// [`self.file_name`]: Utf8Path::file_name /// [`pop`]: Utf8PathBuf::pop /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// /// let mut buf = Utf8PathBuf::from("/"); /// assert_eq!(buf.file_name(), None); /// buf.set_file_name("bar"); /// assert_eq!(buf, Utf8PathBuf::from("/bar")); /// assert!(buf.file_name().is_some()); /// buf.set_file_name("baz.txt"); /// assert_eq!(buf, Utf8PathBuf::from("/baz.txt")); /// ``` pub fn set_file_name(&mut self, file_name: impl AsRef) { self.0.set_file_name(file_name.as_ref()) } /// Updates [`self.extension`] to `extension`. /// /// Returns `false` and does nothing if [`self.file_name`] is [`None`], /// returns `true` and updates the extension otherwise. /// /// If [`self.extension`] is [`None`], the extension is added; otherwise /// it is replaced. /// /// [`self.file_name`]: Utf8Path::file_name /// [`self.extension`]: Utf8Path::extension /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let mut p = Utf8PathBuf::from("/feel/the"); /// /// p.set_extension("force"); /// assert_eq!(Utf8Path::new("/feel/the.force"), p.as_path()); /// /// p.set_extension("dark_side"); /// assert_eq!(Utf8Path::new("/feel/the.dark_side"), p.as_path()); /// ``` pub fn set_extension(&mut self, extension: impl AsRef) -> bool { self.0.set_extension(extension.as_ref()) } /// Consumes the `Utf8PathBuf`, yielding its internal [`String`] storage. /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// /// let p = Utf8PathBuf::from("/the/head"); /// let s = p.into_string(); /// assert_eq!(s, "/the/head"); /// ``` pub fn into_string(self) -> String { self.into_os_string().into_string().unwrap() } /// Consumes the `Utf8PathBuf`, yielding its internal [`OsString`] storage. /// /// # Examples /// /// ``` /// use camino::Utf8PathBuf; /// use std::ffi::OsStr; /// /// let p = Utf8PathBuf::from("/the/head"); /// let s = p.into_os_string(); /// assert_eq!(s, OsStr::new("/the/head")); /// ``` pub fn into_os_string(self) -> OsString { self.0.into_os_string() } /// Converts this `Utf8PathBuf` into a [boxed](Box) [`Utf8Path`]. pub fn into_boxed_path(self) -> Box { let ptr = Box::into_raw(self.0.into_boxed_path()) as *mut Utf8Path; // SAFETY: // * self is valid UTF-8 // * ptr was constructed by consuming self so it represents an owned path // * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to // *mut Utf8Path is valid unsafe { Box::from_raw(ptr) } } /// Invokes [`capacity`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// [`capacity`]: PathBuf::capacity #[cfg(path_buf_capacity)] pub fn capacity(&self) -> usize { self.0.capacity() } /// Invokes [`clear`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// [`clear`]: PathBuf::clear #[cfg(path_buf_capacity)] pub fn clear(&mut self) { self.0.clear() } /// Invokes [`reserve`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// [`reserve`]: PathBuf::reserve #[cfg(path_buf_capacity)] pub fn reserve(&mut self, additional: usize) { self.0.reserve(additional) } /// Invokes [`reserve_exact`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// [`reserve_exact`]: PathBuf::reserve_exact #[cfg(path_buf_capacity)] pub fn reserve_exact(&mut self, additional: usize) { self.0.reserve_exact(additional) } /// Invokes [`shrink_to_fit`] on the underlying instance of [`PathBuf`]. /// /// *Requires Rust 1.44 or newer.* /// /// [`shrink_to_fit`]: PathBuf::shrink_to_fit #[cfg(path_buf_capacity)] pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit() } } impl Deref for Utf8PathBuf { type Target = Utf8Path; fn deref(&self) -> &Utf8Path { self.as_path() } } impl fmt::Debug for Utf8PathBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl fmt::Display for Utf8PathBuf { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl> Extend

for Utf8PathBuf { fn extend>(&mut self, iter: I) { for path in iter { self.push(path); } } } /// A slice of a UTF-8 path (akin to [`str`]). /// /// This type supports a number of operations for inspecting a path, including /// breaking the path into its components (separated by `/` on Unix and by either /// `/` or `\` on Windows), extracting the file name, determining whether the path /// is absolute, and so on. /// /// This is an *unsized* type, meaning that it must always be used behind a /// pointer like `&` or [`Box`]. For an owned version of this type, /// see [`Utf8PathBuf`]. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// // Note: this example does work on Windows /// let path = Utf8Path::new("./foo/bar.txt"); /// /// let parent = path.parent(); /// assert_eq!(parent, Some(Utf8Path::new("./foo"))); /// /// let file_stem = path.file_stem(); /// assert_eq!(file_stem, Some("bar")); /// /// let extension = path.extension(); /// assert_eq!(extension, Some("txt")); /// ``` // NB: Internal Path must only contain utf8 data #[repr(transparent)] pub struct Utf8Path(Path); impl Utf8Path { /// Directly wraps a string slice as a `Utf8Path` slice. /// /// This is a cost-free conversion. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// Utf8Path::new("foo.txt"); /// ``` /// /// You can create `Utf8Path`s from `String`s, or even other `Utf8Path`s: /// /// ``` /// use camino::Utf8Path; /// /// let string = String::from("foo.txt"); /// let from_string = Utf8Path::new(&string); /// let from_path = Utf8Path::new(&from_string); /// assert_eq!(from_string, from_path); /// ``` pub fn new(s: &(impl AsRef + ?Sized)) -> &Utf8Path { let path = Path::new(s.as_ref()); // SAFETY: s is a str which means it is always valid UTF-8 unsafe { Utf8Path::assume_utf8(path) } } /// Converts a [`Path`] to a `Utf8Path`. /// /// Returns `None` if the path is not valid UTF-8. /// /// For a version that returns a type that implements [`std::error::Error`], use the /// `TryFrom<&Path>` impl. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// use std::ffi::OsStr; /// # #[cfg(unix)] /// use std::os::unix::ffi::OsStrExt; /// use std::path::Path; /// /// let unicode_path = Path::new("/valid/unicode"); /// Utf8Path::from_path(unicode_path).expect("valid Unicode path succeeded"); /// /// // Paths on Unix can be non-UTF-8. /// # #[cfg(unix)] /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF"); /// # #[cfg(unix)] /// let non_unicode_path = Path::new(non_unicode_str); /// # #[cfg(unix)] /// assert!(Utf8Path::from_path(non_unicode_path).is_none(), "non-Unicode path failed"); /// ``` pub fn from_path(path: &Path) -> Option<&Utf8Path> { path.as_os_str().to_str().map(|s| Utf8Path::new(s)) } /// Converts a `Utf8Path` to a [`Path`]. /// /// This is equivalent to the `AsRef<&Path> for &Utf8Path` impl, but may aid in type inference. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// use std::path::Path; /// /// let utf8_path = Utf8Path::new("foo.txt"); /// let std_path: &Path = utf8_path.as_std_path(); /// assert_eq!(std_path.to_str(), Some("foo.txt")); /// /// // Convert back to a Utf8Path. /// let new_utf8_path = Utf8Path::from_path(std_path).unwrap(); /// assert_eq!(new_utf8_path, "foo.txt"); /// ``` pub fn as_std_path(&self) -> &Path { self.as_ref() } /// Yields the underlying [`str`] slice. /// /// Unlike [`Path::to_str`], this always returns a slice because the contents of a `Utf8Path` /// are guaranteed to be valid UTF-8. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let s = Utf8Path::new("foo.txt").as_str(); /// assert_eq!(s, "foo.txt"); /// ``` /// /// [`str`]: str pub fn as_str(&self) -> &str { // SAFETY: every Utf8Path constructor ensures that self is valid UTF-8 unsafe { assume_utf8(self.as_os_str()) } } /// Yields the underlying [`OsStr`] slice. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let os_str = Utf8Path::new("foo.txt").as_os_str(); /// assert_eq!(os_str, std::ffi::OsStr::new("foo.txt")); /// ``` pub fn as_os_str(&self) -> &OsStr { self.0.as_os_str() } /// Converts a `Utf8Path` to an owned [`Utf8PathBuf`]. /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let path_buf = Utf8Path::new("foo.txt").to_path_buf(); /// assert_eq!(path_buf, Utf8PathBuf::from("foo.txt")); /// ``` pub fn to_path_buf(&self) -> Utf8PathBuf { Utf8PathBuf(self.0.to_path_buf()) } /// Returns `true` if the `Utf8Path` is absolute, i.e., if it is independent of /// the current directory. /// /// * On Unix, a path is absolute if it starts with the root, so /// `is_absolute` and [`has_root`] are equivalent. /// /// * On Windows, a path is absolute if it has a prefix and starts with the /// root: `c:\windows` is absolute, while `c:temp` and `\temp` are not. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert!(!Utf8Path::new("foo.txt").is_absolute()); /// ``` /// /// [`has_root`]: Utf8Path::has_root pub fn is_absolute(&self) -> bool { self.0.is_absolute() } /// Returns `true` if the `Utf8Path` is relative, i.e., not absolute. /// /// See [`is_absolute`]'s documentation for more details. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert!(Utf8Path::new("foo.txt").is_relative()); /// ``` /// /// [`is_absolute`]: Utf8Path::is_absolute pub fn is_relative(&self) -> bool { self.0.is_relative() } /// Returns `true` if the `Utf8Path` has a root. /// /// * On Unix, a path has a root if it begins with `/`. /// /// * On Windows, a path has a root if it: /// * has no prefix and begins with a separator, e.g., `\windows` /// * has a prefix followed by a separator, e.g., `c:\windows` but not `c:windows` /// * has any non-disk prefix, e.g., `\\server\share` /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert!(Utf8Path::new("/etc/passwd").has_root()); /// ``` pub fn has_root(&self) -> bool { self.0.has_root() } /// Returns the `Path` without its final component, if there is one. /// /// Returns [`None`] if the path terminates in a root or prefix. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/foo/bar"); /// let parent = path.parent().unwrap(); /// assert_eq!(parent, Utf8Path::new("/foo")); /// /// let grand_parent = parent.parent().unwrap(); /// assert_eq!(grand_parent, Utf8Path::new("/")); /// assert_eq!(grand_parent.parent(), None); /// ``` pub fn parent(&self) -> Option<&Utf8Path> { self.0.parent().map(|path| { // SAFETY: self is valid UTF-8, so parent is valid UTF-8 as well unsafe { Utf8Path::assume_utf8(path) } }) } /// Produces an iterator over `Utf8Path` and its ancestors. /// /// The iterator will yield the `Utf8Path` that is returned if the [`parent`] method is used zero /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`, /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns /// [`None`], the iterator will do likewise. The iterator will always yield at least one value, /// namely `&self`. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let mut ancestors = Utf8Path::new("/foo/bar").ancestors(); /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo/bar"))); /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/foo"))); /// assert_eq!(ancestors.next(), Some(Utf8Path::new("/"))); /// assert_eq!(ancestors.next(), None); /// /// let mut ancestors = Utf8Path::new("../foo/bar").ancestors(); /// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo/bar"))); /// assert_eq!(ancestors.next(), Some(Utf8Path::new("../foo"))); /// assert_eq!(ancestors.next(), Some(Utf8Path::new(".."))); /// assert_eq!(ancestors.next(), Some(Utf8Path::new(""))); /// assert_eq!(ancestors.next(), None); /// ``` /// /// [`parent`]: Utf8Path::parent pub fn ancestors(&self) -> Utf8Ancestors<'_> { Utf8Ancestors(self.0.ancestors()) } /// Returns the final component of the `Utf8Path`, if there is one. /// /// If the path is a normal file, this is the file name. If it's the path of a directory, this /// is the directory name. /// /// Returns [`None`] if the path terminates in `..`. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert_eq!(Some("bin"), Utf8Path::new("/usr/bin/").file_name()); /// assert_eq!(Some("foo.txt"), Utf8Path::new("tmp/foo.txt").file_name()); /// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.").file_name()); /// assert_eq!(Some("foo.txt"), Utf8Path::new("foo.txt/.//").file_name()); /// assert_eq!(None, Utf8Path::new("foo.txt/..").file_name()); /// assert_eq!(None, Utf8Path::new("/").file_name()); /// ``` pub fn file_name(&self) -> Option<&str> { self.0.file_name().map(|s| { // SAFETY: self is valid UTF-8, so file_name is valid UTF-8 as well unsafe { assume_utf8(s) } }) } /// Returns a path that, when joined onto `base`, yields `self`. /// /// # Errors /// /// If `base` is not a prefix of `self` (i.e., [`starts_with`] /// returns `false`), returns [`Err`]. /// /// [`starts_with`]: Utf8Path::starts_with /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let path = Utf8Path::new("/test/haha/foo.txt"); /// /// assert_eq!(path.strip_prefix("/"), Ok(Utf8Path::new("test/haha/foo.txt"))); /// assert_eq!(path.strip_prefix("/test"), Ok(Utf8Path::new("haha/foo.txt"))); /// assert_eq!(path.strip_prefix("/test/"), Ok(Utf8Path::new("haha/foo.txt"))); /// assert_eq!(path.strip_prefix("/test/haha/foo.txt"), Ok(Utf8Path::new(""))); /// assert_eq!(path.strip_prefix("/test/haha/foo.txt/"), Ok(Utf8Path::new(""))); /// /// assert!(path.strip_prefix("test").is_err()); /// assert!(path.strip_prefix("/haha").is_err()); /// /// let prefix = Utf8PathBuf::from("/test/"); /// assert_eq!(path.strip_prefix(prefix), Ok(Utf8Path::new("haha/foo.txt"))); /// ``` pub fn strip_prefix(&self, base: impl AsRef) -> Result<&Utf8Path, StripPrefixError> { self.0.strip_prefix(base).map(|path| { // SAFETY: self is valid UTF-8, and strip_prefix returns a part of self (or an empty // string), so it is valid UTF-8 as well. unsafe { Utf8Path::assume_utf8(path) } }) } /// Determines whether `base` is a prefix of `self`. /// /// Only considers whole path components to match. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/etc/passwd"); /// /// assert!(path.starts_with("/etc")); /// assert!(path.starts_with("/etc/")); /// assert!(path.starts_with("/etc/passwd")); /// assert!(path.starts_with("/etc/passwd/")); // extra slash is okay /// assert!(path.starts_with("/etc/passwd///")); // multiple extra slashes are okay /// /// assert!(!path.starts_with("/e")); /// assert!(!path.starts_with("/etc/passwd.txt")); /// /// assert!(!Utf8Path::new("/etc/foo.rs").starts_with("/etc/foo")); /// ``` pub fn starts_with(&self, base: impl AsRef) -> bool { self.0.starts_with(base) } /// Determines whether `child` is a suffix of `self`. /// /// Only considers whole path components to match. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/etc/resolv.conf"); /// /// assert!(path.ends_with("resolv.conf")); /// assert!(path.ends_with("etc/resolv.conf")); /// assert!(path.ends_with("/etc/resolv.conf")); /// /// assert!(!path.ends_with("/resolv.conf")); /// assert!(!path.ends_with("conf")); // use .extension() instead /// ``` pub fn ends_with(&self, base: impl AsRef) -> bool { self.0.ends_with(base) } /// Extracts the stem (non-extension) portion of [`self.file_name`]. /// /// [`self.file_name`]: Utf8Path::file_name /// /// The stem is: /// /// * [`None`], if there is no file name; /// * The entire file name if there is no embedded `.`; /// * The entire file name if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name before the final `.` /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert_eq!("foo", Utf8Path::new("foo.rs").file_stem().unwrap()); /// assert_eq!("foo.tar", Utf8Path::new("foo.tar.gz").file_stem().unwrap()); /// ``` pub fn file_stem(&self) -> Option<&str> { self.0.file_stem().map(|s| { // SAFETY: self is valid UTF-8, so file_stem is valid UTF-8 as well unsafe { assume_utf8(s) } }) } /// Extracts the extension of [`self.file_name`], if possible. /// /// The extension is: /// /// * [`None`], if there is no file name; /// * [`None`], if there is no embedded `.`; /// * [`None`], if the file name begins with `.` and has no other `.`s within; /// * Otherwise, the portion of the file name after the final `.` /// /// [`self.file_name`]: Utf8Path::file_name /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// assert_eq!("rs", Utf8Path::new("foo.rs").extension().unwrap()); /// assert_eq!("gz", Utf8Path::new("foo.tar.gz").extension().unwrap()); /// ``` pub fn extension(&self) -> Option<&str> { self.0.extension().map(|s| { // SAFETY: self is valid UTF-8, so extension is valid UTF-8 as well unsafe { assume_utf8(s) } }) } /// Creates an owned [`Utf8PathBuf`] with `path` adjoined to `self`. /// /// See [`Utf8PathBuf::push`] for more details on what it means to adjoin a path. /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// assert_eq!(Utf8Path::new("/etc").join("passwd"), Utf8PathBuf::from("/etc/passwd")); /// ``` pub fn join(&self, path: impl AsRef) -> Utf8PathBuf { Utf8PathBuf(self.0.join(&path.as_ref().0)) } /// Creates an owned [`PathBuf`] with `path` adjoined to `self`. /// /// See [`PathBuf::push`] for more details on what it means to adjoin a path. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// use std::path::PathBuf; /// /// assert_eq!(Utf8Path::new("/etc").join_os("passwd"), PathBuf::from("/etc/passwd")); /// ``` pub fn join_os(&self, path: impl AsRef) -> PathBuf { self.0.join(path) } /// Creates an owned [`Utf8PathBuf`] like `self` but with the given file name. /// /// See [`Utf8PathBuf::set_file_name`] for more details. /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let path = Utf8Path::new("/tmp/foo.txt"); /// assert_eq!(path.with_file_name("bar.txt"), Utf8PathBuf::from("/tmp/bar.txt")); /// /// let path = Utf8Path::new("/tmp"); /// assert_eq!(path.with_file_name("var"), Utf8PathBuf::from("/var")); /// ``` pub fn with_file_name(&self, file_name: impl AsRef) -> Utf8PathBuf { Utf8PathBuf(self.0.with_file_name(file_name.as_ref())) } /// Creates an owned [`Utf8PathBuf`] like `self` but with the given extension. /// /// See [`Utf8PathBuf::set_extension`] for more details. /// /// # Examples /// /// ``` /// use camino::{Utf8Path, Utf8PathBuf}; /// /// let path = Utf8Path::new("foo.rs"); /// assert_eq!(path.with_extension("txt"), Utf8PathBuf::from("foo.txt")); /// /// let path = Utf8Path::new("foo.tar.gz"); /// assert_eq!(path.with_extension(""), Utf8PathBuf::from("foo.tar")); /// assert_eq!(path.with_extension("xz"), Utf8PathBuf::from("foo.tar.xz")); /// assert_eq!(path.with_extension("").with_extension("txt"), Utf8PathBuf::from("foo.txt")); /// ``` pub fn with_extension(&self, extension: impl AsRef) -> Utf8PathBuf { Utf8PathBuf(self.0.with_extension(extension.as_ref())) } /// Produces an iterator over the [`Utf8Component`]s of the path. /// /// When parsing the path, there is a small amount of normalization: /// /// * Repeated separators are ignored, so `a/b` and `a//b` both have /// `a` and `b` as components. /// /// * Occurrences of `.` are normalized away, except if they are at the /// beginning of the path. For example, `a/./b`, `a/b/`, `a/b/.` and /// `a/b` all have `a` and `b` as components, but `./a/b` starts with /// an additional [`CurDir`] component. /// /// * A trailing slash is normalized away, `/a/b` and `/a/b/` are equivalent. /// /// Note that no other normalization takes place; in particular, `a/c` /// and `a/b/../c` are distinct, to account for the possibility that `b` /// is a symbolic link (so its parent isn't `a`). /// /// # Examples /// /// ``` /// use camino::{Utf8Component, Utf8Path}; /// /// let mut components = Utf8Path::new("/tmp/foo.txt").components(); /// /// assert_eq!(components.next(), Some(Utf8Component::RootDir)); /// assert_eq!(components.next(), Some(Utf8Component::Normal("tmp"))); /// assert_eq!(components.next(), Some(Utf8Component::Normal("foo.txt"))); /// assert_eq!(components.next(), None) /// ``` /// /// [`CurDir`]: Utf8Component::CurDir pub fn components(&self) -> Utf8Components { Utf8Components(self.0.components()) } /// Produces an iterator over the path's components viewed as [`str`] /// slices. /// /// For more information about the particulars of how the path is separated /// into components, see [`components`]. /// /// [`components`]: Utf8Path::components /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let mut it = Utf8Path::new("/tmp/foo.txt").iter(); /// assert_eq!(it.next(), Some(std::path::MAIN_SEPARATOR.to_string().as_str())); /// assert_eq!(it.next(), Some("tmp")); /// assert_eq!(it.next(), Some("foo.txt")); /// assert_eq!(it.next(), None) /// ``` pub fn iter(&self) -> Iter<'_> { Iter { inner: self.components(), } } /// Queries the file system to get information about a file, directory, etc. /// /// This function will traverse symbolic links to query information about the /// destination file. /// /// This is an alias to [`fs::metadata`]. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/Minas/tirith"); /// let metadata = path.metadata().expect("metadata call failed"); /// println!("{:?}", metadata.file_type()); /// ``` pub fn metadata(&self) -> io::Result { self.0.metadata() } /// Queries the metadata about a file without following symlinks. /// /// This is an alias to [`fs::symlink_metadata`]. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/Minas/tirith"); /// let metadata = path.symlink_metadata().expect("symlink_metadata call failed"); /// println!("{:?}", metadata.file_type()); /// ``` pub fn symlink_metadata(&self) -> io::Result { self.0.symlink_metadata() } /// Returns the canonical, absolute form of the path with all intermediate /// components normalized and symbolic links resolved. /// /// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not /// be. /// /// This is an alias to [`fs::canonicalize`]. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// use std::path::PathBuf; /// /// let path = Utf8Path::new("/foo/test/../test/bar.rs"); /// assert_eq!(path.canonicalize().unwrap(), PathBuf::from("/foo/test/bar.rs")); /// ``` pub fn canonicalize(&self) -> io::Result { self.0.canonicalize() } /// Reads a symbolic link, returning the file that the link points to. /// /// This returns a [`PathBuf`] because even if a symlink is valid Unicode, its target may not /// be. /// /// This is an alias to [`fs::read_link`]. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/laputa/sky_castle.rs"); /// let path_link = path.read_link().expect("read_link call failed"); /// ``` pub fn read_link(&self) -> io::Result { self.0.read_link() } /// Returns an iterator over the entries within a directory. /// /// The iterator will yield instances of [`io::Result`]`<`[`fs::DirEntry`]`>`. New /// errors may be encountered after an iterator is initially constructed. /// /// This is an alias to [`fs::read_dir`]. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/laputa"); /// for entry in path.read_dir().expect("read_dir call failed") { /// if let Ok(entry) = entry { /// println!("{:?}", entry.path()); /// } /// } /// ``` pub fn read_dir(&self) -> io::Result { self.0.read_dir() } /// Returns `true` if the path points at an existing entity. /// /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// assert!(!Utf8Path::new("does_not_exist.txt").exists()); /// ``` /// /// # See Also /// /// This is a convenience function that coerces errors to false. If you want to /// check errors, call [`fs::metadata`]. pub fn exists(&self) -> bool { self.0.exists() } /// Returns `true` if the path exists on disk and is pointing at a regular file. /// /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// assert_eq!(Utf8Path::new("./is_a_directory/").is_file(), false); /// assert_eq!(Utf8Path::new("a_file.txt").is_file(), true); /// ``` /// /// # See Also /// /// This is a convenience function that coerces errors to false. If you want to /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call /// [`fs::Metadata::is_file`] if it was [`Ok`]. /// /// When the goal is simply to read from (or write to) the source, the most /// reliable way to test the source can be read (or written to) is to open /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on /// a Unix-like system for example. See [`fs::File::open`] or /// [`fs::OpenOptions::open`] for more information. pub fn is_file(&self) -> bool { self.0.is_file() } /// Returns `true` if the path exists on disk and is pointing at a directory. /// /// This function will traverse symbolic links to query information about the /// destination file. In case of broken symbolic links this will return `false`. /// /// If you cannot access the directory containing the file, e.g., because of a /// permission error, this will return `false`. /// /// # Examples /// /// ```no_run /// use camino::Utf8Path; /// assert_eq!(Utf8Path::new("./is_a_directory/").is_dir(), true); /// assert_eq!(Utf8Path::new("a_file.txt").is_dir(), false); /// ``` /// /// # See Also /// /// This is a convenience function that coerces errors to false. If you want to /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call /// [`fs::Metadata::is_dir`] if it was [`Ok`]. pub fn is_dir(&self) -> bool { self.0.is_dir() } /// Converts a `Box` into a [`Utf8PathBuf`] without copying or allocating. pub fn into_path_buf(self: Box) -> Utf8PathBuf { let ptr = Box::into_raw(self) as *mut Path; // SAFETY: // * self is valid UTF-8 // * ptr was constructed by consuming self so it represents an owned path. // * Utf8Path is marked as #[repr(transparent)] so the conversion from a *mut Utf8Path to a // *mut Path is valid. let boxed_path = unsafe { Box::from_raw(ptr) }; Utf8PathBuf(boxed_path.into_path_buf()) } // invariant: Path must be guaranteed to be utf-8 data unsafe fn assume_utf8(path: &Path) -> &Utf8Path { // SAFETY: Utf8Path is marked as #[repr(transparent)] so the conversion from a // *const Path to a *const Utf8Path is valid. &*(path as *const Path as *const Utf8Path) } } impl Clone for Box { fn clone(&self) -> Self { let boxed: Box = self.0.into(); let ptr = Box::into_raw(boxed) as *mut Utf8Path; // SAFETY: // * self is valid UTF-8 // * ptr was created by consuming a Box so it represents an rced pointer // * Utf8Path is marked as #[repr(transparent)] so the conversion from *mut Path to // *mut Utf8Path is valid unsafe { Box::from_raw(ptr) } } } impl fmt::Display for Utf8Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl fmt::Debug for Utf8Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_str(), f) } } /// An iterator over [`Utf8Path`] and its ancestors. /// /// This `struct` is created by the [`ancestors`] method on [`Utf8Path`]. /// See its documentation for more. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/foo/bar"); /// /// for ancestor in path.ancestors() { /// println!("{}", ancestor); /// } /// ``` /// /// [`ancestors`]: Utf8Path::ancestors #[derive(Copy, Clone)] #[repr(transparent)] pub struct Utf8Ancestors<'a>(Ancestors<'a>); impl<'a> fmt::Debug for Utf8Ancestors<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl<'a> Iterator for Utf8Ancestors<'a> { type Item = &'a Utf8Path; fn next(&mut self) -> Option { self.0.next().map(|path| { // SAFETY: Utf8Ancestors was constructed from a Utf8Path, so it is guaranteed to // be valid UTF-8 unsafe { Utf8Path::assume_utf8(path) } }) } } impl<'a> FusedIterator for Utf8Ancestors<'a> {} /// An iterator over the [`Utf8Component`]s of a [`Utf8Path`]. /// /// This `struct` is created by the [`components`] method on [`Utf8Path`]. /// See its documentation for more. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("/tmp/foo/bar.txt"); /// /// for component in path.components() { /// println!("{:?}", component); /// } /// ``` /// /// [`components`]: Utf8Path::components #[derive(Clone, Eq, Ord, PartialEq, PartialOrd)] pub struct Utf8Components<'a>(Components<'a>); impl<'a> Utf8Components<'a> { /// Extracts a slice corresponding to the portion of the path remaining for iteration. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let mut components = Utf8Path::new("/tmp/foo/bar.txt").components(); /// components.next(); /// components.next(); /// /// assert_eq!(Utf8Path::new("foo/bar.txt"), components.as_path()); /// ``` pub fn as_path(&self) -> &'a Utf8Path { // SAFETY: Utf8Components was constructed from a Utf8Path, so it is guaranteed to be valid // UTF-8 unsafe { Utf8Path::assume_utf8(self.0.as_path()) } } } impl<'a> Iterator for Utf8Components<'a> { type Item = Utf8Component<'a>; fn next(&mut self) -> Option { self.0.next().map(|component| { // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 unsafe { Utf8Component::new(component) } }) } } impl<'a> FusedIterator for Utf8Components<'a> {} impl<'a> DoubleEndedIterator for Utf8Components<'a> { fn next_back(&mut self) -> Option { self.0.next_back().map(|component| { // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 unsafe { Utf8Component::new(component) } }) } } impl<'a> fmt::Debug for Utf8Components<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl AsRef for Utf8Components<'_> { fn as_ref(&self) -> &Utf8Path { self.as_path() } } impl AsRef for Utf8Components<'_> { fn as_ref(&self) -> &Path { self.as_path().as_ref() } } impl AsRef for Utf8Components<'_> { fn as_ref(&self) -> &str { self.as_path().as_ref() } } impl AsRef for Utf8Components<'_> { fn as_ref(&self) -> &OsStr { self.as_path().as_os_str() } } /// An iterator over the [`Utf8Component`]s of a [`Utf8Path`], as [`str`] slices. /// /// This `struct` is created by the [`iter`] method on [`Utf8Path`]. /// See its documentation for more. /// /// [`iter`]: Utf8Path::iter #[derive(Clone)] pub struct Iter<'a> { inner: Utf8Components<'a>, } impl fmt::Debug for Iter<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { struct DebugHelper<'a>(&'a Utf8Path); impl fmt::Debug for DebugHelper<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_list().entries(self.0.iter()).finish() } } f.debug_tuple("Iter") .field(&DebugHelper(self.as_path())) .finish() } } impl<'a> Iter<'a> { /// Extracts a slice corresponding to the portion of the path remaining for iteration. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let mut iter = Utf8Path::new("/tmp/foo/bar.txt").iter(); /// iter.next(); /// iter.next(); /// /// assert_eq!(Utf8Path::new("foo/bar.txt"), iter.as_path()); /// ``` pub fn as_path(&self) -> &'a Utf8Path { self.inner.as_path() } } impl AsRef for Iter<'_> { fn as_ref(&self) -> &Utf8Path { self.as_path() } } impl AsRef for Iter<'_> { fn as_ref(&self) -> &Path { self.as_path().as_ref() } } impl AsRef for Iter<'_> { fn as_ref(&self) -> &str { self.as_path().as_ref() } } impl AsRef for Iter<'_> { fn as_ref(&self) -> &OsStr { self.as_path().as_os_str() } } impl<'a> Iterator for Iter<'a> { type Item = &'a str; fn next(&mut self) -> Option<&'a str> { self.inner.next().map(|component| component.as_str()) } } impl<'a> DoubleEndedIterator for Iter<'a> { fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back().map(|component| component.as_str()) } } impl FusedIterator for Iter<'_> {} /// A single component of a path. /// /// A `Utf8Component` roughly corresponds to a substring between path separators /// (`/` or `\`). /// /// This `enum` is created by iterating over [`Utf8Components`], which in turn is /// created by the [`components`](Utf8Path::components) method on [`Utf8Path`]. /// /// # Examples /// /// ```rust /// use camino::{Utf8Component, Utf8Path}; /// /// let path = Utf8Path::new("/tmp/foo/bar.txt"); /// let components = path.components().collect::>(); /// assert_eq!(&components, &[ /// Utf8Component::RootDir, /// Utf8Component::Normal("tmp"), /// Utf8Component::Normal("foo"), /// Utf8Component::Normal("bar.txt"), /// ]); /// ``` #[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] pub enum Utf8Component<'a> { /// A Windows path prefix, e.g., `C:` or `\\server\share`. /// /// There is a large variety of prefix types, see [`Utf8Prefix`]'s documentation /// for more. /// /// Does not occur on Unix. Prefix(Utf8PrefixComponent<'a>), /// The root directory component, appears after any prefix and before anything else. /// /// It represents a separator that designates that a path starts from root. RootDir, /// A reference to the current directory, i.e., `.`. CurDir, /// A reference to the parent directory, i.e., `..`. ParentDir, /// A normal component, e.g., `a` and `b` in `a/b`. /// /// This variant is the most common one, it represents references to files /// or directories. Normal(&'a str), } impl<'a> Utf8Component<'a> { unsafe fn new(component: Component<'a>) -> Utf8Component<'a> { match component { Component::Prefix(prefix) => Utf8Component::Prefix(Utf8PrefixComponent(prefix)), Component::RootDir => Utf8Component::RootDir, Component::CurDir => Utf8Component::CurDir, Component::ParentDir => Utf8Component::ParentDir, Component::Normal(s) => Utf8Component::Normal(assume_utf8(s)), } } /// Extracts the underlying [`str`] slice. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("./tmp/foo/bar.txt"); /// let components: Vec<_> = path.components().map(|comp| comp.as_str()).collect(); /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]); /// ``` pub fn as_str(&self) -> &'a str { // SAFETY: Utf8Component was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 unsafe { assume_utf8(self.as_os_str()) } } /// Extracts the underlying [`OsStr`] slice. /// /// # Examples /// /// ``` /// use camino::Utf8Path; /// /// let path = Utf8Path::new("./tmp/foo/bar.txt"); /// let components: Vec<_> = path.components().map(|comp| comp.as_os_str()).collect(); /// assert_eq!(&components, &[".", "tmp", "foo", "bar.txt"]); /// ``` pub fn as_os_str(&self) -> &'a OsStr { match *self { Utf8Component::Prefix(prefix) => prefix.as_os_str(), Utf8Component::RootDir => Component::RootDir.as_os_str(), Utf8Component::CurDir => Component::CurDir.as_os_str(), Utf8Component::ParentDir => Component::ParentDir.as_os_str(), Utf8Component::Normal(s) => OsStr::new(s), } } } impl<'a> fmt::Debug for Utf8Component<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.as_os_str(), f) } } impl<'a> fmt::Display for Utf8Component<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } impl AsRef for Utf8Component<'_> { fn as_ref(&self) -> &Utf8Path { self.as_str().as_ref() } } impl AsRef for Utf8Component<'_> { fn as_ref(&self) -> &Path { self.as_os_str().as_ref() } } impl AsRef for Utf8Component<'_> { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef for Utf8Component<'_> { fn as_ref(&self) -> &OsStr { self.as_os_str() } } /// Windows path prefixes, e.g., `C:` or `\\server\share`. /// /// Windows uses a variety of path prefix styles, including references to drive /// volumes (like `C:`), network shared folders (like `\\server\share`), and /// others. In addition, some path prefixes are "verbatim" (i.e., prefixed with /// `\\?\`), in which case `/` is *not* treated as a separator and essentially /// no normalization is performed. /// /// # Examples /// /// ``` /// use camino::{Utf8Component, Utf8Path, Utf8Prefix}; /// use camino::Utf8Prefix::*; /// /// fn get_path_prefix(s: &str) -> Utf8Prefix { /// let path = Utf8Path::new(s); /// match path.components().next().unwrap() { /// Utf8Component::Prefix(prefix_component) => prefix_component.kind(), /// _ => panic!(), /// } /// } /// /// # if cfg!(windows) { /// assert_eq!(Verbatim("pictures"), get_path_prefix(r"\\?\pictures\kittens")); /// assert_eq!(VerbatimUNC("server", "share"), get_path_prefix(r"\\?\UNC\server\share")); /// assert_eq!(VerbatimDisk(b'C'), get_path_prefix(r"\\?\c:\")); /// assert_eq!(DeviceNS("BrainInterface"), get_path_prefix(r"\\.\BrainInterface")); /// assert_eq!(UNC("server", "share"), get_path_prefix(r"\\server\share")); /// assert_eq!(Disk(b'C'), get_path_prefix(r"C:\Users\Rust\Pictures\Ferris")); /// # } /// ``` #[derive(Copy, Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Utf8Prefix<'a> { /// Verbatim prefix, e.g., `\\?\cat_pics`. /// /// Verbatim prefixes consist of `\\?\` immediately followed by the given /// component. Verbatim(&'a str), /// Verbatim prefix using Windows' _**U**niform **N**aming **C**onvention_, /// e.g., `\\?\UNC\server\share`. /// /// Verbatim UNC prefixes consist of `\\?\UNC\` immediately followed by the /// server's hostname and a share name. VerbatimUNC(&'a str, &'a str), /// Verbatim disk prefix, e.g., `\\?\C:`. /// /// Verbatim disk prefixes consist of `\\?\` immediately followed by the /// drive letter and `:`. VerbatimDisk(u8), /// Device namespace prefix, e.g., `\\.\COM42`. /// /// Device namespace prefixes consist of `\\.\` immediately followed by the /// device name. DeviceNS(&'a str), /// Prefix using Windows' _**U**niform **N**aming **C**onvention_, e.g. /// `\\server\share`. /// /// UNC prefixes consist of the server's hostname and a share name. UNC(&'a str, &'a str), /// Prefix `C:` for the given disk drive. Disk(u8), } impl<'a> Utf8Prefix<'a> { /// Determines if the prefix is verbatim, i.e., begins with `\\?\`. /// /// # Examples /// /// ``` /// use camino::Utf8Prefix::*; /// /// assert!(Verbatim("pictures").is_verbatim()); /// assert!(VerbatimUNC("server", "share").is_verbatim()); /// assert!(VerbatimDisk(b'C').is_verbatim()); /// assert!(!DeviceNS("BrainInterface").is_verbatim()); /// assert!(!UNC("server", "share").is_verbatim()); /// assert!(!Disk(b'C').is_verbatim()); /// ``` pub fn is_verbatim(&self) -> bool { use Utf8Prefix::*; match self { Verbatim(_) | VerbatimDisk(_) | VerbatimUNC(..) => true, _ => false, } } } /// A structure wrapping a Windows path prefix as well as its unparsed string /// representation. /// /// In addition to the parsed [`Utf8Prefix`] information returned by [`kind`], /// `Utf8PrefixComponent` also holds the raw and unparsed [`str`] slice, /// returned by [`as_str`]. /// /// Instances of this `struct` can be obtained by matching against the /// [`Prefix` variant] on [`Utf8Component`]. /// /// Does not occur on Unix. /// /// # Examples /// /// ``` /// # if cfg!(windows) { /// use camino::{Utf8Component, Utf8Path, Utf8Prefix}; /// use std::ffi::OsStr; /// /// let path = Utf8Path::new(r"c:\you\later\"); /// match path.components().next().unwrap() { /// Utf8Component::Prefix(prefix_component) => { /// assert_eq!(Utf8Prefix::Disk(b'C'), prefix_component.kind()); /// assert_eq!("c:", prefix_component.as_str()); /// } /// _ => unreachable!(), /// } /// # } /// ``` /// /// [`as_str`]: Utf8PrefixComponent::as_str /// [`kind`]: Utf8PrefixComponent::kind /// [`Prefix` variant]: Utf8Component::Prefix #[repr(transparent)] #[derive(Clone, Copy, Eq, PartialEq, Hash, Ord, PartialOrd)] pub struct Utf8PrefixComponent<'a>(PrefixComponent<'a>); impl<'a> Utf8PrefixComponent<'a> { /// Returns the parsed prefix data. /// /// See [`Utf8Prefix`]'s documentation for more information on the different /// kinds of prefixes. pub fn kind(&self) -> Utf8Prefix<'a> { // SAFETY for all the below unsafe blocks: the path self was originally constructed from was // UTF-8 so any parts of it are valid UTF-8 match self.0.kind() { Prefix::Verbatim(prefix) => Utf8Prefix::Verbatim(unsafe { assume_utf8(prefix) }), Prefix::VerbatimUNC(server, share) => { let server = unsafe { assume_utf8(server) }; let share = unsafe { assume_utf8(share) }; Utf8Prefix::VerbatimUNC(server, share) } Prefix::VerbatimDisk(drive) => Utf8Prefix::VerbatimDisk(drive), Prefix::DeviceNS(prefix) => Utf8Prefix::DeviceNS(unsafe { assume_utf8(prefix) }), Prefix::UNC(server, share) => { let server = unsafe { assume_utf8(server) }; let share = unsafe { assume_utf8(share) }; Utf8Prefix::UNC(server, share) } Prefix::Disk(drive) => Utf8Prefix::Disk(drive), } } /// Returns the [`str`] slice for this prefix. pub fn as_str(&self) -> &'a str { // SAFETY: Utf8PrefixComponent was constructed from a Utf8Path, so it is guaranteed to be // valid UTF-8 unsafe { assume_utf8(self.as_os_str()) } } /// Returns the raw [`OsStr`] slice for this prefix. pub fn as_os_str(&self) -> &'a OsStr { self.0.as_os_str() } } impl<'a> fmt::Debug for Utf8PrefixComponent<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } } impl<'a> fmt::Display for Utf8PrefixComponent<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_str(), f) } } // --- impl From for Utf8PathBuf { fn from(string: String) -> Utf8PathBuf { Utf8PathBuf(string.into()) } } impl FromStr for Utf8PathBuf { type Err = Infallible; fn from_str(s: &str) -> Result { Ok(Utf8PathBuf(s.into())) } } // --- // From impls: borrowed -> borrowed // --- impl<'a> From<&'a str> for &'a Utf8Path { fn from(s: &'a str) -> &'a Utf8Path { Utf8Path::new(s) } } // --- // From impls: borrowed -> owned // --- impl> From<&T> for Utf8PathBuf { fn from(s: &T) -> Utf8PathBuf { Utf8PathBuf::from(s.as_ref().to_owned()) } } impl> From<&T> for Box { fn from(s: &T) -> Box { Utf8PathBuf::from(s).into_boxed_path() } } impl From<&'_ Utf8Path> for Arc { fn from(path: &Utf8Path) -> Arc { let arc: Arc = Arc::from(AsRef::::as_ref(path)); let ptr = Arc::into_raw(arc) as *const Utf8Path; // SAFETY: // * path is valid UTF-8 // * ptr was created by consuming an Arc so it represents an arced pointer // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to // *const Utf8Path is valid unsafe { Arc::from_raw(ptr) } } } impl From<&'_ Utf8Path> for Rc { fn from(path: &Utf8Path) -> Rc { let rc: Rc = Rc::from(AsRef::::as_ref(path)); let ptr = Rc::into_raw(rc) as *const Utf8Path; // SAFETY: // * path is valid UTF-8 // * ptr was created by consuming an Rc so it represents an rced pointer // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to // *const Utf8Path is valid unsafe { Rc::from_raw(ptr) } } } impl<'a> From<&'a Utf8Path> for Cow<'a, Utf8Path> { fn from(path: &'a Utf8Path) -> Cow<'a, Utf8Path> { Cow::Borrowed(path) } } impl From<&'_ Utf8Path> for Box { fn from(path: &Utf8Path) -> Box { AsRef::::as_ref(path).into() } } impl From<&'_ Utf8Path> for Arc { fn from(path: &Utf8Path) -> Arc { AsRef::::as_ref(path).into() } } impl From<&'_ Utf8Path> for Rc { fn from(path: &Utf8Path) -> Rc { AsRef::::as_ref(path).into() } } impl<'a> From<&'a Utf8Path> for Cow<'a, Path> { fn from(path: &'a Utf8Path) -> Cow<'a, Path> { Cow::Borrowed(path.as_ref()) } } // --- // From impls: owned -> owned // --- impl From> for Utf8PathBuf { fn from(path: Box) -> Utf8PathBuf { path.into_path_buf() } } impl From for Box { fn from(path: Utf8PathBuf) -> Box { path.into_boxed_path() } } impl<'a> From> for Utf8PathBuf { fn from(path: Cow<'a, Utf8Path>) -> Utf8PathBuf { path.into_owned() } } impl From for String { fn from(path: Utf8PathBuf) -> String { path.into_string() } } impl From for OsString { fn from(path: Utf8PathBuf) -> OsString { path.into_os_string() } } impl<'a> From for Cow<'a, Utf8Path> { fn from(path: Utf8PathBuf) -> Cow<'a, Utf8Path> { Cow::Owned(path) } } impl From for Arc { fn from(path: Utf8PathBuf) -> Arc { let arc: Arc = Arc::from(path.0); let ptr = Arc::into_raw(arc) as *const Utf8Path; // SAFETY: // * path is valid UTF-8 // * ptr was created by consuming an Arc so it represents an arced pointer // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to // *const Utf8Path is valid unsafe { Arc::from_raw(ptr) } } } impl From for Rc { fn from(path: Utf8PathBuf) -> Rc { let rc: Rc = Rc::from(path.0); let ptr = Rc::into_raw(rc) as *const Utf8Path; // SAFETY: // * path is valid UTF-8 // * ptr was created by consuming an Rc so it represents an rced pointer // * Utf8Path is marked as #[repr(transparent)] so the conversion from *const Path to // *const Utf8Path is valid unsafe { Rc::from_raw(ptr) } } } impl From for PathBuf { fn from(path: Utf8PathBuf) -> PathBuf { path.0 } } impl From for Box { fn from(path: Utf8PathBuf) -> Box { PathBuf::from(path).into_boxed_path() } } impl From for Arc { fn from(path: Utf8PathBuf) -> Arc { PathBuf::from(path).into() } } impl From for Rc { fn from(path: Utf8PathBuf) -> Rc { PathBuf::from(path).into() } } impl<'a> From for Cow<'a, Path> { fn from(path: Utf8PathBuf) -> Cow<'a, Path> { PathBuf::from(path).into() } } // --- // TryFrom impls // --- impl TryFrom for Utf8PathBuf { type Error = FromPathBufError; fn try_from(path: PathBuf) -> Result { Utf8PathBuf::from_path_buf(path).map_err(|path| FromPathBufError { path, error: FromPathError(()), }) } } impl<'a> TryFrom<&'a Path> for &'a Utf8Path { type Error = FromPathError; fn try_from(path: &'a Path) -> Result<&'a Utf8Path, Self::Error> { Utf8Path::from_path(path).ok_or(FromPathError(())) } } /// A possible error value while converting a [`PathBuf`] to a [`Utf8PathBuf`]. /// /// Produced by the `TryFrom` implementation for [`Utf8PathBuf`]. /// /// # Examples /// /// ``` /// use camino::{Utf8PathBuf, FromPathBufError}; /// use std::convert::{TryFrom, TryInto}; /// use std::ffi::OsStr; /// # #[cfg(unix)] /// use std::os::unix::ffi::OsStrExt; /// use std::path::PathBuf; /// /// let unicode_path = PathBuf::from("/valid/unicode"); /// let utf8_path_buf: Utf8PathBuf = unicode_path.try_into().expect("valid Unicode path succeeded"); /// /// // Paths on Unix can be non-UTF-8. /// # #[cfg(unix)] /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF"); /// # #[cfg(unix)] /// let non_unicode_path = PathBuf::from(non_unicode_str); /// # #[cfg(unix)] /// let err: FromPathBufError = Utf8PathBuf::try_from(non_unicode_path.clone()) /// .expect_err("non-Unicode path failed"); /// # #[cfg(unix)] /// assert_eq!(err.as_path(), &non_unicode_path); /// # #[cfg(unix)] /// assert_eq!(err.into_path_buf(), non_unicode_path); /// ``` #[derive(Clone, Debug, Eq, PartialEq)] pub struct FromPathBufError { path: PathBuf, error: FromPathError, } impl FromPathBufError { /// Returns the [`Path`] slice that was attempted to be converted to [`Utf8PathBuf`]. pub fn as_path(&self) -> &Path { &self.path } /// Returns the [`PathBuf`] that was attempted to be converted to [`Utf8PathBuf`]. pub fn into_path_buf(self) -> PathBuf { self.path } /// Fetch a [`FromPathError`] for more about the conversion failure. /// /// At the moment this struct does not contain any additional information, but is provided for /// completeness. pub fn from_path_error(&self) -> FromPathError { self.error } } impl fmt::Display for FromPathBufError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "PathBuf contains invalid UTF-8: {}", self.path.display()) } } impl error::Error for FromPathBufError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { Some(&self.error) } } /// A possible error value while converting a [`Path`] to a [`Utf8Path`]. /// /// Produced by the `TryFrom<&Path>` implementation for [`&Utf8Path`](Utf8Path). /// /// /// # Examples /// /// ``` /// use camino::{Utf8Path, FromPathError}; /// use std::convert::{TryFrom, TryInto}; /// use std::ffi::OsStr; /// # #[cfg(unix)] /// use std::os::unix::ffi::OsStrExt; /// use std::path::Path; /// /// let unicode_path = Path::new("/valid/unicode"); /// let utf8_path: &Utf8Path = unicode_path.try_into().expect("valid Unicode path succeeded"); /// /// // Paths on Unix can be non-UTF-8. /// # #[cfg(unix)] /// let non_unicode_str = OsStr::from_bytes(b"\xFF\xFF\xFF"); /// # #[cfg(unix)] /// let non_unicode_path = Path::new(non_unicode_str); /// # #[cfg(unix)] /// let err: FromPathError = <&Utf8Path>::try_from(non_unicode_path) /// .expect_err("non-Unicode path failed"); /// ``` #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct FromPathError(()); impl fmt::Display for FromPathError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Path contains invalid UTF-8") } } impl error::Error for FromPathError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { None } } // --- // AsRef impls // --- impl AsRef for Utf8Path { fn as_ref(&self) -> &Utf8Path { self } } impl AsRef for Utf8PathBuf { fn as_ref(&self) -> &Utf8Path { self.as_path() } } impl AsRef for str { fn as_ref(&self) -> &Utf8Path { Utf8Path::new(self) } } impl AsRef for String { fn as_ref(&self) -> &Utf8Path { Utf8Path::new(self) } } impl AsRef for Utf8Path { fn as_ref(&self) -> &Path { &self.0 } } impl AsRef for Utf8PathBuf { fn as_ref(&self) -> &Path { &*self.0 } } impl AsRef for Utf8Path { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef for Utf8PathBuf { fn as_ref(&self) -> &str { self.as_str() } } impl AsRef for Utf8Path { fn as_ref(&self) -> &OsStr { self.as_os_str() } } impl AsRef for Utf8PathBuf { fn as_ref(&self) -> &OsStr { self.as_os_str() } } // --- // Borrow and ToOwned // --- impl Borrow for Utf8PathBuf { fn borrow(&self) -> &Utf8Path { self.as_path() } } impl ToOwned for Utf8Path { type Owned = Utf8PathBuf; fn to_owned(&self) -> Utf8PathBuf { self.to_path_buf() } } impl> std::iter::FromIterator

for Utf8PathBuf { fn from_iter>(iter: I) -> Utf8PathBuf { let mut buf = Utf8PathBuf::new(); buf.extend(iter); buf } } // --- // [Partial]Eq, [Partial]Ord, Hash // --- impl PartialEq for Utf8PathBuf { fn eq(&self, other: &Utf8PathBuf) -> bool { self.components() == other.components() } } impl Eq for Utf8PathBuf {} impl Hash for Utf8PathBuf { fn hash(&self, state: &mut H) { self.as_path().hash(state) } } impl PartialOrd for Utf8PathBuf { fn partial_cmp(&self, other: &Utf8PathBuf) -> Option { self.components().partial_cmp(other.components()) } } impl Ord for Utf8PathBuf { fn cmp(&self, other: &Utf8PathBuf) -> Ordering { self.components().cmp(other.components()) } } impl PartialEq for Utf8Path { fn eq(&self, other: &Utf8Path) -> bool { self.components().eq(other.components()) } } impl Eq for Utf8Path {} impl Hash for Utf8Path { fn hash(&self, state: &mut H) { for component in self.components() { component.hash(state) } } } impl PartialOrd for Utf8Path { fn partial_cmp(&self, other: &Utf8Path) -> Option { self.components().partial_cmp(other.components()) } } impl Ord for Utf8Path { fn cmp(&self, other: &Utf8Path) -> Ordering { self.components().cmp(other.components()) } } impl<'a> IntoIterator for &'a Utf8PathBuf { type Item = &'a str; type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { self.iter() } } impl<'a> IntoIterator for &'a Utf8Path { type Item = &'a str; type IntoIter = Iter<'a>; fn into_iter(self) -> Iter<'a> { self.iter() } } macro_rules! impl_cmp { ($lhs:ty, $rhs: ty) => { impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { ::eq(self, other) } } impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { ::eq(self, other) } } impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { ::partial_cmp(self, other) } } impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { ::partial_cmp(self, other) } } }; } impl_cmp!(Utf8PathBuf, Utf8Path); impl_cmp!(Utf8PathBuf, &'a Utf8Path); impl_cmp!(Cow<'a, Utf8Path>, Utf8Path); impl_cmp!(Cow<'a, Utf8Path>, &'b Utf8Path); impl_cmp!(Cow<'a, Utf8Path>, Utf8PathBuf); macro_rules! impl_cmp_std_path { ($lhs:ty, $rhs: ty) => { impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { ::eq(self.as_ref(), other) } } impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { ::eq(self, other.as_ref()) } } impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { ::partial_cmp(self.as_ref(), other) } } impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { ::partial_cmp(self, other.as_ref()) } } }; } impl_cmp_std_path!(Utf8PathBuf, Path); impl_cmp_std_path!(Utf8PathBuf, &'a Path); impl_cmp_std_path!(Utf8PathBuf, Cow<'a, Path>); impl_cmp_std_path!(Utf8PathBuf, PathBuf); impl_cmp_std_path!(Utf8Path, Path); impl_cmp_std_path!(Utf8Path, &'a Path); impl_cmp_std_path!(Utf8Path, Cow<'a, Path>); impl_cmp_std_path!(Utf8Path, PathBuf); impl_cmp_std_path!(&'a Utf8Path, Path); impl_cmp_std_path!(&'a Utf8Path, Cow<'b, Path>); impl_cmp_std_path!(&'a Utf8Path, PathBuf); // NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117) macro_rules! impl_cmp_str { ($lhs:ty, $rhs: ty) => { impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { ::eq(self, Utf8Path::new(other)) } } impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { ::eq(Utf8Path::new(self), other) } } impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { ::partial_cmp(self, Utf8Path::new(other)) } } impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { ::partial_cmp(Utf8Path::new(self), other) } } }; } impl_cmp_str!(Utf8PathBuf, str); impl_cmp_str!(Utf8PathBuf, &'a str); impl_cmp_str!(Utf8PathBuf, Cow<'a, str>); impl_cmp_str!(Utf8PathBuf, String); impl_cmp_str!(Utf8Path, str); impl_cmp_str!(Utf8Path, &'a str); impl_cmp_str!(Utf8Path, Cow<'a, str>); impl_cmp_str!(Utf8Path, String); impl_cmp_str!(&'a Utf8Path, str); impl_cmp_str!(&'a Utf8Path, Cow<'b, str>); impl_cmp_str!(&'a Utf8Path, String); // NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117) macro_rules! impl_cmp_os_str { ($lhs:ty, $rhs: ty) => { impl<'a, 'b> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { ::eq(self.as_ref(), other.as_ref()) } } impl<'a, 'b> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { ::eq(self.as_ref(), other.as_ref()) } } impl<'a, 'b> PartialOrd<$rhs> for $lhs { #[inline] fn partial_cmp(&self, other: &$rhs) -> Option { ::partial_cmp(self.as_ref(), other.as_ref()) } } impl<'a, 'b> PartialOrd<$lhs> for $rhs { #[inline] fn partial_cmp(&self, other: &$lhs) -> Option { ::partial_cmp(self.as_ref(), other.as_ref()) } } }; } impl_cmp_os_str!(Utf8PathBuf, OsStr); impl_cmp_os_str!(Utf8PathBuf, &'a OsStr); impl_cmp_os_str!(Utf8PathBuf, Cow<'a, OsStr>); impl_cmp_os_str!(Utf8PathBuf, OsString); impl_cmp_os_str!(Utf8Path, OsStr); impl_cmp_os_str!(Utf8Path, &'a OsStr); impl_cmp_os_str!(Utf8Path, Cow<'a, OsStr>); impl_cmp_os_str!(Utf8Path, OsString); impl_cmp_os_str!(&'a Utf8Path, OsStr); impl_cmp_os_str!(&'a Utf8Path, Cow<'b, OsStr>); impl_cmp_os_str!(&'a Utf8Path, OsString); // NOTE: impls for Cow<'a, Utf8Path> cannot be defined because of the orphan rule (E0117) // invariant: OsStr must be guaranteed to be utf8 data unsafe fn assume_utf8(string: &OsStr) -> &str { &*(string as *const OsStr as *const str) } camino-1.0.5/src/serde_impls.rs000064400000000000000000000026630000000000000145240ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 //! Serde implementations for `Utf8Path`. //! //! The Serde implementations for `Utf8PathBuf` are derived, but `Utf8Path` is an unsized type which //! the derive impls can't handle. Implement these by hand. use crate::Utf8Path; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; use std::fmt; struct Utf8PathVisitor; impl<'a> de::Visitor<'a> for Utf8PathVisitor { type Value = &'a Utf8Path; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a borrowed path") } fn visit_borrowed_str(self, v: &'a str) -> Result where E: de::Error, { Ok(v.as_ref()) } fn visit_borrowed_bytes(self, v: &'a [u8]) -> Result where E: de::Error, { std::str::from_utf8(v) .map(AsRef::as_ref) .map_err(|_| de::Error::invalid_value(de::Unexpected::Bytes(v), &self)) } } impl<'de: 'a, 'a> Deserialize<'de> for &'a Utf8Path { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { deserializer.deserialize_str(Utf8PathVisitor) } } impl Serialize for Utf8Path { fn serialize(&self, serializer: S) -> Result where S: Serializer, { self.as_str().serialize(serializer) } } camino-1.0.5/src/tests.rs000064400000000000000000000021630000000000000133530ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 // Test that all required impls exist. use crate::{Utf8Path, Utf8PathBuf}; use std::{ borrow::Cow, path::{Path, PathBuf}, rc::Rc, sync::Arc, }; macro_rules! all_into { ($t:ty, $x:ident) => { test_into::<$t, Utf8PathBuf>($x.clone()); test_into::<$t, Box>($x.clone()); test_into::<$t, Arc>($x.clone()); test_into::<$t, Rc>($x.clone()); test_into::<$t, Cow<'_, Utf8Path>>($x.clone()); test_into::<$t, PathBuf>($x.clone()); test_into::<$t, Box>($x.clone()); test_into::<$t, Arc>($x.clone()); test_into::<$t, Rc>($x.clone()); test_into::<$t, Cow<'_, Path>>($x.clone()); }; } #[test] fn test_borrowed_into() { let utf8_path = Utf8Path::new("test/path"); all_into!(&Utf8Path, utf8_path); } #[test] fn test_owned_into() { let utf8_path_buf = Utf8PathBuf::from("test/path"); all_into!(Utf8PathBuf, utf8_path_buf); } fn test_into(orig: T) where T: Into, { orig.into(); } camino-1.0.5/tests/integration_tests.rs000064400000000000000000000055650000000000000163420ustar 00000000000000// Copyright (c) The camino Contributors // SPDX-License-Identifier: MIT OR Apache-2.0 use camino::{Utf8Path, Utf8PathBuf}; use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, path::Path, }; static PATH_CORPUS: &[&str] = &[ "", "foo", "foo/bar", "foo//bar", "foo/bar/baz", "foo/bar/./baz", "foo/bar/../baz", "../foo/bar/./../baz", "/foo", "/foo/bar", "/", "///", // --- // Windows-only paths // --- #[cfg(windows)] "foo\\bar", #[cfg(windows)] "\\foo\\bar", #[cfg(windows)] "C:\\foo", #[cfg(windows)] "C:foo\\bar", #[cfg(windows)] "C:\\foo\\..\\.\\bar", #[cfg(windows)] "\\\\server\\foo\\bar", #[cfg(windows)] "\\\\.\\C:\\foo\\bar.txt", ]; #[test] fn test_borrow_eq_ord() { // Utf8PathBuf implements Borrow so equality and ordering comparisons should // match. for (idx, &path1) in PATH_CORPUS.iter().enumerate() { for &path2 in &PATH_CORPUS[idx..] { let borrowed1 = Utf8Path::new(path1); let borrowed2 = Utf8Path::new(path2); let owned1 = Utf8PathBuf::from(path1); let owned2 = Utf8PathBuf::from(path2); assert_eq!( borrowed1 == borrowed2, owned1 == owned2, "Eq impls match: {} == {}", borrowed1, borrowed2 ); assert_eq!( borrowed1.cmp(borrowed2), owned1.cmp(&owned2), "Ord impls match: {} and {}", borrowed1, borrowed2 ); // Also check against std paths. let std1 = Path::new(path1); let std2 = Path::new(path2); assert_eq!( borrowed1, std1, "Eq between Path and Utf8Path: {}", borrowed1 ); assert_eq!( borrowed1 == borrowed2, std1 == std2, "Eq impl matches Path: {} == {}", borrowed1, borrowed2 ); assert_eq!( borrowed1.cmp(borrowed2), std1.cmp(std2), "Ord impl matches Path: {} and {}", borrowed1, borrowed2 ); } } } #[test] fn test_borrow_hash() { // Utf8PathBuf implements Borrow so hash comparisons should match. fn hash_output(x: impl Hash) -> u64 { let mut hasher = DefaultHasher::new(); x.hash(&mut hasher); hasher.finish() } for &path in PATH_CORPUS { let borrowed = Utf8Path::new(path); let owned = Utf8PathBuf::from(path); assert_eq!( hash_output(&owned), hash_output(borrowed), "consistent Hash: {}", borrowed ); } }