1use std::sync::Arc;
15
16use crate::arena::Pod;
17
18pub const INLINE_LEN: usize = 12;
20
21#[repr(C)]
22#[derive(Clone, Copy)]
23pub struct StrView {
24 len: u32,
25 prefix: [u8; 4],
26 tail: [u8; 8],
27}
28
29unsafe impl Pod for StrView {}
30
31const _: () = assert!(size_of::<StrView>() == 16);
32
33#[inline(always)]
43fn load_short(s: &[u8]) -> u64 {
44 let n = s.len();
45 debug_assert!(n <= 8, "one word holds eight bytes");
46 if n >= 4 {
47 let head = u32::from_le_bytes(s[..4].try_into().expect("four bytes")) as u64;
48 let tail = u32::from_le_bytes(s[n - 4..].try_into().expect("four bytes")) as u64;
49 let above = if n > 4 { tail >> ((8 - n) * 8) } else { 0 };
50 head | above << 32
51 } else if n > 0 {
52 u64::from(s[0]) | u64::from(s[n / 2]) << (n / 2 * 8) | u64::from(s[n - 1]) << ((n - 1) * 8)
53 } else {
54 0
55 }
56}
57
58impl StrView {
59 #[inline]
66 pub fn inline(bytes: &[u8]) -> Self {
67 let n = bytes.len();
68 debug_assert!(n <= INLINE_LEN);
69 let (lo, hi) = if n >= 8 {
70 let lo = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes"));
71 let tail = u32::from_le_bytes(bytes[n - 4..].try_into().expect("four bytes"));
72 (lo, if n > 8 { tail >> ((12 - n) * 8) } else { 0 })
73 } else {
74 (load_short(bytes), 0)
75 };
76 let w = lo.to_le_bytes();
77 let h = hi.to_le_bytes();
78 Self {
79 len: n as u32,
80 prefix: [w[0], w[1], w[2], w[3]],
81 tail: [w[4], w[5], w[6], w[7], h[0], h[1], h[2], h[3]],
82 }
83 }
84
85 pub fn long(bytes: &[u8], buffer: u16, offset: u32) -> Self {
89 debug_assert!(bytes.len() > INLINE_LEN);
90 let mut prefix = [0u8; 4];
91 prefix.copy_from_slice(&bytes[..4]);
92 let mut tail = [0u8; 8];
93 tail[..2].copy_from_slice(&buffer.to_le_bytes());
94 tail[2..6].copy_from_slice(&offset.to_le_bytes());
95 Self {
96 len: bytes.len() as u32,
97 prefix,
98 tail,
99 }
100 }
101
102 pub fn len(&self) -> usize {
103 self.len as usize
104 }
105
106 pub fn is_empty(&self) -> bool {
107 self.len == 0
108 }
109
110 pub fn is_inline(&self) -> bool {
111 self.len as usize <= INLINE_LEN
112 }
113
114 fn buffer_id(&self) -> u16 {
115 u16::from_le_bytes([self.tail[0], self.tail[1]])
116 }
117
118 fn offset(&self) -> u32 {
119 u32::from_le_bytes([self.tail[2], self.tail[3], self.tail[4], self.tail[5]])
120 }
121
122 pub fn inline_bytes(&self) -> &[u8] {
124 debug_assert!(self.is_inline());
125 let base = std::ptr::from_ref(self).cast::<u8>();
128 unsafe { std::slice::from_raw_parts(base.add(4), self.len as usize) }
129 }
130
131 pub fn bytes<'a>(&'a self, bufs: &'a StrBuffers) -> &'a [u8] {
134 if self.is_inline() {
135 self.inline_bytes()
136 } else {
137 bufs.slice(self.buffer_id(), self.offset(), self.len as usize)
138 }
139 }
140
141 pub fn sub(&self, bytes: &[u8], start: usize, len: usize) -> Self {
156 debug_assert!(start + len <= self.len());
157 let part = &bytes[start..start + len];
158 if len <= INLINE_LEN {
159 Self::inline(part)
160 } else {
161 Self::long(part, self.buffer_id(), self.offset() + start as u32)
162 }
163 }
164
165 pub fn eq_with(&self, a_bufs: &StrBuffers, other: &StrView, b_bufs: &StrBuffers) -> bool {
168 if self.len != other.len || self.prefix != other.prefix {
169 return false;
170 }
171 if self.is_inline() {
172 return self.tail == other.tail;
173 }
174 self.bytes(a_bufs) == other.bytes(b_bufs)
175 }
176}
177
178struct Buf {
188 ptr: *const u8,
189 len: usize,
190 _owner: Owner,
194}
195
196enum Owner {
198 Held(#[allow(dead_code)] Arc<[u8]>),
200 Lent(#[allow(dead_code)] Arc<dyn std::any::Any + Send + Sync>),
203}
204
205unsafe impl Send for Buf {}
210unsafe impl Sync for Buf {}
211
212#[derive(Default)]
216pub struct StrBuffers {
217 bufs: Vec<Buf>,
218}
219
220pub static NO_BUFFERS: StrBuffers = StrBuffers::empty();
224
225impl StrBuffers {
226 pub fn new() -> Self {
227 Self::default()
228 }
229
230 pub const fn empty() -> Self {
232 Self { bufs: Vec::new() }
233 }
234
235 pub fn push(&mut self, buf: Arc<[u8]>) -> u16 {
237 let (ptr, len) = (buf.as_ptr(), buf.len());
238 self.add(Buf {
239 ptr,
240 len,
241 _owner: Owner::Held(buf),
242 })
243 }
244
245 pub unsafe fn push_lent(
254 &mut self,
255 ptr: *const u8,
256 len: usize,
257 owner: Arc<dyn std::any::Any + Send + Sync>,
258 ) -> u16 {
259 self.add(Buf {
260 ptr,
261 len,
262 _owner: Owner::Lent(owner),
263 })
264 }
265
266 fn add(&mut self, buf: Buf) -> u16 {
267 let id = u16::try_from(self.bufs.len()).expect("string buffer count fits u16");
268 self.bufs.push(buf);
269 id
270 }
271
272 pub fn len(&self) -> usize {
275 self.bufs.len()
276 }
277
278 pub fn is_empty(&self) -> bool {
279 self.bufs.is_empty()
280 }
281
282 pub fn slice(&self, id: u16, offset: u32, len: usize) -> &[u8] {
283 let buf = &self.bufs[id as usize];
284 let start = offset as usize;
285 assert!(
290 start + len <= buf.len,
291 "string view {start}..{} runs past its {}-byte buffer",
292 start + len,
293 buf.len
294 );
295 unsafe { std::slice::from_raw_parts(buf.ptr.add(start), len) }
298 }
299}
300
301#[derive(Default)]
315pub struct StrBuilder {
316 long: Vec<u8>,
317}
318
319impl StrBuilder {
320 pub fn new() -> Self {
321 Self::default()
322 }
323
324 pub fn with_capacity(bytes: usize) -> Self {
329 Self {
330 long: Vec::with_capacity(bytes),
331 }
332 }
333
334 pub fn push_with(&mut self, len: usize, fill: impl FnOnce(&mut [u8])) -> StrView {
340 if len <= INLINE_LEN {
341 let mut inline = [0u8; INLINE_LEN];
342 fill(&mut inline[..len]);
343 StrView::inline(&inline[..len])
344 } else {
345 let start = self.long.len();
346 self.long.resize(start + len, 0);
347 fill(&mut self.long[start..]);
348 StrView::long(&self.long[start..], 0, start as u32)
350 }
351 }
352
353 pub fn push(&mut self, bytes: &[u8]) -> StrView {
355 self.push_with(bytes.len(), |dst| dst.copy_from_slice(bytes))
356 }
357
358 pub fn finish(self) -> StrBuffers {
361 let mut bufs = StrBuffers::new();
362 if !self.long.is_empty() {
363 bufs.push(Arc::from(self.long.into_boxed_slice()));
364 }
365 bufs
366 }
367}
368
369pub struct Dictionary {
373 bytes: Vec<u8>,
374 ends: Vec<u32>,
375}
376
377impl Dictionary {
378 pub fn from_sorted<I, B>(entries: I) -> Self
381 where
382 I: IntoIterator<Item = B>,
383 B: AsRef<[u8]>,
384 {
385 let mut bytes = Vec::new();
386 let mut ends = Vec::new();
387 for e in entries {
388 let e = e.as_ref();
389 debug_assert!(
390 ends.is_empty() || {
391 let start = if ends.len() == 1 {
392 0
393 } else {
394 ends[ends.len() - 2] as usize
395 };
396 let prev = &bytes[start..*ends.last().unwrap() as usize];
397 prev < e
398 },
399 "dictionary entries must be sorted and unique"
400 );
401 bytes.extend_from_slice(e);
402 ends.push(bytes.len() as u32);
403 }
404 Self { bytes, ends }
405 }
406
407 pub fn len(&self) -> usize {
408 self.ends.len()
409 }
410
411 pub fn is_empty(&self) -> bool {
412 self.ends.is_empty()
413 }
414
415 pub fn get(&self, code: u32) -> &[u8] {
416 let i = code as usize;
417 let start = if i == 0 { 0 } else { self.ends[i - 1] as usize };
418 &self.bytes[start..self.ends[i] as usize]
419 }
420
421 pub fn code_of(&self, needle: &[u8]) -> Result<u32, u32> {
425 let mut lo = 0usize;
426 let mut hi = self.len();
427 while lo < hi {
428 let mid = (lo + hi) / 2;
429 match self.get(mid as u32).cmp(needle) {
430 std::cmp::Ordering::Less => lo = mid + 1,
431 std::cmp::Ordering::Greater => hi = mid,
432 std::cmp::Ordering::Equal => return Ok(mid as u32),
433 }
434 }
435 Err(lo as u32)
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn inline_roundtrip() {
445 let bufs = StrBuffers::new();
446 for s in ["", "a", "abcd", "abcdefgh", "twelve chars"] {
447 let v = StrView::inline(s.as_bytes());
448 assert_eq!(v.bytes(&bufs), s.as_bytes(), "{s:?}");
449 }
450 }
451
452 #[test]
453 fn long_roundtrip_and_eq() {
454 let mut bufs = StrBuffers::new();
455 let payload: Arc<[u8]> =
456 Arc::from(&b"hello, this is a longer string sitting in a buffer"[..]);
457 let id = bufs.push(Arc::clone(&payload));
458 let a = StrView::long(&payload, id, 0);
459 assert_eq!(a.bytes(&bufs), &payload[..]);
460 let b = StrView::long(&payload, id, 0);
461 assert!(a.eq_with(&bufs, &b, &bufs));
462 let short = StrView::inline(b"hello");
463 assert!(!a.eq_with(&bufs, &short, &bufs));
464 }
465
466 #[test]
470 fn a_part_of_a_string_points_back_at_it() {
471 let mut bufs = StrBuffers::new();
472 let payload: Arc<[u8]> = Arc::from(&b" a string long enough to need a buffer "[..]);
473 let id = bufs.push(Arc::clone(&payload));
474 let whole = StrView::long(&payload, id, 0);
475 let bytes = whole.bytes(&bufs);
476 let inner = whole.sub(bytes, 2, payload.len() - 4);
477 assert!(!inner.is_inline());
478 assert_eq!(inner.bytes(&bufs), b"a string long enough to need a buffer");
479 let head = whole.sub(bytes, 2, 8);
480 assert!(head.is_inline(), "a short part carries its own bytes");
481 assert_eq!(head.bytes(&StrBuffers::new()), b"a string");
482 }
483
484 #[test]
485 fn prefix_rejects_before_buffer_touch() {
486 let mut bufs = StrBuffers::new();
487 let p1: Arc<[u8]> = Arc::from(&b"aaaaaaaaaaaaaaaaaaaa"[..]);
488 let p2: Arc<[u8]> = Arc::from(&b"bbbbbbbbbbbbbbbbbbbb"[..]);
489 let i1 = bufs.push(Arc::clone(&p1));
490 let i2 = bufs.push(Arc::clone(&p2));
491 let a = StrView::long(&p1, i1, 0);
492 let b = StrView::long(&p2, i2, 0);
493 assert!(!a.eq_with(&bufs, &b, &bufs));
494 }
495
496 #[test]
497 fn lent_bytes_read_where_they_lie() {
498 let outside: Arc<Vec<u8>> = Arc::new(b"a string long enough to need a buffer".to_vec());
502 let (ptr, len) = (outside.as_ptr(), outside.len());
503 let mut bufs = StrBuffers::new();
504 let id = unsafe { bufs.push_lent(ptr, len, Arc::clone(&outside) as Arc<_>) };
505 let view = StrView::long(&outside, id, 0);
506 assert_eq!(view.bytes(&bufs), &outside[..]);
507 assert_eq!(Arc::strong_count(&outside), 2);
510 drop(outside);
511 assert_eq!(view.bytes(&bufs), b"a string long enough to need a buffer");
512 }
513
514 #[test]
515 #[should_panic(expected = "runs past its")]
516 fn a_view_past_its_buffer_is_caught() {
517 let mut bufs = StrBuffers::new();
518 let id = bufs.push(Arc::from(&b"twenty bytes exactly"[..]));
519 bufs.slice(id, 16, 8);
520 }
521
522 #[test]
523 fn every_inline_length_round_trips() {
524 let all = b"abcdefghijkl";
527 for n in 0..=INLINE_LEN {
528 let want = &all[..n];
529 let view = StrView::inline(want);
530 assert_eq!(view.len(), n, "length of {n}");
531 assert_eq!(view.inline_bytes(), want, "bytes of {n}");
532 assert!(view.is_inline(), "{n} bytes should be inline");
533 assert!(view.eq_with(&NO_BUFFERS, &StrView::inline(want), &NO_BUFFERS));
536 }
537 }
538
539 #[test]
540 fn inline_views_of_different_lengths_stay_apart() {
541 let a = StrView::inline(b"abcdefgh");
542 let b = StrView::inline(b"abcdefghi");
543 assert!(!a.eq_with(&NO_BUFFERS, &b, &NO_BUFFERS));
544 assert_eq!(a.tail[4..], [0, 0, 0, 0]);
546 }
547
548 #[test]
549 fn dictionary_codes() {
550 let d = Dictionary::from_sorted(["apple", "banana", "cherry"]);
551 assert_eq!(d.code_of(b"banana"), Ok(1));
552 assert_eq!(d.code_of(b"blueberry"), Err(2));
553 assert_eq!(d.get(2), b"cherry");
554 }
555}