diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-19 00:47:55 +0000 |
commit | 26a029d407be480d791972afb5975cf62c9360a6 (patch) | |
tree | f435a8308119effd964b339f76abb83a57c29483 /third_party/rust/utf8_iter | |
parent | Initial commit. (diff) | |
download | firefox-26a029d407be480d791972afb5975cf62c9360a6.tar.xz firefox-26a029d407be480d791972afb5975cf62c9360a6.zip |
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/utf8_iter')
-rw-r--r-- | third_party/rust/utf8_iter/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/COPYRIGHT | 42 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/Cargo.toml | 34 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/LICENSE-APACHE | 202 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/LICENSE-MIT | 25 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/README.md | 46 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/src/indices.rs | 120 | ||||
-rw-r--r-- | third_party/rust/utf8_iter/src/lib.rs | 273 |
8 files changed, 743 insertions, 0 deletions
diff --git a/third_party/rust/utf8_iter/.cargo-checksum.json b/third_party/rust/utf8_iter/.cargo-checksum.json new file mode 100644 index 0000000000..c82c22f3e7 --- /dev/null +++ b/third_party/rust/utf8_iter/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"COPYRIGHT":"c30152c94a6d75e021adbc52b3a52470366a46edb917e17deae3259251af244c","Cargo.toml":"7da67fd58b8f357a045af06383ca245de59e8221a56abc34406fb6ed6e1cc43a","LICENSE-APACHE":"cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30","LICENSE-MIT":"3fa4ca83dcc9237839b1bdeb2e6d16bdfb5ec0c5ce42b24694d8bbf0dcbef72c","README.md":"6acce7a548969e2ef506f385a81ec6d648fdda145e7a035247a4d438e0372b44","src/indices.rs":"b01fbaac3c9a09be130cac57066a980362a1290fac2fe0f27f6238818235f94c","src/lib.rs":"4a5510ee6c8f7c3fbf55d7a26d799b78e766b2ecc170c1d2e55d093b89b45040"},"package":"64a8922555b9500e3d865caed19330172cd67cbf82203f1a3311d8c305cc9f33"}
\ No newline at end of file diff --git a/third_party/rust/utf8_iter/COPYRIGHT b/third_party/rust/utf8_iter/COPYRIGHT new file mode 100644 index 0000000000..b5e9457404 --- /dev/null +++ b/third_party/rust/utf8_iter/COPYRIGHT @@ -0,0 +1,42 @@ +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. + +-- + +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 <LICENSE-APACHE> or +<http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +<LICENSE-MIT> or <http://opensource.org/licenses/MIT>, at your option. diff --git a/third_party/rust/utf8_iter/Cargo.toml b/third_party/rust/utf8_iter/Cargo.toml new file mode 100644 index 0000000000..6e89caa036 --- /dev/null +++ b/third_party/rust/utf8_iter/Cargo.toml @@ -0,0 +1,34 @@ +# 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.3" +authors = ["Henri Sivonen <hsivonen@hsivonen.fi>"] +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" +resolver = "2" diff --git a/third_party/rust/utf8_iter/LICENSE-APACHE b/third_party/rust/utf8_iter/LICENSE-APACHE new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/third_party/rust/utf8_iter/LICENSE-APACHE @@ -0,0 +1,202 @@ + + 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. diff --git a/third_party/rust/utf8_iter/LICENSE-MIT b/third_party/rust/utf8_iter/LICENSE-MIT new file mode 100644 index 0000000000..3317c82e2f --- /dev/null +++ b/third_party/rust/utf8_iter/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright 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. diff --git a/third_party/rust/utf8_iter/README.md b/third_party/rust/utf8_iter/README.md new file mode 100644 index 0000000000..c6290861ae --- /dev/null +++ b/third_party/rust/utf8_iter/README.md @@ -0,0 +1,46 @@ +# 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. + +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.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. diff --git a/third_party/rust/utf8_iter/src/indices.rs b/third_party/rust/utf8_iter/src/indices.rs new file mode 100644 index 0000000000..1646f8b8dc --- /dev/null +++ b/third_party/rust/utf8_iter/src/indices.rs @@ -0,0 +1,120 @@ +// 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 <LICENSE-APACHE> or +// <http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT> or <http://opensource.org/licenses/MIT>, 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<usize>) { + 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 + } +} diff --git a/third_party/rust/utf8_iter/src/lib.rs b/third_party/rust/utf8_iter/src/lib.rs new file mode 100644 index 0000000000..bea1ce029b --- /dev/null +++ b/third_party/rust/utf8_iter/src/lib.rs @@ -0,0 +1,273 @@ +// 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; + +pub use crate::indices::Utf8CharIndices; +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<char> { + 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<char> { + // 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<char> { + 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. |