Debian Codegraph @

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

raw
1 use core::{marker::PhantomData, mem::MaybeUninit};
2
3 use crate::weak_slice::WeakSliceMut;
4
5 pub struct Pending<'a> {
6 /// start of the allocation
7 buf: WeakSliceMut<'a, MaybeUninit<u8>>,
8 /// next pending byte to output to the stream
9 out: usize,
10 /// number of bytes in the pending buffer
11 pub(crate) pending: usize,
12 /// semantically we're storing a mutable slice of bytes
13 _marker: PhantomData<&'a mut [u8]>,
14 }
15
16 impl<'a> Pending<'a> {
17 pub fn reset_keep(&mut self) {
18 // keep the buffer as it is
19 self.pending = 0;
20 }
21
22 pub fn pending(&self) -> &[u8] {
23 let slice = &self.buf.as_slice()[self.out..][..self.pending];
24 // SAFETY: the slice contains initialized bytes.
25 unsafe { &*(slice as *const [MaybeUninit<u8>] as *const [u8]) }
26 }
27
28 /// Number of bytes that can be added to the pending buffer until it is full
29 pub(crate) fn remaining(&self) -> usize {
30 self.buf.len() - (self.out + self.pending)
31 }
32
33 /// Total number of bytes that can be stored in the pending buffer
34 pub(crate) fn capacity(&self) -> usize {
35 self.buf.len()
36 }
37
38 #[inline(always)]
39 #[track_caller]
40 /// Mark a number of pending bytes as no longer pending
41 pub fn advance(&mut self, number_of_bytes: usize) {
42 debug_assert!(self.pending >= number_of_bytes);
43
44 self.out = self.out.wrapping_add(number_of_bytes);
45 self.pending -= number_of_bytes;
46
47 if self.pending == 0 {
48 self.out = 0;
49 }
50 }
51
52 #[inline(always)]
53 #[track_caller]
54 pub fn rewind(&mut self, n: usize) {
55 assert!(n <= self.pending, "rewinding past then start");
56
57 self.pending -= n;
58
59 if self.pending == 0 {
60 self.out = 0;
61 }
62 }
63
64 #[inline(always)]
65 #[track_caller]
66 pub fn extend(&mut self, buf: &[u8]) {
67 assert!(
68 self.remaining() >= buf.len(),
69 "buf.len() must fit in remaining()"
70 );
71
72 // SAFETY: [u8] is valid [MaybeUninit<u8>]
73 let buf = unsafe { &*(buf as *const [u8] as *const [MaybeUninit<u8>]) };
74
75 self.buf.as_mut_slice()[self.out + self.pending..][..buf.len()].copy_from_slice(buf);
76
77 self.pending += buf.len();
78 }
79
80 pub(crate) unsafe fn from_raw_parts(ptr: *mut MaybeUninit<u8>, len: usize) -> Self {
81 let buf = unsafe { WeakSliceMut::from_raw_parts_mut(ptr, len) };
82
83 Self {
84 buf,
85 out: 0,
86 pending: 0,
87 _marker: PhantomData,
88 }
89 }
90
91 pub(crate) unsafe fn clone_to(&self, ptr: *mut u8) -> Self {
92 let ptr = ptr.cast::<MaybeUninit<u8>>();
93 unsafe { ptr.copy_from_nonoverlapping(self.buf.as_ptr(), self.buf.len()) };
94 Self {
95 buf: unsafe { WeakSliceMut::from_raw_parts_mut(ptr, self.buf.len()) },
96 out: self.out,
97 pending: self.pending,
98 _marker: PhantomData,
99 }
100 }
101 }