repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by admin
smith-harness/src/response_sanitizer/frontier.rs
Raw//! Incremental earliest-start matching (`SMH-SPEC-SPEC0001`, Authentication).
//! Completed starts can progress immediately; failed long prefixes fall back to
//! block matching, rather than restarting at every overlapping byte offset.
use super::{Dictionary, Spelling, length, scalar_spelling, spelling_offset};
#[derive(Clone, Copy)]
pub(super) struct PrefixProgress {
raw_offset: u16,
credential_offset: u16,
wire_offset: u16,
raw_active: bool,
json_active: bool,
}
impl Default for PrefixProgress {
fn default() -> Self {
Self {
raw_offset: 0,
credential_offset: 0,
wire_offset: 0,
raw_active: true,
json_active: true,
}
}
}
impl Dictionary {
pub(super) fn advance_start(&mut self, bytes: &[u8], credentials: &[String]) -> bool {
assert!(
!credentials.is_empty() && self.progress.len() == credentials.len(),
"frontier must contain one progress record per validated credential"
);
let mut pending = false;
for (progress, credential) in self.progress.iter_mut().zip(credentials) {
if progress.raw_active {
let start = usize::from(progress.raw_offset);
let end = bytes.len().min(credential.len());
for (index, (&actual, &expected)) in bytes[start..end]
.iter()
.zip(&credential.as_bytes()[start..end])
.enumerate()
{
let offset = start + index;
#[cfg(test)]
super::COMPARISONS.with(|count| count.set(count.get() + 1));
self.inspected_bytes = self.inspected_bytes.max(spelling_offset(offset + 1));
if actual != expected {
progress.raw_active = false;
break;
}
progress.raw_offset += 1;
}
if usize::from(progress.raw_offset) == credential.len() {
self.matched_length = self.matched_length.max(progress.raw_offset);
progress.raw_active = false;
}
}
while progress.json_active {
let Some(scalar) = credential[usize::from(progress.credential_offset)..]
.chars()
.next()
else {
self.matched_length = self.matched_length.max(progress.wire_offset);
progress.json_active = false;
break;
};
let start = usize::from(progress.wire_offset);
let remaining = &bytes[start..];
match scalar_spelling(remaining, scalar) {
Spelling::Complete(count) => {
progress.credential_offset += length(scalar.len_utf8());
progress.wire_offset = spelling_offset(start + count);
self.inspected_bytes = self.inspected_bytes.max(progress.wire_offset);
}
Spelling::Prefix => {
self.inspected_bytes =
self.inspected_bytes.max(spelling_offset(bytes.len()));
break;
}
Spelling::Different => {
// One scalar can inspect at most one surrogate pair.
self.inspected_bytes = self.inspected_bytes.max(spelling_offset(
start + remaining.len().min(scalar.len_utf16() * 6),
));
progress.json_active = false;
}
}
}
pending |= progress.raw_active || progress.json_active;
}
pending
}
}
#[cfg(test)]
mod tests {
//! SMH-SPEC-SPEC0001: bounded request-owned prefix state.
#[test]
fn prefix_progress_fits_eight_bytes() {
assert_eq!(std::mem::size_of::<super::PrefixProgress>(), 8);
}
}