Skip to content

Truly independent web browser

AK: Add GenericLexer to the Rust crate

Shannon Booth0a5af865f428
diff --git a/AK/Rust/src/generic_lexer.rs b/AK/Rust/src/generic_lexer.rs
new file mode 100644
index 00000000000..f22deabdb2a
--- /dev/null
+++ b/AK/Rust/src/generic_lexer.rs
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub struct GenericLexer<'a, T> {
+ input: &'a [T],
+ index: usize,
+}
+
+impl<'a, T: Copy + PartialEq> GenericLexer<'a, T> {
+ pub fn new(input: &'a [T]) -> Self {
+ Self { input, index: 0 }
+ }
+
+ pub fn is_eof(&self) -> bool {
+ self.index >= self.input.len()
+ }
+
+ pub fn peek(&self) -> Option<T> {
+ self.input.get(self.index).copied()
+ }
+
+ pub fn consume(&mut self) -> Option<T> {
+ let item = self.peek()?;
+ self.index += 1;
+ Some(item)
+ }
+
+ pub fn consume_specific(&mut self, item: T) -> bool {
+ if self.peek() != Some(item) {
+ return false;
+ }
+ self.index += 1;
+ true
+ }
+
+ pub fn consume_while(&mut self, mut predicate: impl FnMut(T) -> bool) -> &'a [T] {
+ let start = self.index;
+ while self.peek().is_some_and(&mut predicate) {
+ self.index += 1;
+ }
+ &self.input[start..self.index]
+ }
+
+ pub fn ignore(&mut self, count: usize) {
+ self.index = self.input.len().min(self.index + count);
+ }
+
+ pub fn ignore_while(&mut self, predicate: impl FnMut(T) -> bool) {
+ self.consume_while(predicate);
+ }
+
+ pub fn ignore_until(&mut self, stop: T) {
+ self.consume_while(|item| item != stop);
+ }
+}
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index d132790781a..f655458ba82 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -6,11 +6,13 @@
//! Rust views of shared AK data structures.
+mod generic_lexer;
pub mod math;
pub mod perf_map;
mod scope_guard;
mod slice;
+pub use generic_lexer::GenericLexer;
pub use scope_guard::ScopeGuard;
pub use slice::{Span, SpanMut, slice_from_raw_parts, slice_from_raw_parts_mut};