descape-3.0.0/.cargo_vcs_info.json0000644000000001360000000000100124400ustar { "git": { "sha1": "5828ebcf4cd4e8ffc8e014541634dfcd08eb734c" }, "path_in_vcs": "" }descape-3.0.0/.github/workflows/coverage.yml000064400000000000000000000023431046102023000171450ustar 00000000000000name: Coverage on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: coveralls: name: Coveralls GitHub Action runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Get toolchain uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: nightly override: true - name: Install grcov uses: SierraSoftworks/setup-grcov@v1 with: github-token: ${{ secrets.GITHUB_TOKEN }} version: latest - name: Run grcov env: PROJECT_NAME: "descape" RUSTFLAGS: "-Zprofile -Ccodegen-units=1 -Cinline-threshold=0 -Clink-dead-code -Coverflow-checks=off" CARGO_INCREMENTAL: 0 run: | cargo build --verbose cargo test --verbose zip -0 cov.zip $(find . -name "$PROJECT_NAME*.gc*" -print) grcov cov.zip -s . -t lcov --llvm --ignore-not-existing --ignore "/*" -o lcov.info - name: Push grcov results to Coveralls via GitHub Action uses: coverallsapp/github-action@v1.0.1 with: github-token: ${{ secrets.GITHUB_TOKEN }} path-to-lcov: "lcov.info" descape-3.0.0/.github/workflows/rust.yml000064400000000000000000000005001046102023000163400ustar 00000000000000name: Rust on: push: branches: [ "master" ] pull_request: branches: [ "master" ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Build run: cargo build --verbose - name: Run tests run: cargo test --verbose descape-3.0.0/.gitignore000064400000000000000000000000241046102023000132140ustar 00000000000000/target /Cargo.lockdescape-3.0.0/.idea/.gitignore000064400000000000000000000002601046102023000141760ustar 00000000000000# Default ignored files /shelf/ /workspace.xml # Editor-based HTTP Client requests /httpRequests/ # Datasource local storage ignored files /dataSources/ /dataSources.local.xml descape-3.0.0/.idea/descape.iml000064400000000000000000000007661046102023000143300ustar 00000000000000 descape-3.0.0/.idea/inspectionProfiles/Project_Default.xml000064400000000000000000000004271046102023000216660ustar 00000000000000 descape-3.0.0/.idea/modules.xml000064400000000000000000000004121046102023000143770ustar 00000000000000 descape-3.0.0/.idea/vcs.xml000064400000000000000000000002471046102023000135300ustar 00000000000000 descape-3.0.0/Cargo.lock0000644000000002270000000000100104140ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "descape" version = "3.0.0" descape-3.0.0/Cargo.toml0000644000000023020000000000100104330ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "descape" version = "3.0.0" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Adds a single extension trait for &str to unescape any backslashes." readme = "README.md" keywords = [ "zerocopy", "string", "escape", "strings", "unicode", ] categories = [ "no-std", "parsing", "value-formatting", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/balt-dev/descape" [package.metadata] msrv = "1.52.1" [package.metadata.docs.rs] rustdoc-args = [ "--cfg", "docsrs", ] [features] core_error = [] std = [] [lib] name = "descape" path = "src/lib.rs" [[test]] name = "test" path = "tests/test.rs" descape-3.0.0/Cargo.toml.orig000064400000000000000000000007711046102023000141240ustar 00000000000000[package] name = "descape" version = "3.0.0" edition = "2018" description = "Adds a single extension trait for &str to unescape any backslashes." license = "Apache-2.0 OR MIT" repository = "https://github.com/balt-dev/descape" keywords = ["zerocopy", "string", "escape", "strings", "unicode"] categories = ["no-std", "parsing", "value-formatting"] readme = "README.md" [package.metadata] msrv = "1.52.1" [features] std = [] core_error = [] [package.metadata.docs.rs] rustdoc-args = ["--cfg", "docsrs"] descape-3.0.0/LICENSE-APACHE000064400000000000000000000261351046102023000131630ustar 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. descape-3.0.0/LICENSE-MIT000064400000000000000000000020451046102023000126650ustar 00000000000000MIT License Copyright (c) 2024 Balt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. descape-3.0.0/README.md000064400000000000000000000104611046102023000125110ustar 00000000000000[![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/balt-dev/descape/.github%2Fworkflows%2Frust.yml?branch=master&style=flat&label=tests)](https://github.com/balt-dev/descape/actions/) [![Coverage](https://coveralls.io/repos/github/balt-dev/descape/badge.svg?branch=master)](https://coveralls.io/github/balt-dev/descape/) [![Documentation](https://docs.rs/descape/badge.svg)](https://docs.rs/descape) [![MSRV](https://img.shields.io/badge/MSRV-1.52.1-gold)](https://gist.github.com/alexheretic/d1e98d8433b602e57f5d0a9637927e0c) [![Repository](https://img.shields.io/badge/-GitHub-%23181717?style=flat&logo=github&labelColor=%23555555&color=%23181717)](https://github.com/balt-dev/descape) [![Latest version](https://img.shields.io/crates/v/descape.svg)](https://crates.io/crates/descape) [![License](https://img.shields.io/crates/l/descape.svg)](https://github.com/balt-dev/descape/blob/master/LICENSE-MIT) [![unsafe forbidden](https://img.shields.io/badge/unsafe-forbidden-success.svg)](https://github.com/rust-secure-code/safety-dance/) # descape Provides utilities for easily parsing escape sequences in a string, using `alloc::borrow::Cow` to only borrow when needed. This library supports many escape sequences: - `\\a` -> `\x07` - `\\b` -> `\x08` - `\\t` -> `\x09` - `\\n` -> `\x0A` - `\\v` -> `\x0B` - `\\f` -> `\x0C` - `\\r` -> `\x0D` - `\\e` -> `\x1B` - `\\'` -> `'` - `\\"` -> `"` - \\` -> ` - `\\\\` -> `\\` - `\\xNN` -> `\xNN` - `\\o` -> `\o`, for all octal digits `o` - `\\oo` -> `\oo`, for all octal digits `o` - `\\ooo` -> `\ooo`, for all octal digits `o` - `\\uXXXX` -> `\u{XXXX}` - `\\u{HEX}` -> `\u{HEX}` Along with this, you can define your own custom escape handlers! Custom escape handlers support multi-character escape results, skipping past escape sequences, and even custom escape prefixes! See `descape::EscapeHandler`. This crate supports `no-std`. Optionally, this crate has the `std` and `core_error` features, to allow the error type of an invalid escape to implement the `Error` trait. `std` uses `std::error::Error`, and `core_error` depends on `core::error::Error`, which is stable on Rust 1.82.0 or greater. ## Examples ### Parsing an escaped string ```rust let escaped = "Hello,\\nworld!".to_unescaped(); assert_eq!( escaped.unwrap(), Cow::Owned::<'_, str>("Hello,\nworld!".to_string()) ); ``` ### Not allocating for a string without escapes ```rust let no_escapes = "No escapes here!".to_unescaped(); assert_eq!( no_escapes.unwrap(), Cow::Borrowed("No escapes here!") ); ``` ### Erroring for invalid escapes ```rust // v invalid at index 7 let invalid_escape = r"Uh oh! \xJJ".to_unescaped(); assert_eq!( invalid_escape.unwrap_err().index, 7 ); ``` ## Permitting any escape, handing it back raw ```rust fn raw(idx: usize, chr: char, _: &mut CharIndices) -> Result, ()> { Ok(chr.into()) } let escaped = r"\H\e\l\l\o \n \W\o\r\l\d"; let unescaped = escaped.to_unescaped_with(raw).expect("this is fine"); assert_eq!(unescaped, "Hello n World"); ``` ## Removing escape sequences entirely ```rust fn raw(idx: usize, chr: char, _: &mut CharIndices) -> Result, ()> { Ok(EscapeValue::Remove) } let escaped = r"What if I want a \nnewline?"; let unescaped = escaped.to_unescaped_with(raw).expect("this should work"); assert_eq!(unescaped, "What if I want a newline?"); ``` ## Not allowing escape sequences unsupported by Rust ```rust fn rust_only(idx: usize, chr: char, iter: &mut CharIndices) -> Result, ()> { match chr { 'a' | 'b' | 'v' | 'f' | 'e' | '`' => Err(()), _ => descape::DefaultEscapeHandler.escape(idx, chr, iter) } } r"This is \nfine".to_unescaped_with(rust_only).expect(r"\n is valid"); r"This is not \fine".to_unescaped_with(rust_only).expect_err(r"\f is invalid"); ``` ## Custom escape prefixes ```rust struct PercentEscape; impl EscapeHandler for PercentEscape { fn prefix(&self) -> char { '%' }; fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result, ()> { descape::DefaultEscapeHandler.escape(idx, chr, iter) } } assert_eq!( r"Hello,%tworld!".to_unescaped_with(PercentEscape).unwrap(), "Hello,\tworld!" ) ``` descape-3.0.0/src/lib.rs000064400000000000000000000350411046102023000131360ustar 00000000000000#![no_std] #![forbid(unsafe_code)] #![warn(clippy::pedantic, clippy::perf, missing_docs, clippy::panic, clippy::cargo)] #![allow(clippy::type_complexity)] #![cfg_attr(docsrs, feature(doc_cfg))] /*! # descape Provides utilities for easily parsing escape sequences in a string via [`UnescapeExt`], using [`alloc::borrow::Cow`] to only borrow when needed. This library supports many escape sequences: - `\\a` -> `\x07` - `\\b` -> `\x08` - `\\t` -> `\x09` - `\\n` -> `\x0A` - `\\v` -> `\x0B` - `\\f` -> `\x0C` - `\\r` -> `\x0D` - `\\e` -> `\x1B` - `\\'` -> `'` - `\\"` -> `"` - \\` -> ` - `\\\\` -> `\\` - `\\xNN` -> `\xNN` - `\\o` -> `\o`, for all octal digits `o` - `\\oo` -> `\oo`, for all octal digits `o` - `\\ooo` -> `\ooo`, for all octal digits `o` - `\\uXXXX` -> `\u{XXXX}` - `\\u{HEX}` -> `\u{HEX}` Along with this, you can define your own custom escape handlers! See [`UnescapeExt::to_unescaped_with`] for more information on that. This crate supports `no-std`. Optionally, this crate has the `std` and `core_error` features, to allow the error type of an invalid escape to implement the `Error` trait. `std` uses `std::error::Error`, and `core_error` depends on `core::error::Error`, which is stable on Rust 1.82.0 or greater. */ #[cfg(any(feature = "std", docsrs))] extern crate std; #[cfg(any(feature = "std", docsrs))] use std::error::Error as ErrorTrait; #[cfg(all(feature = "core_error", not(feature = "std")))] use core::error::Error as ErrorTrait; extern crate alloc; use alloc::{ borrow::Cow, string::String, str::CharIndices }; #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default, Hash)] /// An error representing an invalid escape sequence in a string. pub struct InvalidEscape { /// The index of the invalid escape sequence. pub index: usize, } impl InvalidEscape { /// Constructs an invalid escape error from an index. #[must_use] pub const fn new(index: usize) -> Self { Self { index } } } impl core::fmt::Display for InvalidEscape { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "invalid escape sequence at index {}", self.index)?; Ok(()) } } #[cfg_attr(docsrs, doc(cfg(any(feature = "std", feature = "core_error"))))] #[cfg(any(feature = "std", feature = "core_error", docsrs))] impl ErrorTrait for InvalidEscape {} /// An enum defining all possible non-error returns for a macro. #[derive(Debug, Clone, PartialEq, Eq)] pub enum EscapeValue<'s> { /// Remove the escape sequence entirely. Remove, /// Leave the escape sequence as is. Skip, /// Replace the escape sequence with a single character. Character(char), /// Replace the escape sequence with a string of characters. String(Cow<'s, str>) } impl From for EscapeValue<'static> { fn from(value: char) -> Self { Self::Character(value) } } impl<'string> From<&'string str> for EscapeValue<'string> { fn from(value: &'string str) -> Self { Self::String(Cow::Borrowed(value)) } } impl<'string> From> for EscapeValue<'string> { fn from(value: Cow<'string, str>) -> Self { Self::String(value) } } impl<'string> From for EscapeValue<'string> { fn from(value: String) -> Self { Self::String(Cow::Owned(value)) } } /// A trait distinguishing an object as a handler for custom escape sequences. /// /// For convenience, this trait is **automatically implemented** for all implementors of `FnMut` with the correct signature. /// pub trait EscapeHandler { /// Definition of a custom escape handler. /// /// Custom escape handlers are called before parsing any escape sequences, /// and are given 3 arguments: /// - `idx`: The index of the current character (e.g. `Hello\nthere` gets `5`) /// - `chr`: The current character in the string (e.g. `\\n` gets `'n'`) /// - `iter`: A mutable reference to the underlying character iterator - /// use this to get the rest of the string via `CharIndices::as_str`, /// or get the next characters /// /// Handlers return a `Result, ()>`. /// Returning `Ok(Some(char))` replaces the sequence with the given character, /// returning `Ok(None)` removes the sequence entirely, /// and returning `Err` errors the unescaping at the index of the escape sequence. /// /// /// # Examples /// ## Permitting any escape, handing it back raw /// ```rust /// # use descape::*; use std::str::CharIndices; /// fn raw<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result, ()> { /// Ok(chr.into()) /// } /// let escaped = r"\H\e\l\l\o \n \W\o\r\l\d"; /// let unescaped = escaped.to_unescaped_with(raw).unwrap(); /// assert_eq!(unescaped, "Hello n World"); /// ``` /// ## Removing escape sequences entirely /// ```rust /// # use descape::*; use std::str::CharIndices; /// fn raw<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result, ()> { /// Ok(EscapeValue::Remove) /// } /// let escaped = r"What if I want a \nnewline?"; /// let unescaped = escaped.to_unescaped_with(raw).unwrap(); /// assert_eq!(unescaped, "What if I want a newline?"); /// ``` /// ## Replacing escape sequences with their character number /// ```rust /// # use descape::*; use std::str::CharIndices; /// fn charnum<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result, ()> { /// Ok(format!("[{:02X}]", chr as u32).into()) /// } /// let escaped = r"Well this\Ais a\Zthing."; /// let unescaped = escaped.to_unescaped_with(charnum).unwrap(); /// assert_eq!(unescaped, "Well this[41]is a[5A]thing."); /// ``` /// ## Not allowing escape sequences unsupported by Rust /// ```rust /// # use descape::*; use std::str::CharIndices; /// fn rust_only<'i, 's>(idx: usize, chr: char, iter: &'i mut CharIndices<'s>) -> Result, ()> { /// match chr { /// 'a' | 'b' | 'v' | 'f' | 'e' | '`' => Err(()), /// _ => descape::DefaultEscapeHandler.escape(idx, chr, iter) /// } /// } /// r"This is \nfine".to_unescaped_with(rust_only).expect(r"\n is valid"); /// r"This is not \fine".to_unescaped_with(rust_only).expect_err(r"\f is invalid"); /// ``` /// # An informal note /// Ideally, this trait would return `Result, Option>>`, but `Error` has only been in `core` /// since Rust version `1.82.0`. Using it would bump the MSRV by a tremendous amount, /// and as such it has been left out. #[allow(clippy::result_unit_err, clippy::missing_errors_doc)] fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result, ()>; /// The escape prefix to use for this handler. /// Defaults to `\\`. /// /// # Examples /// ```rust /// # use descape::*; use std::str::CharIndices; /// struct PercentEscape; /// impl EscapeHandler for PercentEscape { /// fn prefix(&self) -> char { '%' } /// fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result, ()> { /// descape::DefaultEscapeHandler.escape(idx, chr, iter) /// } /// } /// /// assert_eq!( /// r"Hello,%tworld!".to_unescaped_with(PercentEscape).unwrap(), /// "Hello,\tworld!" /// ) /// ``` fn prefix(&self) -> char { '\\' } } impl EscapeHandler for F where F: for<'iter, 'source> FnMut(usize, char, &'iter mut CharIndices<'source>) -> Result, ()> { fn escape<'iter, 'source>(&mut self, idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result, ()> { self(idx, chr, iter) } } mod sealed { pub trait Sealed {} impl Sealed for str {} } /// An extension trait for [`&str`](str) to allow parsing escape sequences in strings, only copying when needed. pub trait UnescapeExt: sealed::Sealed { /** Unescapes a string, returning an [`alloc::borrow::Cow`]. Will only allocate if the string has any escape sequences. Uses [`crate::DefaultHandler`]. # Errors Errors if there's an invalid escape sequence in the string. Passes back the byte index of the invalid character. */ fn to_unescaped(&self) -> Result, InvalidEscape>; /** Unescapes a string using a custom escape handler. See the documentation of [`crate::EscapeHandler`] for more details. # Errors Errors if there's an invalid escape sequence in the string. Passes back the byte index of the invalid character. */ fn to_unescaped_with( &self, callback: impl EscapeHandler ) -> Result, InvalidEscape>; } impl UnescapeExt for str { #[inline] fn to_unescaped(&'_ self) -> Result, InvalidEscape> { self.to_unescaped_with(DefaultEscapeHandler) } // Put this outside to prevent monomorphization bloat fn to_unescaped_with( &'_ self, mut callback: impl EscapeHandler ) -> Result, InvalidEscape> { to_unescaped_with_mono(self, &mut callback) } } fn to_unescaped_with_mono<'this, 'cb>( this: &'this str, callback: &'cb mut dyn EscapeHandler ) -> Result, InvalidEscape> { // Iterates over each character as a UTF-8 string slice let mut iter = this.char_indices(); let mut seen: &'this str = ""; let mut owned = None::; let prefix = callback.prefix(); while let Some((index, chr)) = iter.next() { if chr != prefix { if let Some(owned) = &mut owned { owned.push(chr); } else { seen = &this[..index + chr.len_utf8()]; } continue; } if let Some((i, chr)) = iter.next() { let res = callback.escape(index, chr, &mut iter) .map_err(|()| InvalidEscape { index })?; if res == EscapeValue::Skip && owned.is_none() { seen = &this[..i + chr.len_utf8()]; continue; } let owned = owned.get_or_insert_with(|| seen.into()); match res { EscapeValue::Character(c) => { owned.push(c); continue; }, EscapeValue::String(str) => { owned.push_str(&*str); continue; }, EscapeValue::Remove => { continue; }, EscapeValue::Skip => { owned.push(prefix); owned.push(chr); continue; } } } else { // No matches found return Err(InvalidEscape::new(index)); } } match owned { Some(string) => Ok(Cow::Owned(string)), None => Ok(Cow::Borrowed(this)), } } /// The default escape sequence handler. /// /// The following escapes are valid: /// - `\\a` -> `\x07` /// - `\\b` -> `\x08` /// - `\\t` -> `\x09` /// - `\\n` -> `\x0A` /// - `\\v` -> `\x0B` /// - `\\f` -> `\x0C` /// - `\\r` -> `\x0D` /// - `\\e` -> `\x1B` /// - `\\'` -> `'` /// - `\\"` -> `"` /// - \\` -> ` /// - `\\\\` -> `\\` /// - `\\xNN` -> `\xNN` /// - `\\o` -> `\o`, for all octal digits `o` /// - `\\oo` -> `\oo`, for all octal digits `o` /// - `\\ooo` -> `\ooo`, for all octal digits `o` /// - `\\uXXXX` -> `\u{XXXX}` /// - `\\u{HEX}` -> `\u{HEX}` /// pub struct DefaultEscapeHandler; impl EscapeHandler for DefaultEscapeHandler { fn escape<'iter, 'source>(&mut self, _idx: usize, chr: char, iter: &'iter mut CharIndices<'source>) -> Result, ()> { Ok( match chr { 'a' => '\x07'.into(), 'b' => '\x08'.into(), 't' => '\x09'.into(), 'n' => '\x0A'.into(), 'v' => '\x0B'.into(), 'f' => '\x0C'.into(), 'r' => '\x0D'.into(), 'e' => '\x1B'.into(), '`' => '`'.into(), '\'' => '\''.into(), '"' => '"'.into(), '\\' => '\\'.into(), 'u' => { let (chr, skip) = unescape_unicode(iter).ok_or(())?; // Skip the needed amount of characters for _ in 0..skip { iter.next(); } chr.into() }, 'x' => { // Skip two characters let res = unescape_hex(iter).ok_or(())?; iter.next(); iter.next(); res.into() }, c if c.is_digit(8) => { let (chr, skip) = unescape_oct(c, iter).ok_or(())?; for _ in 0..skip { iter.next(); } chr.into() }, _ => return Err(()), } ) } } fn unescape_unicode( iter: &mut CharIndices ) -> Option<(char, usize)> { let string = iter.as_str(); let (_, next) = iter.next()?; if next == '{' { // \u{HEX} let end = string[1 ..].find('}')?; let num = &string[1 ..= end]; let codepoint = u32::from_str_radix(num, 16).ok()?; char::from_u32(codepoint).map(|v| (v, end + 1)) } else { // \uNNNN // If any of these are non-ASCII, then it's already invalid, // so a direct slice is fine let next_four = string.get( ..4 )?; let codepoint = u32::from_str_radix(next_four, 16).ok()?; // Encode the u32 char::from_u32(codepoint).map(|v| (v, 3)) } } // FIXME: This could be factored out along with part of unescape_unicode into its own function. fn unescape_hex( iter: &mut CharIndices ) -> Option { // Must be \xNN let codepoint = iter.as_str() .get(..2) .and_then(|num| u32::from_str_radix(num, 16).ok())?; char::from_u32(codepoint) } #[allow(clippy::cast_possible_truncation)] // Can't actually happen fn unescape_oct( chr: char, iter: &mut CharIndices ) -> Option<(char, usize)> { // Could be \o, \oo, or \ooo let str = iter.as_str(); let end = iter.clone() // Cloning this is pretty cheap .take(2) .take_while(|(_, c)| c.is_digit(8)) .enumerate() .last() .map_or(0, |(idx, _)| idx + 1); let num = &str[ .. end]; // These are the characters _after_ the first let mut codepoint = if num.is_empty() { 0 } else { u32::from_str_radix(num, 8).ok()? }; // Add the first character at the top of the number codepoint += (chr as u32 - '0' as u32) * 8u32.pow(end as u32); char::from_u32(codepoint).map(|chr| (chr, end)) } descape-3.0.0/tests/test.rs000064400000000000000000000052721046102023000137250ustar 00000000000000use std::borrow::Cow; use std::str::CharIndices; use descape::*; macro_rules! ensure_err { ($($name: ident),+) => {$( assert_eq!($name.to_unescaped().map_err(|err| err.index), Err(0), "{} parsed successfully when invalid", stringify!($name)); )+}; } #[test] fn test_escapes() { static ESCAPED: &str = r#"\a \b \t \n \v❤️\f \r \e \' \" \` \\ \u{0} \u{21}❤️\u{433} \u{FFFD} \u0000 \u0021 \uFFFD \x7E \xFF \0 \11 \100"#; static UNESCAPED: &str = "\x07 \x08 \t \n \x0B❤️\x0C \x0D \x1B \' \" ` \\ \u{0} \u{21}❤️\u{433} \u{FFFD} \u{0000} \u{0021} \u{FFFD} \x7E \u{FF} \0 \t @"; static NO_ESCAPES: &str = "No escapes here!"; static BAD_ESCAPE: &str = r"\Z"; static CUT_ESCAPE: &str = r"\"; static BAD_UNICODE: &str = r"\u{This is definitely not hexadecimal}"; static EMPTY_UNICODE: &str = r"\u{}"; static CUT_UNICODE: &str = r"\u{03"; static BAD_HEX: &str = r"\xGG"; static CUT_HEX: &str = r"\xA"; static EMPTY_HEX: &str = r"\x"; static NON_UNICODE: &str = r"\u{D800}"; assert_eq!( ESCAPED.to_unescaped() .map_err(|err| &ESCAPED[..err.index]) .expect("should not reject legal escaped string"), Cow::Owned::<'_, str>(UNESCAPED.to_string()) ); assert_eq!( NO_ESCAPES.to_unescaped() .map_err(|err| &ESCAPED[..err.index]) .expect("should not reject legal escaped string"), Cow::Borrowed(NO_ESCAPES) ); ensure_err!( BAD_ESCAPE, CUT_ESCAPE, BAD_UNICODE, EMPTY_UNICODE, CUT_UNICODE, BAD_HEX, CUT_HEX, EMPTY_HEX, NON_UNICODE ); } fn custom_esc<'a>(_: usize, chr: char, iter: &mut CharIndices<'a>) -> Result, ()> { if chr == 'T' { let (_, next) = iter.next().ok_or(())?; return Ok((match next { 'a' => 'g', 'o' => 'p', _ => Err(())? }).into()); } Ok(EscapeValue::Remove) } #[test] fn test_customs() { r"Hello \T world".to_unescaped_with(custom_esc) .expect_err(r"custom escape should fail for \T"); r"Foo \Tg bar".to_unescaped_with(custom_esc) .expect_err(r"custom escape should fail for \Tg"); assert_eq!( r"Spam E\Tags".to_unescaped_with(custom_esc).expect(r"custom escape should succeed for \Ta"), Cow::<'static, str>::Owned(String::from("Spam Eggs")), "custom escape gave incorrect result" ); assert_eq!( r"Bee\To \n Boop".to_unescaped_with(custom_esc).expect(r"custom escape should succeed for \To"), Cow::<'static, str>::Owned(String::from("Beep Boop")), "custom escape gave incorrect result" ); }