Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
117 lines
5.9 KiB
Plaintext
117 lines
5.9 KiB
Plaintext
Here is a Rust module.
|
|
|
|
```
|
|
//! Original four-way trigram suffix index. It is a drafter, never target authority.
|
|
use super::contract::{Error, Result};
|
|
#[derive(Clone,Copy,Default)]
|
|
struct Slot { key:u64,pos:[u32;4],n:u8 }
|
|
pub(crate) struct SuffixDrafter {
|
|
min_match:usize,max_match:usize,history:Vec<i32>,table:Box<[Slot]>,mask:usize,last_match:usize,
|
|
/// Table slots claimed since the last reset, so a reset clears those instead of the whole table (the table is
|
|
/// sized for the whole context: 32 MB at 262144 cells, a request touches a few thousand slots).
|
|
touched:Vec<u32>,
|
|
}
|
|
/// `LELEKA_SUFFIX_RESET=full`: clear the whole table on every reset (the earlier behaviour; A/B control).
|
|
fn sparse_reset()->bool {
|
|
static ON:std::sync::OnceLock<bool>=std::sync::OnceLock::new();
|
|
*ON.get_or_init(||!std::env::var("LELEKA_SUFFIX_RESET").is_ok_and(|v|v=="full"))
|
|
}
|
|
fn mix(mut x:u64)->u64 {
|
|
x^=x>>33;x=x.wrapping_mul(0xff51afd7ed558ccd);x^=x>>33;
|
|
x=x.wrapping_mul(0xc4ceb9fe1a85ec53);x^(x>>33)
|
|
}
|
|
impl SuffixDrafter {
|
|
pub(crate) fn new(min_match:usize,max_match:usize,capacity_tokens:usize)->Result<Self> {
|
|
if capacity_tokens==0 || capacity_tokens>i32::MAX as usize {return Err(Error::InvalidDimension);}
|
|
let cap=capacity_tokens.checked_mul(2).and_then(usize::checked_next_power_of_two).ok_or(Error::Overflow)?;
|
|
let mut table=Vec::new();table.try_reserve_exact(cap).map_err(|_|Error::InputAllocation)?;
|
|
table.resize(cap,Slot::default());
|
|
let mut history=Vec::new();history.try_reserve_exact(capacity_tokens).map_err(|_|Error::InputAllocation)?;
|
|
Ok(Self{min_match:min_match.max(3),max_match:min_match.max(max_match),history,table:table.into_boxed_slice(),mask:cap-1,last_match:0,touched:Vec::new()})
|
|
}
|
|
pub(crate) fn metadata_bytes(&self)->Result<usize> {
|
|
self.history.capacity().checked_mul(std::mem::size_of::<i32>())
|
|
.and_then(|n|n.checked_add(self.table.len().checked_mul(std::mem::size_of::<Slot>())?))
|
|
.and_then(|n|n.checked_add(std::mem::size_of::<Self>())).ok_or(Error::Overflow)
|
|
}
|
|
pub(crate) fn reset(&mut self) {
|
|
self.history.clear();self.last_match=0;
|
|
// Only a slot `find_slot(.., true)` claimed holds anything: clearing those is the same table as a full fill.
|
|
if sparse_reset()&&self.touched.len()<=self.table.len()/4 {
|
|
for &i in &self.touched {self.table[i as usize]=Slot::default();}
|
|
} else {
|
|
self.table.fill(Slot::default());
|
|
}
|
|
self.touched.clear();
|
|
}
|
|
pub(crate) fn reserve_reset(&self,n:usize)->Result<()> {
|
|
if n>self.history.capacity() {return Err(Error::InputAllocation);}Ok(())
|
|
}
|
|
pub(crate) fn reserve_append(&self,n:usize)->Result<()> {
|
|
if self.history.len().checked_add(n).ok_or(Error::Overflow)?>self.history.capacity() {return Err(Error::InputAllocation);}Ok(())
|
|
}
|
|
fn key_at(&self,end:usize)->u64 {
|
|
let a=self.history[end-2] as u32 as u64;let b=self.history[end-1] as u32 as u64;let c=self.history[end] as u32 as u64;
|
|
mix(a.wrapping_mul(0x9E3779B97F4A7C15)^mix(b.wrapping_add(0x632BE59BD9B4E019))^(c<<1))|1
|
|
}
|
|
fn find_slot(&mut self,key:u64,insert:bool)->Option<usize> {
|
|
let mut i=key as usize & self.mask;
|
|
for _ in 0..=self.mask {
|
|
if self.table[i].key==key {return Some(i);}
|
|
if self.table[i].key==0 {if !insert {return None;}self.table[i].key=key;self.touched.push(i as u32);return Some(i);}
|
|
i=(i+1)&self.mask;
|
|
}None
|
|
}
|
|
pub(crate) fn append(&mut self,tokens:&[i32])->Result<()> {
|
|
self.reserve_append(tokens.len())?;
|
|
for &token in tokens {
|
|
self.history.push(token);let end=self.history.len()-1;if end<2 {continue;}
|
|
let key=self.key_at(end);
|
|
if let Some(i)=self.find_slot(key,true) {
|
|
let s=&mut self.table[i];for w in (1..4).rev() {s.pos[w]=s.pos[w-1];}
|
|
s.pos[0]=end as u32;if s.n<4 {s.n+=1;}
|
|
}
|
|
}Ok(())
|
|
}
|
|
pub(crate) fn propose(&mut self,out:&mut[i32])->usize {
|
|
self.last_match=0;let n=self.history.len();if n<4||out.is_empty() {return 0;}
|
|
let cur=n-1;let key=self.key_at(cur);let Some(i)=self.find_slot(key,false) else {return 0;};
|
|
let slot=self.table[i];let(mut best_end,mut best_len)=(0,0);
|
|
for w in 0..slot.n as usize {
|
|
let p=slot.pos[w] as usize;if p>=cur {continue;}
|
|
let mut len=0;while len<self.max_match && len<=p && self.history[p-len]==self.history[cur-len] {len+=1;}
|
|
if len>best_len {best_len=len;best_end=p;}
|
|
}
|
|
if best_len<self.min_match {return 0;}self.last_match=best_len;
|
|
let mut k=0;for q in best_end+1..=cur {if k==out.len() {break;}out[k]=self.history[q];k+=1;}k
|
|
}
|
|
pub(crate) fn last_match(&self)->usize {self.last_match}
|
|
pub(crate) fn len(&self)->usize {self.history.len()}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn a_sparse_reset_leaves_the_same_empty_table_as_a_full_clear() {
|
|
let mut drafter=SuffixDrafter::new(3,64,4096).unwrap();
|
|
let tokens:Vec<i32>=(0..300).map(|i|(i*7+i/3)%97).collect();
|
|
drafter.append(&tokens).unwrap();
|
|
assert!(!drafter.touched.is_empty());
|
|
drafter.reset();
|
|
assert!(drafter.table.iter().all(|s|s.key==0&&s.n==0&&s.pos==[0;4]),"every claimed slot is cleared");
|
|
assert!(drafter.touched.is_empty()&&drafter.len()==0);
|
|
// the same tokens give the same proposals after the reset as on a fresh drafter
|
|
let mut fresh=SuffixDrafter::new(3,64,4096).unwrap();
|
|
drafter.append(&tokens).unwrap();fresh.append(&tokens).unwrap();
|
|
let (mut a,mut b)=([0;7],[0;7]);
|
|
assert_eq!(drafter.propose(&mut a),fresh.propose(&mut b));
|
|
assert_eq!(a,b);
|
|
assert_eq!(drafter.last_match(),fresh.last_match());
|
|
}
|
|
}
|
|
```
|
|
|
|
Write the same module again, restructured so that each long function is split into small helper functions. Output the complete file.
|