1use core::fmt;
11use core::hash::{Hash, Hasher};
12use core::marker::PhantomData;
13
14use crate::id::NodeId;
15
16const MIN_CLASS: u32 = 2; const MAX_CLASS: u32 = 30; const CLASSES: usize = (MAX_CLASS as usize) + 1;
19pub const MAX_SPAN_LEN: u32 = 1u32 << MAX_CLASS;
21
22#[inline(always)]
24const fn class_of(len: u32) -> u32 {
25 let clamped = if len > MAX_SPAN_LEN { MAX_SPAN_LEN } else { len };
26 let c = u32::BITS - clamped.saturating_sub(1).leading_zeros();
27 if c < MIN_CLASS { MIN_CLASS } else { c }
28}
29
30#[inline(always)]
32pub const fn class_cap(len: u32) -> u32 {
33 1u32 << class_of(len)
34}
35
36#[repr(C)]
42pub struct Span<T> {
43 pub(crate) off: u32,
44 pub(crate) len: u32,
45 _marker: PhantomData<fn() -> T>,
46}
47
48pub type ChildSpan = Span<NodeId>;
50pub type StrSpan = Span<u8>;
52
53const _: () = {
54 assert!(size_of::<ChildSpan>() == 8);
55 assert!(size_of::<StrSpan>() == 8);
56};
57
58impl<T> Clone for Span<T> {
59 #[inline(always)]
60 fn clone(&self) -> Self {
61 *self
62 }
63}
64
65impl<T> Copy for Span<T> {}
66
67impl<T> PartialEq for Span<T> {
68 #[inline(always)]
69 fn eq(&self, other: &Self) -> bool {
70 self.off == other.off && self.len == other.len
71 }
72}
73
74impl<T> Eq for Span<T> {}
75
76impl<T> Hash for Span<T> {
77 #[inline(always)]
78 fn hash<H: Hasher>(&self, state: &mut H) {
79 self.off.hash(state);
80 self.len.hash(state);
81 }
82}
83
84impl<T> Default for Span<T> {
85 #[inline(always)]
86 fn default() -> Self {
87 Self::EMPTY
88 }
89}
90
91impl<T> fmt::Debug for Span<T> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.debug_struct("Span")
94 .field("off", &self.off)
95 .field("len", &self.len)
96 .finish()
97 }
98}
99
100impl<T> Span<T> {
101 pub const EMPTY: Self = Self {
102 off: 0,
103 len: 0,
104 _marker: PhantomData,
105 };
106
107 #[inline(always)]
108 pub(crate) const fn new(off: u32, len: u32) -> Self {
109 Self {
110 off,
111 len,
112 _marker: PhantomData,
113 }
114 }
115
116 #[inline(always)]
117 pub const fn off(self) -> u32 {
118 self.off
119 }
120
121 #[inline(always)]
122 pub const fn len(self) -> u32 {
123 self.len
124 }
125
126 #[inline(always)]
127 pub const fn is_empty(self) -> bool {
128 self.len == 0
129 }
130
131 #[inline(always)]
132 pub const fn range(self) -> core::ops::Range<usize> {
133 let start = self.off as usize;
134 start..start.saturating_add(self.len as usize)
135 }
136}
137
138#[derive(Debug, Clone)]
139pub struct SpanPool<T: Copy + Default> {
140 data: Vec<T>,
141 free: [Vec<u32>; CLASSES],
142 live: usize,
143 live_cap: usize,
144}
145
146impl<T: Copy + Default> Default for SpanPool<T> {
147 fn default() -> Self {
148 Self {
149 data: Vec::new(),
150 free: Default::default(),
151 live: 0,
152 live_cap: 0,
153 }
154 }
155}
156
157impl<T: Copy + Default> SpanPool<T> {
158 #[inline(always)]
160 pub fn data(&self) -> &[T] {
161 &self.data
162 }
163
164 #[inline(always)]
165 pub fn get(&self, span: Span<T>) -> &[T] {
166 if span.len == 0 {
167 return &[];
168 }
169 &self.data[span.range()]
170 }
171
172 #[inline(always)]
173 pub fn try_get(&self, span: Span<T>) -> Option<&[T]> {
174 if span.len == 0 {
175 return Some(&[]);
176 }
177 let start = span.off as usize;
178 let end = start.checked_add(span.len as usize)?;
179 self.data.get(start..end)
180 }
181
182 #[inline]
184 pub fn live(&self) -> usize {
185 self.live
186 }
187
188 #[inline]
190 pub fn live_capacity(&self) -> usize {
191 self.live_cap
192 }
193
194 #[inline]
197 pub fn try_reserve_data(
198 &mut self,
199 min_cap: usize,
200 ) -> Result<(), std::collections::TryReserveError> {
201 if self.data.capacity() < min_cap {
202 self.data
203 .try_reserve(min_cap.saturating_sub(self.data.len()))?;
204 }
205 Ok(())
206 }
207
208 fn alloc(&mut self, len: u32) -> u32 {
209 assert!(len <= MAX_SPAN_LEN, "SpanPool: span length {len} exceeds MAX_SPAN_LEN");
210 let class = class_of(len) as usize;
211 let cap = 1usize << class;
212 if let Some(off) = self.free[class].pop() {
213 self.live_cap += cap;
214 return off;
215 }
216 let off = u32::try_from(self.data.len()).expect("SpanPool: backing offset exceeds u32::MAX");
217 let new_total = self
218 .data
219 .len()
220 .checked_add(cap)
221 .expect("SpanPool: backing capacity overflow");
222 assert!(
223 u32::try_from(new_total).is_ok(),
224 "SpanPool: backing slab exceeds u32::MAX elements"
225 );
226 self.data.resize(new_total, T::default());
227 self.live_cap += cap;
228 off
229 }
230
231 #[inline]
233 pub fn free(&mut self, span: Span<T>) {
234 if span.len != 0 {
235 let class = class_of(span.len) as usize;
236 self.live = self.live.saturating_sub(span.len as usize);
237 self.live_cap = self.live_cap.saturating_sub(1usize << class);
238 self.reset(span.off as usize, span.len as usize);
239 self.free[class].push(span.off);
240 }
241 }
242
243 #[inline]
245 fn reset(&mut self, start: usize, len: usize) {
246 self.data[start..start + len].fill(T::default());
247 }
248
249 pub fn replace(&mut self, span: Span<T>, src: &[T]) -> Span<T> {
252 let new_len = u32::try_from(src.len()).expect("SpanPool: span length exceeds u32::MAX");
253 assert!(
254 new_len <= MAX_SPAN_LEN,
255 "SpanPool: span length {new_len} exceeds MAX_SPAN_LEN"
256 );
257 if new_len == 0 {
258 self.free(span);
259 return Span::EMPTY;
260 }
261 let off = if span.len != 0 && class_of(span.len) == class_of(new_len) {
262 self.live = self.live.saturating_sub(span.len as usize) + new_len as usize;
263 if new_len < span.len {
264 self.reset((span.off + new_len) as usize, (span.len - new_len) as usize);
266 }
267 span.off
268 } else {
269 self.free(span);
270 let off = self.alloc(new_len);
271 self.live += new_len as usize;
272 off
273 };
274 let start = off as usize;
275 let end = start + new_len as usize;
276 self.data[start..end].copy_from_slice(src);
277 Span::new(off, new_len)
278 }
279
280 pub fn insert_at(&mut self, span: Span<T>, at: usize, elem: T) -> Span<T> {
283 let old_len = span.len as usize;
284 let at = at.min(old_len);
285 let new_len = span.len.checked_add(1).expect("SpanPool: span length overflow");
286 assert!(
287 new_len <= MAX_SPAN_LEN,
288 "SpanPool: span length {new_len} exceeds MAX_SPAN_LEN"
289 );
290 if span.len != 0 && class_of(span.len) == class_of(new_len) {
291 let base = span.off as usize;
292 self.data.copy_within(base + at..base + old_len, base + at + 1);
293 self.data[base + at] = elem;
294 self.live += 1;
295 Span::new(span.off, new_len)
296 } else {
297 let new_off = self.alloc(new_len);
298 let dst = new_off as usize;
299 if span.len != 0 {
300 let src = span.off as usize;
301 self.data.copy_within(src..src + at, dst);
302 self.data.copy_within(src + at..src + old_len, dst + at + 1);
303 self.free(span);
304 }
305 self.data[dst + at] = elem;
306 self.live += new_len as usize;
307 Span::new(new_off, new_len)
308 }
309 }
310
311 pub fn remove_at(&mut self, span: Span<T>, at: usize) -> Span<T> {
313 assert!(at < span.len as usize, "SpanPool::remove_at index {at} out of bounds (len={})", span.len);
314 let new_len = span.len - 1;
315 if new_len == 0 {
316 self.free(span);
317 return Span::EMPTY;
318 }
319 let start = span.off as usize;
320 let end = start + span.len as usize;
321 if class_of(new_len) == class_of(span.len) {
322 self.data.copy_within(start + at + 1..end, start + at);
323 self.reset(end - 1, 1);
324 self.live = self.live.saturating_sub(1);
325 Span::new(span.off, new_len)
326 } else {
327 let off = self.alloc(new_len);
328 let dst = off as usize;
329 self.data.copy_within(start..start + at, dst);
330 self.data.copy_within(start + at + 1..end, dst + at);
331 self.free(span);
332 self.live += new_len as usize;
333 Span::new(off, new_len)
334 }
335 }
336}
337
338#[derive(Debug, Clone, Default)]
349pub struct StrArena(SpanPool<u8>);
350
351impl StrArena {
352 #[inline(always)]
353 pub fn data(&self) -> &[u8] {
354 self.0.data()
355 }
356
357 #[inline(always)]
358 pub fn live(&self) -> usize {
359 self.0.live()
360 }
361
362 #[inline]
363 pub(crate) fn try_reserve_bytes(
364 &mut self,
365 min_cap: usize,
366 ) -> Result<(), std::collections::TryReserveError> {
367 self.0.try_reserve_data(min_cap)
368 }
369
370 #[inline(always)]
373 pub(crate) fn str_unchecked(&self, span: StrSpan) -> &str {
374 let bytes = self.0.get(span);
375 debug_assert!(core::str::from_utf8(bytes).is_ok());
376 unsafe { core::str::from_utf8_unchecked(bytes) }
380 }
381
382 #[inline]
384 pub fn try_str(&self, span: StrSpan) -> Option<&str> {
385 let bytes = self.0.try_get(span)?;
386 core::str::from_utf8(bytes).ok()
387 }
388
389 #[inline]
391 pub fn str(&self, span: StrSpan) -> &str {
392 self.try_str(span).unwrap_or("")
393 }
394
395 #[inline]
397 pub(crate) fn replace_str(&mut self, span: StrSpan, text: &str) -> StrSpan {
398 if self.0.get(span) == text.as_bytes() {
399 return span;
400 }
401 self.0.replace(span, text.as_bytes())
402 }
403
404 #[inline]
405 pub(crate) fn free(&mut self, span: StrSpan) {
406 self.0.free(span);
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn class_capacity_is_next_power_of_two_with_floor() {
416 assert_eq!(class_cap(1), 4);
417 assert_eq!(class_cap(4), 4);
418 assert_eq!(class_cap(5), 8);
419 assert_eq!(class_cap(8), 8);
420 assert_eq!(class_cap(9), 16);
421 assert_eq!(class_cap(17), 32);
422 }
423
424 #[test]
425 fn replace_reuses_slots_within_class_and_recycles_across_classes() {
426 let mut p: SpanPool<u32> = SpanPool::default();
427 let a = p.replace(Span::EMPTY, &[1, 2, 3]);
428 assert_eq!(p.get(a), &[1, 2, 3]);
429 let a2 = p.replace(a, &[4, 5, 6, 7]);
430 assert_eq!(a2.off(), a.off(), "same class must reuse in place");
431 assert_eq!(p.get(a2), &[4, 5, 6, 7]);
432
433 let a3 = p.replace(a2, &[1, 2, 3, 4, 5]);
434 assert_ne!(a3.off(), a2.off(), "larger class allocates a new slot");
435 assert_eq!(p.live(), 5);
436
437 let b = p.replace(Span::EMPTY, &[9, 8]);
438 assert_eq!(b.off(), a2.off(), "freed 4-slot span must be recycled");
439 assert_eq!(p.live(), 7);
440 assert_eq!(p.live_capacity(), 12);
441 p.free(b);
442 assert_eq!(p.live_capacity(), 8);
443 assert_eq!(p.data().len(), 12);
444 }
445
446 #[test]
447 fn insert_at_and_remove_at_preserve_order_across_classes() {
448 let mut p: SpanPool<u32> = SpanPool::default();
449 let mut s = Span::EMPTY;
450 for i in 0..6u32 {
451 s = p.insert_at(s, i as usize, i * 10);
452 }
453 assert_eq!(p.get(s), &[0, 10, 20, 30, 40, 50]);
454 s = p.insert_at(s, 2, 15);
455 assert_eq!(p.get(s), &[0, 10, 15, 20, 30, 40, 50]);
456 s = p.remove_at(s, 2);
457 assert_eq!(p.get(s), &[0, 10, 20, 30, 40, 50]);
458 s = p.remove_at(s, 0);
459 s = p.remove_at(s, 0);
460 assert_eq!(p.get(s), &[20, 30, 40, 50]);
461 assert_eq!(p.live(), 4);
462 }
463
464 #[test]
467 fn slots_outside_live_spans_stay_default() {
468 let mut p: SpanPool<u32> = SpanPool::default();
469 let mut a = p.replace(Span::EMPTY, &[1, 2, 3, 4, 5, 6, 7]); let b = p.replace(Span::EMPTY, &[9, 9, 9]);
471 a = p.replace(a, &[8, 8, 8, 8, 8]); a = p.remove_at(a, 0); let freed = p.replace(Span::EMPTY, &[7; 16]);
474 p.free(freed);
475 let c = p.insert_at(b, 3, 4); let live: std::collections::HashSet<usize> = [a, c]
477 .iter()
478 .flat_map(|s| s.off() as usize..(s.off() + s.len()) as usize)
479 .collect();
480 for (i, v) in p.data().iter().enumerate() {
481 assert!(live.contains(&i) || *v == 0, "slot {i} holds stale {v}");
482 }
483 assert_eq!((p.get(a), p.get(c)), (&[8, 8, 8, 8][..], &[9, 9, 9, 4][..]));
484 }
485
486 #[test]
487 fn str_arena_skips_identical_writes_and_reads_utf8_zero_cost() {
488 let mut s = StrArena::default();
489 let a = s.replace_str(StrSpan::EMPTY, "hello 🚀");
490 let b = s.replace_str(a, "hello 🚀");
491 assert_eq!(a, b);
492 assert_eq!(s.str(b), "hello 🚀");
493 }
494
495 #[test]
498 fn str_arena_slab_stays_utf8_across_shrinks_recycling_and_migration() {
499 let mut s = StrArena::default();
500 let slab_ok = |s: &StrArena| core::str::from_utf8(s.data()).is_ok();
501 let a = s.replace_str(StrSpan::EMPTY, "ab·");
503 let a2 = s.replace_str(a, "abc");
504 assert_eq!(a2.off(), a.off());
505 assert_eq!(s.data()[a.off() as usize..][..4], *b"abc\0");
506 assert!(slab_ok(&s));
507 let b = s.replace_str(StrSpan::EMPTY, "x🚀yz");
509 s.free(b);
510 let c = s.replace_str(StrSpan::EMPTY, "hello");
511 assert_eq!(c.off(), b.off(), "recycled from the free list");
512 assert!(slab_ok(&s));
513 let d = s.replace_str(a2, "€€€€€€");
515 assert!(slab_ok(&s));
516 let e = s.replace_str(d, "é");
517 assert!(slab_ok(&s));
518 assert_eq!((s.str(c), s.str(e)), ("hello", "é"));
519 for text in ["日本語テã‚スト", "ab", "🚀🚀", "a"] {
520 let f = s.replace_str(e, text);
521 assert!(slab_ok(&s), "after writing {text:?}");
522 assert_eq!(s.str(f), text);
523 }
524 }
525}