Skip to content

Truly independent web browser

AK: Add a Rust parser for integers made only of ASCII digits

Shannon Booth107c839e1ed7
diff --git a/AK/Rust/src/lib.rs b/AK/Rust/src/lib.rs
index 04d4215a7bb..39e233baec0 100644
--- a/AK/Rust/src/lib.rs
+++ b/AK/Rust/src/lib.rs
@@ -12,6 +12,7 @@ pub mod perf_map;
mod scope_guard;
mod slice;
pub mod stack;
+mod string_conversions;
pub mod waiter_list;
#[cfg(all(windows, target_arch = "x86_64"))]
pub mod windows_code_memory;
@@ -19,6 +20,7 @@ pub mod windows_code_memory;
pub use generic_lexer::GenericLexer;
pub use scope_guard::ScopeGuard;
pub use slice::{Span, SpanMut, slice_from_raw_parts, slice_from_raw_parts_mut};
+pub use string_conversions::{UnsignedInteger, parse_ascii_digits};
use core::mem::MaybeUninit;
use std::num::NonZeroUsize;
diff --git a/AK/Rust/src/string_conversions.rs b/AK/Rust/src/string_conversions.rs
new file mode 100644
index 00000000000..a52ab389cb2
--- /dev/null
+++ b/AK/Rust/src/string_conversions.rs
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+pub trait UnsignedInteger: Copy {
+ const ZERO: Self;
+
+ fn checked_mul_add(self, radix: u32, digit: u32) -> Option<Self>;
+}
+
+macro_rules! impl_unsigned_integer {
+ ($($type:ty),*) => {
+ $(
+ impl UnsignedInteger for $type {
+ const ZERO: Self = 0;
+
+ fn checked_mul_add(self, radix: u32, digit: u32) -> Option<Self> {
+ self.checked_mul(<$type>::try_from(radix).ok()?)?
+ .checked_add(<$type>::try_from(digit).ok()?)
+ }
+ }
+ )*
+ };
+}
+
+impl_unsigned_integer!(u8, u16, u32, u64, usize);
+
+/// Parses `input` as an unsigned integer made only of radix-`radix` digits, with no sign, whitespace or prefix.
+/// Returns `None` if `input` is empty, holds anything else, or does not fit in `T`.
+pub fn parse_ascii_digits<T: UnsignedInteger>(input: &[u8], radix: u32) -> Option<T> {
+ if input.is_empty() {
+ return None;
+ }
+
+ input.iter().try_fold(T::ZERO, |value, &byte| {
+ value.checked_mul_add(radix, char::from(byte).to_digit(radix)?)
+ })
+}