unscanny-0.1.0/.cargo_vcs_info.json0000644000000001360000000000100126700ustar { "git": { "sha1": "168fa7a05fe2931f86a788e26d7bfb67185767b5" }, "path_in_vcs": "" }unscanny-0.1.0/.github/workflows/rust.yml000064400000000000000000000005360072674642500166310ustar 00000000000000name: Continuous integration on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: ci: runs-on: ubuntu-latest strategy: matrix: rust: [stable] steps: - name: Checkout source code uses: actions/checkout@v2 - name: Build run: cargo build - name: Test run: cargo test unscanny-0.1.0/.gitignore000064400000000000000000000000610072674642500134750ustar 00000000000000/target Cargo.lock .vscode .DS_Store desktop.ini unscanny-0.1.0/Cargo.toml0000644000000015040000000000100106660ustar # 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 = "unscanny" version = "0.1.0" authors = ["Laurenz "] description = "Painless string scanning." readme = "README.md" keywords = [ "scanning", "tokenizing", ] categories = [ "parsing", "text-processing", ] license = "MIT OR Apache-2.0" repository = "https://github.com/typst/unscanny" resolver = "2" unscanny-0.1.0/Cargo.toml.orig000064400000000000000000000005140072674642500143770ustar 00000000000000[package] name = "unscanny" version = "0.1.0" authors = ["Laurenz "] edition = "2021" description = "Painless string scanning." repository = "https://github.com/typst/unscanny" readme = "README.md" license = "MIT OR Apache-2.0" categories = ["parsing", "text-processing"] keywords = ["scanning", "tokenizing"] unscanny-0.1.0/LICENSE-APACHE000064400000000000000000000227730072674642500134470ustar 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 unscanny-0.1.0/LICENSE-MIT000064400000000000000000000020140072674642500131410ustar 00000000000000MIT License 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. unscanny-0.1.0/README.md000064400000000000000000000030750072674642500127740ustar 00000000000000# unscanny [![Crates.io](https://img.shields.io/crates/v/unscanny.svg)](https://crates.io/crates/unscanny) [![Documentation](https://docs.rs/unscanny/badge.svg)](https://docs.rs/unscanny) Painless string scanning. ```toml [dependencies] unscanny = "0.1" ``` Basically, you'll want to use this crate if it's too much pain to solve your problem with a bare `chars()` iterator. Speaking more broadly, `unscanny` is useful in these situations: - You need to parse simple flat grammars (dates, times, custom stuff, ...) and want an interface that's a bit more convenient to use than a simple char iterator. - You're hand-writing a tokenizer. The `Scanner` keeps an internal cursor, allows you to peek around it, advance it beyond chars or other patterns and easily slice substrings before and after the cursor. # Example Recognizing and parsing a simple comma separated list of floats. ```rust let mut s = Scanner::new(" +12 , -15.3, 14.3 "); let mut nums = vec![]; while !s.done() { s.eat_whitespace(); let start = s.cursor(); s.eat_if(['+', '-']); s.eat_while(char::is_ascii_digit); s.eat_if('.'); s.eat_while(char::is_ascii_digit); nums.push(s.from(start).parse::().unwrap()); s.eat_whitespace(); s.eat_if(','); } assert_eq!(nums, [12.0, -15.3, 14.3]); ``` ## Safety This crate internally uses unsafe code for better performance. However, all unsafe code is documented with justification why its safe, all accesses are checked in debug mode and everything is tested. ## License This crate is dual-licensed under the MIT and Apache 2.0 licenses. unscanny-0.1.0/rustfmt.toml000064400000000000000000000003450072674642500141130ustar 00000000000000unstable_features = true overflow_delimited_expr = true spaces_around_ranges = true use_field_init_shorthand = true merge_derives = false max_width = 90 struct_lit_width = 40 chain_width = 70 single_line_if_else_max_width = 60 unscanny-0.1.0/src/lib.rs000064400000000000000000000543630072674642500134260ustar 00000000000000/*! Painless string scanning. Basically, you'll want to use this crate if it's too much pain to solve your problem with a bare `chars()` iterator. Speaking more broadly, `unscanny` is useful in these situations: - You need to parse simple flat grammars (dates, times, custom stuff, ...) and want an interface that's a bit more convenient to use than a simple char iterator. - You're hand-writing a tokenizer. The `Scanner` keeps an internal cursor, allows you to peek around it, advance it beyond chars or other patterns and easily slice substrings before and after the cursor. Note that the scanner doesn't have built-in support for parsing things like numbers. It's a level of abstraction below that and wouldn't want to mandate a specific number format. However, you can very easily build your required abstractions on top. # Example Recognizing and parsing a simple comma separated list of floats. ``` # use unscanny::Scanner; let mut s = Scanner::new(" +12 , -15.3, 14.3 "); let mut nums = vec![]; while !s.done() { s.eat_whitespace(); let start = s.cursor(); s.eat_if(['+', '-']); s.eat_while(char::is_ascii_digit); s.eat_if('.'); s.eat_while(char::is_ascii_digit); nums.push(s.from(start).parse::().unwrap()); s.eat_whitespace(); s.eat_if(','); } assert_eq!(nums, [12.0, -15.3, 14.3]); ``` */ #![deny(missing_docs)] use std::fmt::{self, Debug, Formatter, Write}; use std::ops::Range; /// A string scanner. #[derive(Copy, Clone, Eq, PartialEq, Hash)] pub struct Scanner<'a> { /// The string to scan. string: &'a str, /// The index at which we currently are. To guarantee safety, it must always /// hold that: /// - 0 <= cursor <= string.len() /// - cursor is on a character boundary cursor: usize, } impl<'a> Scanner<'a> { /// Create a new string scanner, starting with a cursor position of `0`. #[inline] pub fn new(string: &'a str) -> Self { Self { string, cursor: 0 } } /// The full source string. #[inline] pub fn string(&self) -> &'a str { self.string } /// The current cursor position. #[inline] pub fn cursor(&self) -> usize { self.cursor } /// Whether the scanner has fully consumed the string. #[inline] pub fn done(&self) -> bool { self.cursor == self.string.len() } /// The subslice before the cursor. #[inline] pub fn before(&self) -> &'a str { // Safety: The cursor is always in-bounds and on a codepoint boundary. debug_assert!(self.string.is_char_boundary(self.cursor)); unsafe { self.string.get_unchecked(.. self.cursor) } } /// The subslice after the cursor. #[inline] pub fn after(&self) -> &'a str { // Safety: The cursor is always in-bounds and on a codepoint boundary. debug_assert!(self.string.is_char_boundary(self.cursor)); unsafe { self.string.get_unchecked(self.cursor ..) } } /// The subslices before and after the cursor. #[inline] pub fn parts(&self) -> (&'a str, &'a str) { (self.before(), self.after()) } /// The subslice from `start` to the cursor. /// /// Snaps `start` into the bounds of the string and to the next character /// boundary. #[inline] pub fn from(&self, start: usize) -> &'a str { // Safety: // - Snapping returns an in-bounds index that is on a codepoint boundary // - The cursor is always in-bounds and on a codepoint boundary. // - The start index is <= the end index due to the `min()` let start = self.snap(start).min(self.cursor); debug_assert!(self.string.is_char_boundary(start)); debug_assert!(self.string.is_char_boundary(self.cursor)); unsafe { self.string.get_unchecked(start .. self.cursor) } } /// The subslice from the cursor to `end`. /// /// Snaps `end` into the bounds of the string and to the next character /// boundary. #[inline] pub fn to(&self, end: usize) -> &'a str { // Safety: // - Snapping returns an in-bounds index that is on a codepoint boundary // - The cursor is always in-bounds and on a codepoint boundary. // - The end index is >= the start index due to the `max()` let end = self.snap(end).max(self.cursor); debug_assert!(self.string.is_char_boundary(self.cursor)); debug_assert!(self.string.is_char_boundary(end)); unsafe { self.string.get_unchecked(self.cursor .. end) } } /// The subslice from the `start` to `end`. /// /// Snaps `start` and `end` into the bounds of the string and to the next character /// boundary. #[inline] pub fn get(&self, range: Range) -> &'a str { // Safety: // - Snapping returns an in-bounds index that is on a codepoint boundary // - The end index is >= the start index due to the `max()` let start = self.snap(range.start); let end = self.snap(range.end).max(start); debug_assert!(self.string.is_char_boundary(start)); debug_assert!(self.string.is_char_boundary(end)); unsafe { self.string.get_unchecked(start .. end) } } /// The character right behind the cursor. #[inline] pub fn peek(&self) -> Option { self.after().chars().next() } /// Whether the part right behind the cursor starts with the given pattern. #[inline] pub fn at(&self, mut pat: impl Pattern) -> bool { pat.matches(self.after()).is_some() } /// Look at the n-th character relative to the cursor without changing the /// cursor. /// /// - `scout(-1)` is the character before the cursor. /// - `scout(0)` is the same as `peek()`. /// /// Runs in `O(|n|)`. #[inline] pub fn scout(&self, n: isize) -> Option { if n >= 0 { self.after().chars().nth(n as usize) } else { self.before().chars().nth_back((-n - 1) as usize) } } /// The byte index of the n-th character relative to the cursor. /// /// - `locate(-1)` is the byte position of the character before the cursor. /// - `locate(0)` is the same as `cursor()`. /// /// Runs in `O(|n|)`. #[inline] pub fn locate(&self, n: isize) -> usize { if n >= 0 { let mut chars = self.after().chars(); for _ in 0 .. n { if chars.next().is_none() { break; } } self.string.len() - chars.as_str().len() } else { let mut chars = self.before().chars(); for _ in 0 .. -n { if chars.next_back().is_none() { break; } } chars.as_str().len() } } /// Consume and return the character right behind the cursor. #[inline] pub fn eat(&mut self) -> Option { let peeked = self.peek(); if let Some(c) = peeked { // Safety: When `c` is right behind the cursor, there must be an // in-bounds codepoint boundary at `self.cursor + c.len_utf8()`. self.cursor += c.len_utf8(); } peeked } /// Consume and return the character right before the cursor, moving it /// back. #[inline] pub fn uneat(&mut self) -> Option { let unpeeked = self.before().chars().next_back(); if let Some(c) = unpeeked { // Safety: When `c` is right before the cursor, there must be an // in-bounds codepoint boundary at `self.cursor - c.len_utf8()`. self.cursor -= c.len_utf8(); } unpeeked } /// Consume the given pattern if that's what's right behind the cursor. /// /// Returns `true` if the pattern was consumed. #[inline] pub fn eat_if(&mut self, mut pat: impl Pattern) -> bool { if let Some(len) = pat.matches(self.after()) { // Safety: The contract of `matches` guarantees that there is an // in-bounds codepoint boundary at `len` bytes into `self.after()`. self.cursor += len; true } else { false } } /// Consume while the given pattern is what's right behind the cursor. /// /// Returns the consumed substring. #[inline] pub fn eat_while(&mut self, mut pat: impl Pattern) -> &'a str { let start = self.cursor; while let Some(len @ 1 ..) = pat.matches(self.after()) { // Safety: The contract of `matches` guarantees that there is an // in-bounds codepoint boundary at `len` bytes into `self.after()`. self.cursor += len; } self.from(start) } /// Consume until the given pattern is what's right behind the cursor. /// /// Returns the consumed substring. #[inline] pub fn eat_until(&mut self, mut pat: impl Pattern) -> &'a str { let start = self.cursor; while !self.done() && pat.matches(self.after()).is_none() { self.eat(); } self.from(start) } /// Consume all whitespace until the next non-whitespace character. /// /// Returns the consumed whitespace. #[inline] pub fn eat_whitespace(&mut self) -> &'a str { self.eat_while(char::is_whitespace) } /// Consume the given pattern if that's what's right behind the cursor or /// panic otherwise. #[inline] #[track_caller] pub fn expect(&mut self, mut pat: impl Pattern) { if let Some(len) = pat.matches(self.after()) { // Safety: The contract of `matches` guarantees that there is an // in-bounds codepoint boundary at `len` bytes into `self.after()`. self.cursor += len; } else { pat.expected(); } } /// Jump to a byte position in the source string. /// /// Snaps into the bounds of the string and to the next character boundary. #[inline] pub fn jump(&mut self, target: usize) { // Safety: Snapping returns an in-bounds index that is on a codepoint // boundary. self.cursor = self.snap(target); } } impl<'a> Scanner<'a> { /// Snaps an index in-bounds and to the next codepoint boundary. #[inline] fn snap(&self, mut index: usize) -> usize { // Safety: // - The call to `min()` brings the index in bounds // - After the while loop, the index must be on a codepoint boundary // - `index` cannot underflow because 0 is always a codepoint boundary index = index.min(self.string.len()); while !self.string.is_char_boundary(index) { index -= 1; } index } } impl Debug for Scanner<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { f.write_str("Scanner(")?; let (before, after) = self.parts(); if !before.is_empty() { before.fmt(f)?; f.write_char(' ')?; } f.write_char('|')?; if !after.is_empty() { f.write_char(' ')?; after.fmt(f)?; } f.write_char(')') } } /// Something a string can start with. /// /// This is implemented for: /// /// | Type | Example | /// |------------------------|-----------------------------------| /// | `char` | `scanner.at('a')` | /// | `&str` | `scanner.at("hello")` | /// | `[char; N]`, `&[char]` | `scanner.at(['a', 'b', 'c'])` | /// | `FnMut(char) -> bool` | `scanner.at(char::is_alphabetic)` | /// | `FnMut(&char) -> bool` | `scanner.at(char::is_ascii)` | /// /// As you might have noticed, this closely mirrors the /// [`Pattern`](std::str::pattern::Pattern) trait from the standard library. /// Unfortunately, this trait is unstable, so we can't use it in the scanner's /// method signatures. Furthermore, it doesn't support passing `&char` functions /// which is quite useful because some char methods take `self` by reference. pub trait Pattern: Sealed {} use sealed::Sealed; mod sealed { pub unsafe trait Sealed { /// If the string starts with the pattern, return `Some(len)` with the /// byte length of the match. For safety, it must hold that `len` is in /// bounds of `string` and that `len` bytes into the string, there is a /// UTF-8 char boundary. fn matches(&mut self, string: &str) -> Option; /// Panic with a message stating that the pattern was expected. fn expected(&self); } } impl Pattern<()> for char {} unsafe impl Sealed<()> for char { #[inline] fn matches(&mut self, string: &str) -> Option { // Safety: When the string starts with the needle, there must be an // in-bounds codepoint boundary at `needle.len()` bytes into the // string. let mut buf = [0; 4]; let needle = &*self.encode_utf8(&mut buf); string.starts_with(needle).then(|| needle.len()) } #[cold] fn expected(&self) { panic!("expected {self:?}"); } } impl Pattern<()> for &str {} unsafe impl Sealed<()> for &str { #[inline] fn matches(&mut self, string: &str) -> Option { // Safety: When the string starts with the `self`, there must be an // in-bounds codepoint boundary at `self.len()` bytes into the string. string.starts_with(&*self).then(|| self.len()) } #[cold] fn expected(&self) { panic!("expected {self:?}"); } } impl Pattern<()> for &[char] {} unsafe impl Sealed<()> for &[char] { #[inline] fn matches(&mut self, string: &str) -> Option { // Safety: When the `string` starts with `next`, there must be an // in-bounds codepoint boundary at `next.len_utf8()` bytes into the // string. let next = string.chars().next()?; self.iter().any(|&c| c == next).then(|| next.len_utf8()) } #[cold] fn expected(&self) { struct Or<'a>(&'a [char]); impl Debug for Or<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let mut iter = self.0.iter(); if let Some(c) = iter.next() { c.fmt(f)?; for c in iter { f.write_str(" or ")?; c.fmt(f)?; } } Ok(()) } } if self.is_empty() { panic!("empty slice cannot match"); } else { panic!("expected {:?}", Or(self)); } } } impl Pattern<()> for [char; N] {} unsafe impl Sealed<()> for [char; N] { #[inline] fn matches(&mut self, string: &str) -> Option { self.as_slice().matches(string) } #[cold] fn expected(&self) { self.as_slice().expected(); } } impl Pattern<()> for &[char; N] {} unsafe impl Sealed<()> for &[char; N] { #[inline] fn matches(&mut self, string: &str) -> Option { self.as_slice().matches(string) } #[cold] fn expected(&self) { self.as_slice().expected(); } } impl Pattern for F where F: FnMut(char) -> bool {} unsafe impl Sealed for F where F: FnMut(char) -> bool, { #[inline] fn matches(&mut self, string: &str) -> Option { // Safety: When the `string` starts with `next`, there must be an // in-bounds codepoint boundary at `next.len_utf8()` bytes into the // string. string.chars().next().filter(|&c| self(c)).map(char::len_utf8) } #[cold] fn expected(&self) { panic!("expected closure to return `true`"); } } impl Pattern<&char> for F where F: FnMut(&char) -> bool {} unsafe impl Sealed<&char> for F where F: FnMut(&char) -> bool, { #[inline] fn matches(&mut self, string: &str) -> Option { // Safety: When the `string` starts with `next`, there must be an // in-bounds codepoint boundary at `next.len_utf8()` bytes into the // string. string.chars().next().filter(self).map(char::len_utf8) } #[cold] fn expected(&self) { panic!("expected closure to return `true`"); } } #[cfg(test)] mod tests { use super::Scanner; #[test] fn test_fmt() { let mut s = Scanner::new("hello world"); assert_eq!(format!("{s:?}"), r#"Scanner(| "hello world")"#); s.eat_while(char::is_alphabetic); assert_eq!(format!("{s:?}"), r#"Scanner("hello" | " world")"#); s.eat_while(|_| true); assert_eq!(format!("{s:?}"), r#"Scanner("hello world" |)"#); } #[test] fn test_empty() { let mut s = Scanner::new(""); s.jump(10); assert_eq!(s.cursor(), 0); assert_eq!(s.done(), true); assert_eq!(s.before(), ""); assert_eq!(s.after(), ""); assert_eq!(s.from(0), ""); assert_eq!(s.from(10), ""); assert_eq!(s.to(10), ""); assert_eq!(s.to(10), ""); assert_eq!(s.get(10 .. 20), ""); assert_eq!(s.at(""), true); assert_eq!(s.at('a'), false); assert_eq!(s.at(|_| true), false); assert_eq!(s.scout(-1), None); assert_eq!(s.scout(-1), None); assert_eq!(s.scout(1), None); assert_eq!(s.locate(-1), 0); assert_eq!(s.locate(0), 0); assert_eq!(s.locate(1), 0); assert_eq!(s.eat(), None); assert_eq!(s.uneat(), None); assert_eq!(s.eat_if(""), true); assert_eq!(s.eat_if('a'), false); assert_eq!(s.eat_while(""), ""); assert_eq!(s.eat_while('a'), ""); assert_eq!(s.eat_until(""), ""); assert_eq!(s.eat_whitespace(), ""); } #[test] fn test_slice() { let mut s = Scanner::new("zoo 🦍🌴🎍 party"); assert_eq!(s.parts(), ("", "zoo 🦍🌴🎍 party")); assert_eq!(s.get(2 .. 9), "o 🦍"); assert_eq!(s.get(2 .. 22), "o 🦍🌴🎍 party"); s.eat_while(char::is_ascii); assert_eq!(s.parts(), ("zoo ", "🦍🌴🎍 party")); assert_eq!(s.from(1), "oo "); assert_eq!(s.to(15), "🦍🌴"); assert_eq!(s.to(16), "🦍🌴🎍"); assert_eq!(s.to(17), "🦍🌴🎍 "); assert_eq!(s.to(usize::MAX), "🦍🌴🎍 party"); s.eat_until(char::is_whitespace); assert_eq!(s.parts(), ("zoo 🦍🌴🎍", " party")); assert_eq!(s.from(3), " 🦍🌴🎍"); } #[test] fn test_done_and_peek() { let mut s = Scanner::new("Γ€bc"); assert_eq!(s.done(), false); assert_eq!(s.peek(), Some('Γ€')); s.eat(); assert_eq!(s.done(), false); assert_eq!(s.peek(), Some('b')); s.eat(); assert_eq!(s.done(), false); assert_eq!(s.peek(), Some('c')); s.eat(); assert_eq!(s.done(), true); assert_eq!(s.peek(), None); } #[test] fn test_at() { let mut s = Scanner::new("Π‚12"); assert!(s.at('Π‚')); assert!(s.at(['b', 'Π‚', 'Њ'])); assert!(s.at("Π‚")); assert!(s.at("Π‚1")); assert!(s.at(char::is_alphabetic)); assert!(!s.at(&['b', 'c'])); assert!(!s.at("a13")); assert!(!s.at(char::is_numeric)); s.eat(); assert!(s.at(char::is_numeric)); assert!(s.at(char::is_ascii_digit)); } #[test] fn test_scout_and_locate() { let mut s = Scanner::new("aπŸ†c1Π€"); s.eat_until(char::is_numeric); assert_eq!(s.scout(-4), None); assert_eq!(s.scout(-3), Some('a')); assert_eq!(s.scout(-2), Some('πŸ†')); assert_eq!(s.scout(-1), Some('c')); assert_eq!(s.scout(0), Some('1')); assert_eq!(s.scout(1), Some('Π€')); assert_eq!(s.scout(2), None); assert_eq!(s.locate(-4), 0); assert_eq!(s.locate(-3), 0); assert_eq!(s.locate(-2), 1); assert_eq!(s.locate(-1), 5); assert_eq!(s.locate(0), 6); assert_eq!(s.locate(1), 7); assert_eq!(s.locate(2), 9); assert_eq!(s.locate(3), 9); } #[test] fn test_eat_and_uneat() { let mut s = Scanner::new("🐢🐱🐭"); assert_eq!(s.eat(), Some('🐢')); s.jump(usize::MAX); assert_eq!(s.uneat(), Some('🐭')); assert_eq!(s.uneat(), Some('🐱')); assert_eq!(s.uneat(), Some('🐢')); assert_eq!(s.uneat(), None); assert_eq!(s.eat(), Some('🐢')); } #[test] fn test_conditional_and_looping() { let mut s = Scanner::new("abc123def33"); assert_eq!(s.eat_if('b'), false); assert_eq!(s.eat_if('a'), true); assert_eq!(s.eat_while(['a', 'b', 'c']), "bc"); assert_eq!(s.eat_while(char::is_numeric), "123"); assert_eq!(s.eat_until(char::is_numeric), "def"); assert_eq!(s.eat_while('3'), "33"); } #[test] fn test_eat_whitespace() { let mut s = Scanner::new("αˆ™αˆ \n b\tቂ"); assert_eq!(s.eat_whitespace(), ""); assert_eq!(s.eat_while(char::is_alphabetic), "αˆ™αˆ"); assert_eq!(s.eat_whitespace(), " \n "); assert_eq!(s.eat_if('b'), true); assert_eq!(s.eat_whitespace(), "\t"); assert_eq!(s.eat_while(char::is_alphabetic), "ቂ"); } #[test] fn test_expect_okay() { let mut s = Scanner::new("🦚12"); s.expect('🦚'); s.jump(1); s.expect("🦚"); assert_eq!(s.after(), "12"); } #[test] #[should_panic(expected = "expected '🐒'")] fn test_expect_char_fail() { let mut s = Scanner::new("no turtle in sight"); s.expect('🐒'); } #[test] #[should_panic(expected = "expected \"🐒\"")] fn test_expect_str_fail() { let mut s = Scanner::new("no turtle in sight"); s.expect("🐒"); } #[test] #[should_panic(expected = "empty slice cannot match")] fn test_expect_empty_array_fail() { let mut s = Scanner::new(""); s.expect([]); } #[test] #[should_panic(expected = "expected '🐒' or '🐬'")] fn test_expect_array_fail() { let mut s = Scanner::new("no turtle or dolphin in sight"); s.expect(['🐒', '🐬']); } #[test] #[should_panic(expected = "expected closure to return `true`")] fn test_expect_closure_fail() { let mut s = Scanner::new("no numbers in sight"); s.expect(char::is_numeric); } }