utf8_iter-1.0.4/.cargo_vcs_info.json0000644000000001360000000000100127470ustar { "git": { "sha1": "6b604ea2365bd535fb66eb4bfe92a9e00e333090" }, "path_in_vcs": "" }utf8_iter-1.0.4/.gitignore000064400000000000000000000000241046102023000135230ustar 00000000000000/target /Cargo.lock utf8_iter-1.0.4/COPYRIGHT000064400000000000000000000033161046102023000130350ustar 00000000000000Copyright Mozilla Foundation Licensed under the Apache License (Version 2.0), or the MIT license, (the "Licenses") at your option. You may not use this file except in compliance with one of the Licenses. You may obtain copies of the Licenses at: https://www.apache.org/licenses/LICENSE-2.0 https://opensource.org/licenses/MIT Unless required by applicable law or agreed to in writing, software distributed under the Licenses is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licenses for the specific language governing permissions and limitations under the Licenses. -- Test code is dedicated to the Public Domain when so designated (see the individual files for PD/CC0-dedicated sections). -- The implementation for Utf8CharIndices was adapted from the CharIndices implementation of the Rust standard library at revision ab32548539ec38a939c1b58599249f3b54130026 (https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/library/core/src/str/iter.rs). Excerpt from https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/COPYRIGHT , which refers to https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/LICENSE-APACHE and https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/LICENSE-MIT : For full authorship information, see the version control history or https://thanks.rust-lang.org Except as otherwise noted (below and/or in individual files), Rust is licensed under the Apache License, Version 2.0 or or the MIT license or , at your option. utf8_iter-1.0.4/Cargo.toml0000644000000017530000000000100107530ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" name = "utf8_iter" version = "1.0.4" authors = ["Henri Sivonen "] description = "Iterator by char over potentially-invalid UTF-8 in &[u8]" homepage = "https://docs.rs/utf8_iter/" documentation = "https://docs.rs/utf8_iter/" readme = "README.md" keywords = [ "encoding", "UTF-8", "unicode", "iterator", ] categories = [ "text-processing", "encoding", "internationalization", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/hsivonen/utf8_iter" utf8_iter-1.0.4/Cargo.toml.orig000064400000000000000000000007661046102023000144370ustar 00000000000000[package] name = "utf8_iter" version = "1.0.4" edition = "2021" description = "Iterator by char over potentially-invalid UTF-8 in &[u8]" authors = ["Henri Sivonen "] license = "Apache-2.0 OR MIT" readme = "README.md" documentation = "https://docs.rs/utf8_iter/" homepage = "https://docs.rs/utf8_iter/" repository = "https://github.com/hsivonen/utf8_iter" keywords = ["encoding", "UTF-8", "unicode", "iterator"] categories = ["text-processing", "encoding", "internationalization"] utf8_iter-1.0.4/LICENSE-APACHE000064400000000000000000000261361046102023000134730ustar 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. utf8_iter-1.0.4/LICENSE-MIT000064400000000000000000000020351046102023000131730ustar 00000000000000Copyright Mozilla Foundation 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. utf8_iter-1.0.4/README.md000064400000000000000000000026411046102023000130210ustar 00000000000000# utf8_iter [![crates.io](https://img.shields.io/crates/v/utf8_iter.svg)](https://crates.io/crates/utf8_iter) [![docs.rs](https://docs.rs/utf8_iter/badge.svg)](https://docs.rs/utf8_iter/) utf8_iter provides iteration by `char` over potentially-invalid UTF-8 `&[u8]` such that UTF-8 errors are handled according to the WHATWG Encoding Standard. Iteration by `Result` is provided as an alternative that distinguishes UTF-8 errors from U+FFFD appearing in the input. An implementation of `char_indices()` analogous to the same-name method on `str` is also provided. Key parts of the code are copypaste from the UTF-8 to UTF-16 conversion code in `encoding_rs`, which was optimized for speed in the case of valid input. The implementation here uses the structure that was found to be fast in the `encoding_rs` context but the structure hasn't been benchmarked in this context. This is a `no_std` crate. ## Licensing TL;DR: `Apache-2.0 OR MIT` Please see the file named [COPYRIGHT](https://github.com/hsivonen/utf8_iter/blob/master/COPYRIGHT). ## Documentation Generated [API documentation](https://docs.rs/utf8_iter/) is available online. ## Release Notes ### 1.0.4 * Add iteration by `Result`. ### 1.0.3 * Fix an error in documentation. ### 1.0.2 * `char_indices()` implementation. ### 1.0.1 * `as_slice()` method. * Implement `DoubleEndedIterator` ### 1.0.0 The initial release. utf8_iter-1.0.4/src/indices.rs000064400000000000000000000071311046102023000143140ustar 00000000000000// The code in this file was adapted from the CharIndices implementation of // the Rust standard library at revision ab32548539ec38a939c1b58599249f3b54130026 // (https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/library/core/src/str/iter.rs). // // Excerpt from https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/COPYRIGHT , // which refers to // https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/LICENSE-APACHE // and // https://github.com/rust-lang/rust/blob/ab32548539ec38a939c1b58599249f3b54130026/LICENSE-MIT // : // // For full authorship information, see the version control history or // https://thanks.rust-lang.org // // Except as otherwise noted (below and/or in individual files), Rust is // licensed under the Apache License, Version 2.0 or // or the MIT license // or , at your option. use super::Utf8Chars; use core::iter::FusedIterator; /// An iterator over the [`char`]s and their positions. #[derive(Clone, Debug)] #[must_use = "iterators are lazy and do nothing unless consumed"] pub struct Utf8CharIndices<'a> { front_offset: usize, iter: Utf8Chars<'a>, } impl<'a> Iterator for Utf8CharIndices<'a> { type Item = (usize, char); #[inline] fn next(&mut self) -> Option<(usize, char)> { let pre_len = self.as_slice().len(); match self.iter.next() { None => None, Some(ch) => { let index = self.front_offset; let len = self.as_slice().len(); self.front_offset += pre_len - len; Some((index, ch)) } } } #[inline] fn count(self) -> usize { self.iter.count() } #[inline] fn size_hint(&self) -> (usize, Option) { self.iter.size_hint() } #[inline] fn last(mut self) -> Option<(usize, char)> { // No need to go through the entire string. self.next_back() } } impl<'a> DoubleEndedIterator for Utf8CharIndices<'a> { #[inline] fn next_back(&mut self) -> Option<(usize, char)> { self.iter.next_back().map(|ch| { let index = self.front_offset + self.as_slice().len(); (index, ch) }) } } impl FusedIterator for Utf8CharIndices<'_> {} impl<'a> Utf8CharIndices<'a> { #[inline(always)] /// Creates the iterator from a byte slice. pub fn new(bytes: &'a [u8]) -> Self { Utf8CharIndices::<'a> { front_offset: 0, iter: Utf8Chars::new(bytes), } } /// Views the underlying data as a subslice of the original data. /// /// This has the same lifetime as the original slice, and so the /// iterator can continue to be used while this exists. #[must_use] #[inline] pub fn as_slice(&self) -> &'a [u8] { self.iter.as_slice() } /// Returns the byte position of the next character, or the length /// of the underlying string if there are no more characters. /// /// # Examples /// /// ``` /// use utf8_iter::Utf8CharsEx; /// let mut chars = "a楽".as_bytes().char_indices(); /// /// assert_eq!(chars.offset(), 0); /// assert_eq!(chars.next(), Some((0, 'a'))); /// /// assert_eq!(chars.offset(), 1); /// assert_eq!(chars.next(), Some((1, '楽'))); /// /// assert_eq!(chars.offset(), 4); /// assert_eq!(chars.next(), None); /// ``` #[inline] #[must_use] pub fn offset(&self) -> usize { self.front_offset } } utf8_iter-1.0.4/src/lib.rs000064400000000000000000000254201046102023000134450ustar 00000000000000// Copyright Mozilla Foundation // // Licensed under the Apache License (Version 2.0), or the MIT license, // (the "Licenses") at your option. You may not use this file except in // compliance with one of the Licenses. You may obtain copies of the // Licenses at: // // https://www.apache.org/licenses/LICENSE-2.0 // https://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the Licenses is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the Licenses for the specific language governing permissions and // limitations under the Licenses. #![no_std] //! Provides iteration by `char` over `&[u8]` containing potentially-invalid //! UTF-8 such that errors are handled according to the [WHATWG Encoding //! Standard](https://encoding.spec.whatwg.org/#utf-8-decoder) (i.e. the same //! way as in `String::from_utf8_lossy`). //! //! The trait `Utf8CharsEx` provides the convenience method `chars()` on //! byte slices themselves instead of having to use the more verbose //! `Utf8Chars::new(slice)`. //! //! ```rust //! use utf8_iter::Utf8CharsEx; //! let data = b"\xFF\xC2\xE2\xE2\x98\xF0\xF0\x9F\xF0\x9F\x92\xE2\x98\x83"; //! let from_iter: String = data.chars().collect(); //! let from_std = String::from_utf8_lossy(data); //! assert_eq!(from_iter, from_std); //! ``` mod indices; mod report; pub use crate::indices::Utf8CharIndices; pub use crate::report::ErrorReportingUtf8Chars; pub use crate::report::Utf8CharsError; use core::iter::FusedIterator; #[repr(align(64))] // Align to cache lines struct Utf8Data { pub table: [u8; 384], } // This is generated code copied and pasted from utf_8.rs of encoding_rs. // Please don't edit by hand but instead regenerate as instructed in that // file. static UTF8_DATA: Utf8Data = Utf8Data { table: [ 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 84, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 148, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 164, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 252, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 16, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 32, 8, 8, 64, 8, 8, 8, 128, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, ], }; // End manually copypasted generated code. #[inline(always)] fn in_inclusive_range8(i: u8, start: u8, end: u8) -> bool { i.wrapping_sub(start) <= (end - start) } /// Iterator by `char` over `&[u8]` that contains /// potentially-invalid UTF-8. See the crate documentation. #[derive(Debug, Clone)] pub struct Utf8Chars<'a> { remaining: &'a [u8], } impl<'a> Utf8Chars<'a> { #[inline(always)] /// Creates the iterator from a byte slice. pub fn new(bytes: &'a [u8]) -> Self { Utf8Chars::<'a> { remaining: bytes } } /// Views the current remaining data in the iterator as a subslice /// of the original slice. #[inline(always)] pub fn as_slice(&self) -> &'a [u8] { self.remaining } #[inline(never)] fn next_fallback(&mut self) -> Option { if self.remaining.is_empty() { return None; } let first = self.remaining[0]; if first < 0x80 { self.remaining = &self.remaining[1..]; return Some(char::from(first)); } if !in_inclusive_range8(first, 0xC2, 0xF4) || self.remaining.len() == 1 { self.remaining = &self.remaining[1..]; return Some('\u{FFFD}'); } let second = self.remaining[1]; let (lower_bound, upper_bound) = match first { 0xE0 => (0xA0, 0xBF), 0xED => (0x80, 0x9F), 0xF0 => (0x90, 0xBF), 0xF4 => (0x80, 0x8F), _ => (0x80, 0xBF), }; if !in_inclusive_range8(second, lower_bound, upper_bound) { self.remaining = &self.remaining[1..]; return Some('\u{FFFD}'); } if first < 0xE0 { self.remaining = &self.remaining[2..]; let point = ((u32::from(first) & 0x1F) << 6) | (u32::from(second) & 0x3F); return Some(unsafe { char::from_u32_unchecked(point) }); } if self.remaining.len() == 2 { self.remaining = &self.remaining[2..]; return Some('\u{FFFD}'); } let third = self.remaining[2]; if !in_inclusive_range8(third, 0x80, 0xBF) { self.remaining = &self.remaining[2..]; return Some('\u{FFFD}'); } if first < 0xF0 { self.remaining = &self.remaining[3..]; let point = ((u32::from(first) & 0xF) << 12) | ((u32::from(second) & 0x3F) << 6) | (u32::from(third) & 0x3F); return Some(unsafe { char::from_u32_unchecked(point) }); } // At this point, we have a valid 3-byte prefix of a // four-byte sequence that has to be incomplete, because // otherwise `next()` would have succeeded. self.remaining = &self.remaining[3..]; Some('\u{FFFD}') } } impl<'a> Iterator for Utf8Chars<'a> { type Item = char; #[inline] fn next(&mut self) -> Option { // Not delegating directly to `ErrorReportingUtf8Chars` to avoid // an extra branch in the common case based on a cursory inspection // of generated code in a similar case. Be sure to inspect the // generated code as inlined into an actual usage site carefully // if attempting to consolidate the source code here. // This loop is only broken out of as goto forward #[allow(clippy::never_loop)] loop { if self.remaining.len() < 4 { break; } let first = self.remaining[0]; if first < 0x80 { self.remaining = &self.remaining[1..]; return Some(char::from(first)); } let second = self.remaining[1]; if in_inclusive_range8(first, 0xC2, 0xDF) { if !in_inclusive_range8(second, 0x80, 0xBF) { break; } let point = ((u32::from(first) & 0x1F) << 6) | (u32::from(second) & 0x3F); self.remaining = &self.remaining[2..]; return Some(unsafe { char::from_u32_unchecked(point) }); } // This table-based formulation was benchmark-based in encoding_rs, // but it hasn't been re-benchmarked in this iterator context. let third = self.remaining[2]; if first < 0xF0 { if ((UTF8_DATA.table[usize::from(second)] & UTF8_DATA.table[usize::from(first) + 0x80]) | (third >> 6)) != 2 { break; } let point = ((u32::from(first) & 0xF) << 12) | ((u32::from(second) & 0x3F) << 6) | (u32::from(third) & 0x3F); self.remaining = &self.remaining[3..]; return Some(unsafe { char::from_u32_unchecked(point) }); } let fourth = self.remaining[3]; if (u16::from( UTF8_DATA.table[usize::from(second)] & UTF8_DATA.table[usize::from(first) + 0x80], ) | u16::from(third >> 6) | (u16::from(fourth & 0xC0) << 2)) != 0x202 { break; } let point = ((u32::from(first) & 0x7) << 18) | ((u32::from(second) & 0x3F) << 12) | ((u32::from(third) & 0x3F) << 6) | (u32::from(fourth) & 0x3F); self.remaining = &self.remaining[4..]; return Some(unsafe { char::from_u32_unchecked(point) }); } self.next_fallback() } } impl<'a> DoubleEndedIterator for Utf8Chars<'a> { #[inline] fn next_back(&mut self) -> Option { if self.remaining.is_empty() { return None; } let mut attempt = 1; for b in self.remaining.iter().rev() { if b & 0xC0 != 0x80 { let (head, tail) = self.remaining.split_at(self.remaining.len() - attempt); let mut inner = Utf8Chars::new(tail); let candidate = inner.next(); if inner.as_slice().is_empty() { self.remaining = head; return candidate; } break; } if attempt == 4 { break; } attempt += 1; } self.remaining = &self.remaining[..self.remaining.len() - 1]; Some('\u{FFFD}') } } impl FusedIterator for Utf8Chars<'_> {} /// Convenience trait that adds `chars()` and `char_indices()` methods /// similar to the ones on string slices to byte slices. pub trait Utf8CharsEx { fn chars(&self) -> Utf8Chars<'_>; fn char_indices(&self) -> Utf8CharIndices<'_>; } impl Utf8CharsEx for [u8] { /// Convenience method for creating an UTF-8 iterator /// for the slice. #[inline] fn chars(&self) -> Utf8Chars<'_> { Utf8Chars::new(self) } /// Convenience method for creating a byte index and /// UTF-8 iterator for the slice. #[inline] fn char_indices(&self) -> Utf8CharIndices<'_> { Utf8CharIndices::new(self) } } // No manually-written tests for forward-iteration, because the code passed multiple // days of fuzzing comparing with known-good behavior. utf8_iter-1.0.4/src/report.rs000064400000000000000000000204731046102023000142150ustar 00000000000000// Copyright Mozilla Foundation // // Licensed under the Apache License (Version 2.0), or the MIT license, // (the "Licenses") at your option. You may not use this file except in // compliance with one of the Licenses. You may obtain copies of the // Licenses at: // // https://www.apache.org/licenses/LICENSE-2.0 // https://opensource.org/licenses/MIT // // Unless required by applicable law or agreed to in writing, software // distributed under the Licenses is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the Licenses for the specific language governing permissions and // limitations under the Licenses. use crate::in_inclusive_range8; use crate::UTF8_DATA; use core::fmt::Formatter; use core::iter::FusedIterator; /// A type for signaling UTF-8 errors. /// /// Note: `core::error::Error` is not implemented due to implementing it /// being an [unstable feature][1] at the time of writing. /// /// [1]: https://github.com/rust-lang/rust/issues/103765 #[derive(Debug, PartialEq)] #[non_exhaustive] pub struct Utf8CharsError; impl core::fmt::Display for Utf8CharsError { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), core::fmt::Error> { write!(f, "byte sequence not well-formed UTF-8") } } /// Iterator by `Result` over `&[u8]` that contains /// potentially-invalid UTF-8. There is exactly one `Utf8CharsError` per /// each error as defined by the WHATWG Encoding Standard. /// /// ``` /// let s = b"a\xFFb\xFF\x80c\xF0\x9F\xA4\xA6\xF0\x9F\xA4\xF0\x9F\xF0d"; /// let plain = utf8_iter::Utf8Chars::new(s); /// let reporting = utf8_iter::ErrorReportingUtf8Chars::new(s); /// assert!(plain.eq(reporting.map(|r| r.unwrap_or('\u{FFFD}')))); /// ``` #[derive(Debug, Clone)] pub struct ErrorReportingUtf8Chars<'a> { remaining: &'a [u8], } impl<'a> ErrorReportingUtf8Chars<'a> { #[inline(always)] /// Creates the iterator from a byte slice. pub fn new(bytes: &'a [u8]) -> Self { ErrorReportingUtf8Chars::<'a> { remaining: bytes } } /// Views the current remaining data in the iterator as a subslice /// of the original slice. #[inline(always)] pub fn as_slice(&self) -> &'a [u8] { self.remaining } #[inline(never)] fn next_fallback(&mut self) -> Option> { if self.remaining.is_empty() { return None; } let first = self.remaining[0]; if first < 0x80 { self.remaining = &self.remaining[1..]; return Some(Ok(char::from(first))); } if !in_inclusive_range8(first, 0xC2, 0xF4) || self.remaining.len() == 1 { self.remaining = &self.remaining[1..]; return Some(Err(Utf8CharsError)); } let second = self.remaining[1]; let (lower_bound, upper_bound) = match first { 0xE0 => (0xA0, 0xBF), 0xED => (0x80, 0x9F), 0xF0 => (0x90, 0xBF), 0xF4 => (0x80, 0x8F), _ => (0x80, 0xBF), }; if !in_inclusive_range8(second, lower_bound, upper_bound) { self.remaining = &self.remaining[1..]; return Some(Err(Utf8CharsError)); } if first < 0xE0 { self.remaining = &self.remaining[2..]; let point = ((u32::from(first) & 0x1F) << 6) | (u32::from(second) & 0x3F); return Some(Ok(unsafe { char::from_u32_unchecked(point) })); } if self.remaining.len() == 2 { self.remaining = &self.remaining[2..]; return Some(Err(Utf8CharsError)); } let third = self.remaining[2]; if !in_inclusive_range8(third, 0x80, 0xBF) { self.remaining = &self.remaining[2..]; return Some(Err(Utf8CharsError)); } if first < 0xF0 { self.remaining = &self.remaining[3..]; let point = ((u32::from(first) & 0xF) << 12) | ((u32::from(second) & 0x3F) << 6) | (u32::from(third) & 0x3F); return Some(Ok(unsafe { char::from_u32_unchecked(point) })); } // At this point, we have a valid 3-byte prefix of a // four-byte sequence that has to be incomplete, because // otherwise `next()` would have succeeded. self.remaining = &self.remaining[3..]; Some(Err(Utf8CharsError)) } } impl<'a> Iterator for ErrorReportingUtf8Chars<'a> { type Item = Result; #[inline] fn next(&mut self) -> Option> { // This loop is only broken out of as goto forward #[allow(clippy::never_loop)] loop { if self.remaining.len() < 4 { break; } let first = self.remaining[0]; if first < 0x80 { self.remaining = &self.remaining[1..]; return Some(Ok(char::from(first))); } let second = self.remaining[1]; if in_inclusive_range8(first, 0xC2, 0xDF) { if !in_inclusive_range8(second, 0x80, 0xBF) { break; } let point = ((u32::from(first) & 0x1F) << 6) | (u32::from(second) & 0x3F); self.remaining = &self.remaining[2..]; return Some(Ok(unsafe { char::from_u32_unchecked(point) })); } // This table-based formulation was benchmark-based in encoding_rs, // but it hasn't been re-benchmarked in this iterator context. let third = self.remaining[2]; if first < 0xF0 { if ((UTF8_DATA.table[usize::from(second)] & UTF8_DATA.table[usize::from(first) + 0x80]) | (third >> 6)) != 2 { break; } let point = ((u32::from(first) & 0xF) << 12) | ((u32::from(second) & 0x3F) << 6) | (u32::from(third) & 0x3F); self.remaining = &self.remaining[3..]; return Some(Ok(unsafe { char::from_u32_unchecked(point) })); } let fourth = self.remaining[3]; if (u16::from( UTF8_DATA.table[usize::from(second)] & UTF8_DATA.table[usize::from(first) + 0x80], ) | u16::from(third >> 6) | (u16::from(fourth & 0xC0) << 2)) != 0x202 { break; } let point = ((u32::from(first) & 0x7) << 18) | ((u32::from(second) & 0x3F) << 12) | ((u32::from(third) & 0x3F) << 6) | (u32::from(fourth) & 0x3F); self.remaining = &self.remaining[4..]; return Some(Ok(unsafe { char::from_u32_unchecked(point) })); } self.next_fallback() } } impl<'a> DoubleEndedIterator for ErrorReportingUtf8Chars<'a> { #[inline] fn next_back(&mut self) -> Option> { if self.remaining.is_empty() { return None; } let mut attempt = 1; for b in self.remaining.iter().rev() { if b & 0xC0 != 0x80 { let (head, tail) = self.remaining.split_at(self.remaining.len() - attempt); let mut inner = ErrorReportingUtf8Chars::new(tail); let candidate = inner.next(); if inner.as_slice().is_empty() { self.remaining = head; return candidate; } break; } if attempt == 4 { break; } attempt += 1; } self.remaining = &self.remaining[..self.remaining.len() - 1]; Some(Err(Utf8CharsError)) } } impl FusedIterator for ErrorReportingUtf8Chars<'_> {} #[cfg(test)] mod tests { use crate::ErrorReportingUtf8Chars; // Should be a static assert, but not taking a dependency for this. #[test] fn test_size() { assert_eq!( core::mem::size_of:: as Iterator>::Item>>(), core::mem::size_of::>() ); } #[test] fn test_eq() { let a: as Iterator>::Item = Ok('a'); let a_again: as Iterator>::Item = Ok('a'); assert_eq!(a, a_again); } }