pub struct Fsa<D> { /* private fields */ }Expand description
A read-only minimal-FSA map over a byte container.
Implementations§
Source§impl<D: AsRef<[u8]>> Fsa<D>
impl<D: AsRef<[u8]>> Fsa<D>
Sourcepub fn new(data: D) -> Result<Self, FsaError>
pub fn new(data: D) -> Result<Self, FsaError>
Load an FSA from a serialized byte buffer. Accepts anything that
implements AsRef<[u8]> (&[u8], Vec<u8>, mmap::Mmap, etc.).
The buffer is parsed header-only — no allocation per entry.
Returns FsaError::BadMagic / FsaError::BadVersion /
FsaError::Truncated on invalid input; never panics.
use inputx_fsa::{Builder, Fsa, FsaError};
let mut b = Builder::new();
b.insert(b"hello", 42);
let bytes = b.finish();
let fsa = Fsa::new(&bytes[..]).unwrap();
assert_eq!(fsa.len(), 1);
// Corrupt magic → graceful error, no panic.
let mut bad = bytes.clone();
bad[0] = 0;
assert!(matches!(Fsa::new(&bad[..]), Err(FsaError::BadMagic)));pub fn is_empty(&self) -> bool
Sourcepub fn state_count(&self) -> u32
pub fn state_count(&self) -> u32
Total number of states in the automaton (diagnostics).
Sourcepub fn get(&self, key: &[u8]) -> Option<u64>
pub fn get(&self, key: &[u8]) -> Option<u64>
Look up key — Some(value) for an exact match, None otherwise.
Constant cost per byte; the buffer is never copied.
use inputx_fsa::{Builder, Fsa};
let mut b = Builder::new();
b.insert(b"ni", 1);
b.insert(b"nihao", 100);
let fsa = Fsa::new(b.finish()).unwrap();
assert_eq!(fsa.get(b"ni"), Some(1));
assert_eq!(fsa.get(b"nihao"), Some(100));
assert_eq!(fsa.get(b"niha"), None); // prefix-only, not a key
assert_eq!(fsa.get(b"absent"), None);Sourcepub fn contains_prefix(&self, prefix: &[u8]) -> bool
pub fn contains_prefix(&self, prefix: &[u8]) -> bool
true if any stored key starts with prefix.
Sourcepub fn prefix(&self, prefix: &[u8]) -> Vec<(Vec<u8>, u64)>
pub fn prefix(&self, prefix: &[u8]) -> Vec<(Vec<u8>, u64)>
All (key, value) pairs whose key starts with prefix, sorted.
Sourcepub fn prefix_for_each<F: FnMut(&[u8], u64)>(&self, prefix: &[u8], visit: F)
pub fn prefix_for_each<F: FnMut(&[u8], u64)>(&self, prefix: &[u8], visit: F)
Streaming variant: invoke visit(key, value) for every (key, value)
whose key starts with prefix, in sorted order, without allocating a
result vector. The key slice is valid only for the call. This is the
hot-path entry — a bare-letter prefix can match tens of thousands of
keys, and materializing them all would dominate cost.
use inputx_fsa::{Builder, Fsa};
let mut b = Builder::new();
for (k, v) in [(&b"apple"[..], 1u64), (b"apply", 2), (b"banana", 3)] {
b.insert(k, v);
}
let fsa = Fsa::new(b.finish()).unwrap();
let mut count = 0;
let mut last_value = 0;
fsa.prefix_for_each(b"app", |_key, value| {
count += 1;
last_value = value;
});
assert_eq!(count, 2); // apple + apply
assert_eq!(last_value, 2); // "apply" sorts last