Debian Codegraph @

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