Debian Codegraph @

debian/rust-vendor/zlib-rs/src/deflate/sym_buf.rs

raw
1 // taken from https://docs.rs/tokio/latest/src/tokio/io/read_buf.rs.html#23-27
2 // based on https://rust-lang.github.io/rfcs/2930-read-buf.html
3
4 use crate::weak_slice::WeakSliceMut;
5
6 pub(crate) struct SymBuf<'a> {
7 buf: WeakSliceMut<'a, u8>,
8 filled: usize,
9 }
10
11 impl<'a> SymBuf<'a> {
12 #[inline]
13 pub fn iter(&self) -> impl Iterator<Item = (u16, u8)> + '_ {
14 self.buf.as_slice()[..self.filled]
15 .chunks_exact(3)
16 .map(|chunk| match *chunk {
17 [dist_low, dist_high, lc] => (u16::from_le_bytes([dist_low, dist_high]), lc),
18 _ => unreachable!("chunks are exactly 3 elements wide"),
19 })
20 }
21
22 #[inline]
23 pub fn should_flush_block(&self) -> bool {
24 self.filled == self.buf.len() - 3
25 }
26
27 /// Returns true if there are no bytes in this ReadBuf
28 #[inline]
29 pub fn is_empty(&self) -> bool {
30 self.filled == 0
31 }
32
33 /// Clears the buffer, resetting the filled region to empty.
34 ///
35 /// The number of initialized bytes is not changed, and the contents of the buffer are not modified.
36 #[inline]
37 pub fn clear(&mut self) {
38 self.buf.as_mut_slice().fill(0);
39 self.filled = 0;
40 }
41
42 #[inline(always)]
43 pub fn push_lit(&mut self, byte: u8) {
44 // NOTE: we rely on the buffer being zeroed here!
45 self.buf.as_mut_slice()[self.filled + 2] = byte;
46
47 self.filled += 3;
48 }
49
50 #[inline(always)]
51 pub fn push_dist(&mut self, dist: u16, len: u8) {
52 let buf = &mut self.buf.as_mut_slice()[self.filled..][..3];
53
54 // Write both dist bytes as a single 2-byte store. This avoids the
55 // `movb %ch, [mem]` instruction pattern (store from high-byte register
56 // alias) that LLVM otherwise emits when dist arrives as a wide register.
57 // That pattern triggers the Intel Raptor Lake CPU errata, causing silent
58 // 2-byte stores that corrupt the adjacent `len` byte.
59 // SAFETY: buf has at least 3 bytes (guaranteed above), so the unaligned
60 // 2-byte write at offset 0 stays within bounds.
61 unsafe {
62 core::ptr::write_unaligned(buf.as_mut_ptr().cast::<[u8; 2]>(), dist.to_le_bytes())
63 };
64 buf[2] = len;
65
66 self.filled += 3;
67 }
68
69 pub(crate) unsafe fn from_raw_parts(ptr: *mut u8, lit_bufsize: usize) -> Self {
70 Self {
71 buf: unsafe { WeakSliceMut::from_raw_parts_mut(ptr, lit_bufsize * 3) },
72 filled: 0,
73 }
74 }
75
76 pub(crate) unsafe fn clone_to(&self, ptr: *mut u8) -> Self {
77 unsafe { ptr.copy_from_nonoverlapping(self.buf.as_ptr(), self.buf.len()) };
78 Self {
79 buf: unsafe { WeakSliceMut::from_raw_parts_mut(ptr, self.buf.len()) },
80 filled: self.filled,
81 }
82 }
83 }