Debian Codegraph @

debian/rust-vendor/zlib-rs/src/inflate/writer.rs

raw
1 use core::fmt;
2 use core::mem::MaybeUninit;
3 use core::ops::Range;
4
5 use crate::cpu_features::CpuFeatures;
6 use crate::weak_slice::WeakSliceMut;
7
8 pub struct Writer<'a> {
9 buf: WeakSliceMut<'a, MaybeUninit<u8>>,
10 filled: usize,
11 }
12
13 impl<'a> Writer<'a> {
14 /// Creates a new `Writer` from a fully initialized buffer.
15 #[inline]
16 pub fn new(buf: &'a mut [u8]) -> Writer<'a> {
17 // SAFETY: Because buf is a slice, most of the preconditions for
18 // core::slice::from_raw_parts_mut are satisfied:
19 // * buf.as_mut_ptr() is non-null.
20 // * The memory range is within a single allocated object.
21 // * buf is mutable, so the range is valid for both reads
22 // and writes of up to buf.len() * size_of::<u8>() bytes.
23 // * The contents of the slice are initialized.
24 // * buf.as_mut_ptr() + buf.len() does not wrap around
25 // the end of the address space.
26 // The remaining precondition is enforced by the borrow checker when this function is called:
27 // * The memory range cannot be accessed through any other pointer for the
28 // duration of lifetime 'a.
29 unsafe { Self::new_uninit(buf.as_mut_ptr(), buf.len()) }
30 }
31
32 /// Creates a new `Writer` from an uninitialized buffer.
33 ///
34 /// # Safety
35 ///
36 /// The arguments must satisfy the requirements of [`core::slice::from_raw_parts_mut`].
37 #[inline]
38 pub unsafe fn new_uninit(ptr: *mut u8, len: usize) -> Writer<'a> {
39 // SAFETY: The preconditions for WeakSliceMut::from_raw_parts_mut are the same
40 // as for core::slice::from_raw_parts_mut, and the caller is responsible for
41 // ensuring the latter.
42 let buf = unsafe { WeakSliceMut::from_raw_parts_mut(ptr as *mut MaybeUninit<u8>, len) };
43 Writer { buf, filled: 0 }
44 }
45
46 #[inline]
47 pub unsafe fn new_uninit_raw(ptr: *mut u8, len: usize, capacity: usize) -> Writer<'a> {
48 let buf =
49 unsafe { WeakSliceMut::from_raw_parts_mut(ptr as *mut MaybeUninit<u8>, capacity) };
50 Writer { buf, filled: len }
51 }
52
53 /// Pointer to where the next byte will be written
54 #[inline]
55 pub fn next_out(&mut self) -> *mut MaybeUninit<u8> {
56 self.buf.as_mut_ptr().wrapping_add(self.filled).cast()
57 }
58
59 /// Returns the total capacity of the buffer.
60 #[inline]
61 pub fn capacity(&self) -> usize {
62 self.buf.len()
63 }
64
65 /// Returns the length of the filled part of the buffer
66 #[inline]
67 pub fn len(&self) -> usize {
68 self.filled
69 }
70
71 /// Returns a shared reference to the filled portion of the buffer.
72 #[inline]
73 pub fn filled(&self) -> &[u8] {
74 // SAFETY: the filled area of the buffer is always initialized, and self.filled is always
75 // in-bounds.
76 unsafe { core::slice::from_raw_parts(self.buf.as_ptr().cast(), self.filled) }
77 }
78
79 /// Returns the number of bytes at the end of the slice that have not yet been filled.
80 #[inline]
81 pub fn remaining(&self) -> usize {
82 self.capacity() - self.filled
83 }
84
85 #[inline]
86 pub fn is_full(&self) -> bool {
87 self.filled == self.buf.len()
88 }
89
90 pub fn push(&mut self, byte: u8) {
91 self.buf.as_mut_slice()[self.filled] = MaybeUninit::new(byte);
92
93 self.filled += 1;
94 }
95
96 /// Appends data to the buffer
97 #[inline(always)]
98 pub fn extend(&mut self, buf: &[u8]) {
99 // using simd here (on x86_64) was not fruitful
100 self.buf.as_mut_slice()[self.filled..][..buf.len()].copy_from_slice(slice_to_uninit(buf));
101
102 self.filled += buf.len();
103 }
104
105 #[inline(always)]
106 pub fn extend_from_window(&mut self, window: &super::window::Window, range: Range<usize>) {
107 self.extend_from_window_with_features::<{ CpuFeatures::NONE }>(window, range)
108 }
109
110 pub fn extend_from_window_with_features<const FEATURES: usize>(
111 &mut self,
112 window: &super::window::Window,
113 range: Range<usize>,
114 ) {
115 match FEATURES {
116 #[cfg(target_arch = "x86_64")]
117 CpuFeatures::AVX2 => self.extend_from_window_help::<32>(window, range),
118 _ => self.extend_from_window_runtime_dispatch(window, range),
119 }
120 }
121
122 fn extend_from_window_runtime_dispatch(
123 &mut self,
124 window: &super::window::Window,
125 range: Range<usize>,
126 ) {
127 // NOTE: the dynamic check for avx512 makes avx2 slower. Measure this carefully before re-enabling
128 //
129 // #[cfg(target_arch = "x86_64")]
130 // if crate::cpu_features::is_enabled_avx512() {
131 // return self.extend_from_window_help::<64>(window, range);
132 // }
133
134 #[cfg(target_arch = "x86_64")]
135 if crate::cpu_features::is_enabled_avx2_and_bmi2() {
136 return self.extend_from_window_help::<32>(window, range);
137 }
138
139 #[cfg(target_arch = "x86_64")]
140 if crate::cpu_features::is_enabled_sse() {
141 return self.extend_from_window_help::<16>(window, range);
142 }
143
144 #[cfg(target_arch = "aarch64")]
145 if crate::cpu_features::is_enabled_neon() {
146 return self.extend_from_window_help::<16>(window, range);
147 }
148
149 #[cfg(all(target_arch = "loongarch64", feature = "lsx"))]
150 if crate::cpu_features::is_enabled_lsx() {
151 return self.extend_from_window_help::<16>(window, range);
152 }
153
154 #[cfg(target_arch = "wasm32")]
155 if crate::cpu_features::is_enabled_simd128() {
156 return self.extend_from_window_help::<16>(window, range);
157 }
158
159 self.extend_from_window_help::<8>(window, range)
160 }
161
162 #[inline(always)]
163 fn extend_from_window_help<const N: usize>(
164 &mut self,
165 window: &super::window::Window,
166 range: Range<usize>,
167 ) {
168 let len = range.end - range.start;
169
170 if self.remaining() >= len + N {
171 // SAFETY: we know that our window has at least a N extra bytes
172 // at the end, making it always safe to perform an (unaligned) Chunk read anywhere in
173 // the window slice.
174 //
175 // The calling function checks for CPU features requirements for C.
176 unsafe {
177 let src = window.as_ptr();
178 Self::copy_chunk_unchecked::<N>(
179 src.wrapping_add(range.start).cast(),
180 self.next_out(),
181 len,
182 )
183 }
184 } else {
185 let buf = &window.as_slice()[range];
186 self.buf.as_mut_slice()[self.filled..][..buf.len()]
187 .copy_from_slice(slice_to_uninit(buf));
188 }
189
190 self.filled += len;
191 }
192
193 /// Variant of `extend_from_window` used with `inflateBack`. It does not attempt a chunked
194 /// copy, because there is no padding at the end and the window and output buffer alias.
195 /// So a standard `memmove` will have to do.
196 #[inline(always)]
197 pub fn extend_from_window_back(&mut self, window: &super::window::Window, range: Range<usize>) {
198 let len = range.end - range.start;
199
200 unsafe {
201 core::ptr::copy(
202 window.as_ptr().add(range.start),
203 self.buf.as_mut_ptr().add(self.filled).cast(),
204 len,
205 );
206 }
207
208 self.filled += len;
209 }
210
211 #[inline(always)]
212 pub fn copy_match(&mut self, offset_from_end: usize, length: usize) {
213 self.copy_match_with_features::<{ CpuFeatures::NONE }>(offset_from_end, length)
214 }
215
216 #[inline(always)]
217 pub fn copy_match_with_features<const FEATURES: usize>(
218 &mut self,
219 offset_from_end: usize,
220 length: usize,
221 ) {
222 match FEATURES {
223 #[cfg(target_arch = "x86_64")]
224 CpuFeatures::AVX2 => self.copy_match_help::<32>(offset_from_end, length),
225 _ => self.copy_match_runtime_dispatch(offset_from_end, length),
226 }
227 }
228
229 fn copy_match_runtime_dispatch(&mut self, offset_from_end: usize, length: usize) {
230 // NOTE: the dynamic check for avx512 makes avx2 slower. Measure this carefully before re-enabling
231 //
232 // #[cfg(target_arch = "x86_64")]
233 // if crate::cpu_features::is_enabled_avx512() {
234 // return self.copy_match_help::<core::arch::x86_64::__m512i>(offset_from_end, length);
235 // }
236
237 #[cfg(target_arch = "x86_64")]
238 if crate::cpu_features::is_enabled_avx2_and_bmi2() {
239 return self.copy_match_help::<32>(offset_from_end, length);
240 }
241
242 #[cfg(target_arch = "x86_64")]
243 if crate::cpu_features::is_enabled_sse() {
244 return self.copy_match_help::<16>(offset_from_end, length);
245 }
246
247 #[cfg(target_arch = "aarch64")]
248 if crate::cpu_features::is_enabled_neon() {
249 return self.copy_match_help::<16>(offset_from_end, length);
250 }
251
252 #[cfg(all(target_arch = "loongarch64", feature = "lsx"))]
253 if crate::cpu_features::is_enabled_lsx() {
254 return self.copy_match_help::<16>(offset_from_end, length);
255 }
256
257 #[cfg(target_arch = "wasm32")]
258 if crate::cpu_features::is_enabled_simd128() {
259 return self.copy_match_help::<16>(offset_from_end, length);
260 }
261
262 self.copy_match_help::<8>(offset_from_end, length)
263 }
264
265 #[inline(always)]
266 fn copy_match_help<const N: usize>(&mut self, offset_from_end: usize, length: usize) {
267 let capacity = self.buf.len();
268 let len = Ord::min(self.filled + length + N, capacity);
269 let buf = &mut self.buf.as_mut_slice()[..len];
270
271 let current = self.filled;
272 self.filled += length;
273
274 // Note also that the referenced string may overlap the current
275 // position; for example, if the last 2 bytes decoded have values
276 // X and Y, a string reference with <length = 5, distance = 2>
277 // adds X,Y,X,Y,X to the output stream.
278
279 if length > offset_from_end {
280 match offset_from_end {
281 1 => {
282 // this will just repeat this value many times
283 let element = buf[current - 1];
284 buf[current..][..length].fill(element);
285 }
286 _ => {
287 // there is a SIMD implementation of this logic, which _should_ be faster, but
288 // isn't in measurements on x86_64. It still might be for other architectures,
289 // adds a lot of complexity and unsafe code.
290 for i in 0..length {
291 buf[current + i] = buf[current - offset_from_end + i];
292 }
293 }
294 }
295 } else {
296 Self::copy_chunked_within::<N>(buf, capacity, current, offset_from_end, length);
297 }
298 }
299
300 /// Variant of `copy_match` used with `inflateBack`. It does not attempt a chunked
301 /// copy, because there is no padding at the end.
302 #[inline(always)]
303 pub fn copy_match_back(&mut self, offset_from_end: usize, length: usize) {
304 let capacity = self.buf.len();
305 let len = Ord::min(self.filled + length, capacity);
306 let buf = &mut self.buf.as_mut_slice()[..len];
307
308 let current = self.filled;
309 self.filled += length;
310
311 // Note also that the referenced string may overlap the current
312 // position; for example, if the last 2 bytes decoded have values
313 // X and Y, a string reference with <length = 5, distance = 2>
314 // adds X,Y,X,Y,X to the output stream.
315
316 match offset_from_end {
317 1 => {
318 // this will just repeat this value many times
319 let element = buf[current - 1];
320 buf[current..][..length].fill(element);
321 }
322 _ => {
323 for i in 0..length {
324 buf[current + i] = buf[current - offset_from_end + i];
325 }
326 }
327 }
328 }
329
330 #[inline(always)]
331 fn copy_chunked_within<const N: usize>(
332 buf: &mut [MaybeUninit<u8>],
333 capacity: usize,
334 current: usize,
335 offset_from_end: usize,
336 length: usize,
337 ) {
338 let start = current.checked_sub(offset_from_end).expect("in bounds");
339
340 if current + length + N < capacity {
341 let ptr = buf.as_mut_ptr();
342 // SAFETY: if statement and checked_sub ensures we stay in bounds.
343 unsafe { Self::copy_chunk_unchecked::<N>(ptr.add(start), ptr.add(current), length) }
344 } else {
345 // a full simd copy does not fit in the output buffer
346 buf.copy_within(start..start + length, current);
347 }
348 }
349
350 /// # Safety
351 ///
352 /// `src..src + length` must be safe to perform reads in chunks of N elements until
353 /// `src + length` is reached. `dst` must be safe to (unaligned) write that number of chunks.
354 #[inline(always)]
355 unsafe fn copy_chunk_unchecked<const N: usize>(
356 mut src: *const MaybeUninit<u8>,
357 mut dst: *mut MaybeUninit<u8>,
358 length: usize,
359 ) {
360 if length == 0 {
361 return;
362 }
363
364 // SAFETY: The caller ensured that src + length is within (or just at the end of)
365 // a readable range of bytes. LLVM disallows allocations bigger than isize::MAX,
366 // so if src..src+length is a valid allocation (a precondition of this function)
367 // the length will never exceed isize::MAX.
368 let end = unsafe { src.add(length) };
369
370 // SAFETY: We checked above that length != 0, so there is at least one chunk remaining.
371 let chunk = unsafe { load_chunk::<N>(src) };
372 unsafe { store_chunk::<N>(dst, chunk) };
373
374 // SAFETY: src and dest haven't been modified yet, and we checked above that
375 // length != 0, so adding one chunk (N bytes) to both src and dst will result in
376 // a pointer in (or just at the end of) each of the underlying buffers.
377 src = unsafe { src.add(N) };
378 dst = unsafe { dst.add(N) };
379
380 while src < end {
381 // SAFETY: The caller ensured that src and dst contain enough bytes to support
382 // reads (from src) or writes (to dst) up to and including the chunk that contains
383 // end. Note that, if length is not a multiple of N, we will copy up to N-1 bytes
384 // past end.
385 let chunk = unsafe { load_chunk::<N>(src) };
386 unsafe { store_chunk::<N>(dst, chunk) };
387
388 // SAFETY: Because src is currently < end, we have at least one more chunk available
389 // to copy, so there is room to advance the pointers by N within both the src and
390 // dst bufs.
391 src = unsafe { src.add(N) };
392 dst = unsafe { dst.add(N) };
393 }
394 }
395 }
396
397 /// # Safety
398 ///
399 /// Must be valid to read a `[u8; N]` value from `from` with an unaligned read.
400 #[inline(always)]
401 unsafe fn load_chunk<const N: usize>(from: *const MaybeUninit<u8>) -> [MaybeUninit<u8>; N] {
402 // SAFETY: Checked by the caller.
403 unsafe { core::ptr::read_unaligned(from.cast::<[MaybeUninit<u8>; N]>()) }
404 }
405
406 /// # Safety
407 ///
408 /// Must be valid to write a `[u8; N]` value to `out` with an unaligned write.
409 #[inline(always)]
410 unsafe fn store_chunk<const N: usize>(out: *mut MaybeUninit<u8>, chunk: [MaybeUninit<u8>; N]) {
411 // SAFETY: checked by the caller.
412 unsafe { core::ptr::write_unaligned(out.cast(), chunk) }
413 }
414
415 impl fmt::Debug for Writer<'_> {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 f.debug_struct("Writer")
418 .field("ptr", &self.buf.as_ptr())
419 .field("filled", &self.filled)
420 .field("capacity", &self.capacity())
421 .finish()
422 }
423 }
424
425 fn slice_to_uninit(slice: &[u8]) -> &[MaybeUninit<u8>] {
426 unsafe { &*(slice as *const [u8] as *const [MaybeUninit<u8>]) }
427 }
428
429 #[cfg(test)]
430 mod test {
431 use super::*;
432
433 const N: usize = 128;
434 const M: usize = 64;
435
436 fn test_array() -> [MaybeUninit<u8>; N] {
437 core::array::from_fn(|i| MaybeUninit::new(if i < M { i as u8 } else { 0xAAu8 }))
438 }
439
440 fn test_copy_match(offset_from_end: usize, length: usize) {
441 let mut buf = test_array();
442 let mut writer = Writer {
443 buf: unsafe { WeakSliceMut::from_raw_parts_mut(buf.as_mut_ptr(), buf.len()) },
444 filled: M,
445 };
446 writer.copy_match(offset_from_end, length);
447 assert_eq!(writer.filled, M + length);
448
449 let mut naive = test_array();
450 for i in 0..length {
451 naive[M + i] = naive[M - offset_from_end + i];
452 }
453
454 let buf = unsafe { core::mem::transmute::<[MaybeUninit<u8>; 128], [u8; N]>(buf) };
455 let naive = unsafe { core::mem::transmute::<[MaybeUninit<u8>; 128], [u8; N]>(naive) };
456 assert_eq!(
457 buf[M..][..length],
458 naive[M..][..length],
459 "{offset_from_end} {length}"
460 );
461 }
462
463 #[test]
464 fn copy_chunk_unchecked() {
465 let offset_from_end = 17;
466 let length = 17;
467
468 macro_rules! helper {
469 ($func:expr) => {
470 let mut buf = test_array();
471 let mut writer = Writer {
472 buf: unsafe { WeakSliceMut::from_raw_parts_mut(buf.as_mut_ptr(), buf.len()) },
473 filled: M,
474 };
475
476 $func(&mut writer, offset_from_end, length);
477 };
478 }
479
480 #[cfg(target_arch = "x86_64")]
481 if crate::cpu_features::is_enabled_avx512() {
482 helper!(Writer::copy_match_help::<64>);
483 }
484
485 #[cfg(target_arch = "x86_64")]
486 if crate::cpu_features::is_enabled_avx2_and_bmi2() {
487 helper!(Writer::copy_match_help::<32>);
488 }
489
490 #[cfg(target_arch = "x86_64")]
491 if crate::cpu_features::is_enabled_sse() {
492 helper!(Writer::copy_match_help::<16>);
493 }
494
495 #[cfg(target_arch = "aarch64")]
496 if crate::cpu_features::is_enabled_neon() {
497 helper!(Writer::copy_match_help::<16>);
498 }
499
500 #[cfg(all(target_arch = "loongarch64", feature = "lsx"))]
501 if crate::cpu_features::is_enabled_lsx() {
502 helper!(Writer::copy_match_help::<16>);
503 }
504
505 #[cfg(target_arch = "wasm32")]
506 if crate::cpu_features::is_enabled_simd128() {
507 helper!(Writer::copy_match_help::<16>);
508 }
509
510 helper!(Writer::copy_match_help::<8>);
511 }
512
513 #[test]
514 #[cfg_attr(miri, ignore = "slow")]
515 fn copy_match() {
516 for offset_from_end in 1..=64 {
517 for length in 0..=64 {
518 test_copy_match(offset_from_end, length)
519 }
520 }
521 }
522
523 #[test]
524 fn copy_match_insufficient_space_for_simd() {
525 let mut buf = [1, 2, 3, 0xAA, 0xAA].map(MaybeUninit::new);
526 let mut writer = Writer {
527 buf: unsafe { WeakSliceMut::from_raw_parts_mut(buf.as_mut_ptr(), buf.len()) },
528 filled: 3,
529 };
530
531 writer.copy_match(3, 2);
532
533 assert_eq!(buf.map(|e| unsafe { e.assume_init() }), [1, 2, 3, 1, 2]);
534 }
535 }