compcol 0.5.0

A no_std collection of compression algorithms behind a uniform streaming trait, gated per-algorithm by Cargo features.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Async `tokio::io::AsyncRead` / `AsyncWrite` adapters.
//!
//! Mirrors the four blocking adapters in [`crate::io`] for the tokio
//! runtime. Same model, same constructor shape, same `finish` /
//! `into_inner` / `get_ref` accessors; only the trait bounds change.
//!
//! Gated on the new `tokio` Cargo feature, which itself pulls in
//! `std`. Adds a single optional dependency on the `tokio` crate
//! (default-features off, just the trait definitions are needed).
//!
//! ```ignore
//! use tokio::io::{AsyncReadExt, AsyncWriteExt};
//! use compcol::{Algorithm, gzip::Gzip};
//! use compcol::tokio_io::{EncoderWriter, DecoderReader};
//!
//! # async fn ex(file: tokio::fs::File, src: tokio::fs::File) -> std::io::Result<()> {
//! let mut w = EncoderWriter::new(file, Gzip::encoder());
//! w.write_all(b"hello, async gzip\n").await?;
//! let _file = w.shutdown_into_inner().await?;
//!
//! let mut r = DecoderReader::new(src, Gzip::decoder());
//! let mut bytes = Vec::new();
//! r.read_to_end(&mut bytes).await?;
//! # Ok(())
//! # }
//! ```

extern crate alloc;
extern crate std;

use alloc::vec;
use alloc::vec::Vec;
use core::pin::Pin;
use core::task::{Context, Poll};
use std::io;

use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};

use crate::{Decoder, Encoder, Error, Status};

const SCRATCH: usize = 64 * 1024;

// Shared `?`-style helper for Poll<io::Result<T>>.
macro_rules! ready_poll {
    ($e:expr) => {
        match $e {
            Poll::Ready(v) => v,
            Poll::Pending => return Poll::Pending,
        }
    };
}

// ─── EncoderWriter ──────────────────────────────────────────────────────

/// Async dual of [`crate::io::EncoderWriter`]. Wraps a
/// `W: AsyncWrite + Unpin` and exposes `AsyncWrite` itself: bytes you
/// write are compressed and forwarded to the inner.
///
/// Call [`shutdown_into_inner`](Self::shutdown_into_inner) to flush the
/// encoder's tail bytes and recover the inner writer. The standard
/// `AsyncWrite::poll_shutdown` does the flush but doesn't return the
/// inner — for the typical "compress to a file, then keep the handle"
/// flow, prefer `shutdown_into_inner`.
pub struct EncoderWriter<W: AsyncWrite + Unpin, E: Encoder + Unpin> {
    enc: E,
    inner: W,
    scratch: Vec<u8>,
    /// Encoded bytes waiting to be flushed to `inner`. `out_pos..out.len()`
    /// is the unwritten slice. Cleared once fully written.
    out: Vec<u8>,
    out_pos: usize,
    /// Position within the encoder's `finish` drain state during shutdown.
    finished: bool,
}

impl<W: AsyncWrite + Unpin, E: Encoder + Unpin> EncoderWriter<W, E> {
    /// Wrap `inner` with a caller-supplied encoder.
    pub fn new(inner: W, enc: E) -> Self {
        Self {
            enc,
            inner,
            scratch: vec![0u8; SCRATCH],
            out: Vec::with_capacity(SCRATCH),
            out_pos: 0,
            finished: false,
        }
    }

    pub fn get_ref(&self) -> &W {
        &self.inner
    }
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.inner
    }

    /// Drain encoded tail bytes into `inner` and recover the inner writer.
    ///
    /// Async equivalent of the sync
    /// [`crate::io::EncoderWriter::finish`]. Calls `poll_shutdown` to
    /// completion, then returns ownership of `inner`.
    pub async fn shutdown_into_inner(mut self) -> io::Result<W> {
        // We call poll_shutdown directly via poll_fn so this works
        // without bringing the `tokio = ["io-util"]` extension trait
        // into the dep set.
        core::future::poll_fn(|cx| Pin::new(&mut self).poll_shutdown(cx)).await?;
        Ok(self.inner)
    }

    /// Best-effort sync drain used by both `poll_write` and `poll_shutdown`
    /// to push `self.out` out before doing more work.
    fn drain_out(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        while self.out_pos < self.out.len() {
            let n =
                ready_poll!(Pin::new(&mut self.inner).poll_write(cx, &self.out[self.out_pos..]))?;
            if n == 0 {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "inner returned 0 from poll_write",
                )));
            }
            self.out_pos += n;
        }
        self.out.clear();
        self.out_pos = 0;
        Poll::Ready(Ok(()))
    }
}

impl<W: AsyncWrite + Unpin, E: Encoder + Unpin> AsyncWrite for EncoderWriter<W, E> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let me = Pin::into_inner(self);
        if me.finished {
            return Poll::Ready(Err(io::Error::other("encoder writer already finished")));
        }
        // First, push any previously-encoded bytes out.
        ready_poll!(me.drain_out(cx))?;
        // Encode some of buf into scratch, stage in `out`. We don't
        // necessarily fully consume buf — a small encode call is fine,
        // tokio callers will simply re-poll.
        let (p, _status) = me.enc.encode(buf, &mut me.scratch)?;
        me.out.extend_from_slice(&me.scratch[..p.written]);
        Poll::Ready(Ok(p.consumed))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        ready_poll!(me.drain_out(cx))?;
        Pin::new(&mut me.inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        // Drain whatever's already staged.
        ready_poll!(me.drain_out(cx))?;
        // Drive enc.finish until StreamEnd, staging into `out` as we go.
        while !me.finished {
            let (p, status) = me.enc.finish(&mut me.scratch)?;
            me.out.extend_from_slice(&me.scratch[..p.written]);
            ready_poll!(me.drain_out(cx))?;
            if matches!(status, Status::StreamEnd) {
                me.finished = true;
            } else if p.written == 0 {
                return Poll::Ready(Err(io::Error::other("encoder stalled in finish")));
            }
        }
        Pin::new(&mut me.inner).poll_shutdown(cx)
    }
}

// ─── DecoderWriter ──────────────────────────────────────────────────────

/// Async dual of [`crate::io::DecoderWriter`]: you write *compressed*
/// bytes, the wrapped `W` receives the decoded plaintext.
pub struct DecoderWriter<W: AsyncWrite + Unpin, D: Decoder + Unpin> {
    dec: D,
    inner: W,
    scratch: Vec<u8>,
    out: Vec<u8>,
    out_pos: usize,
    finished: bool,
}

impl<W: AsyncWrite + Unpin, D: Decoder + Unpin> DecoderWriter<W, D> {
    pub fn new(inner: W, dec: D) -> Self {
        Self {
            dec,
            inner,
            scratch: vec![0u8; SCRATCH],
            out: Vec::with_capacity(SCRATCH),
            out_pos: 0,
            finished: false,
        }
    }

    pub fn get_ref(&self) -> &W {
        &self.inner
    }
    pub fn get_mut(&mut self) -> &mut W {
        &mut self.inner
    }

    pub async fn shutdown_into_inner(mut self) -> io::Result<W> {
        core::future::poll_fn(|cx| Pin::new(&mut self).poll_shutdown(cx)).await?;
        Ok(self.inner)
    }

    fn drain_out(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        while self.out_pos < self.out.len() {
            let n =
                ready_poll!(Pin::new(&mut self.inner).poll_write(cx, &self.out[self.out_pos..]))?;
            if n == 0 {
                return Poll::Ready(Err(io::Error::new(
                    io::ErrorKind::WriteZero,
                    "inner returned 0 from poll_write",
                )));
            }
            self.out_pos += n;
        }
        self.out.clear();
        self.out_pos = 0;
        Poll::Ready(Ok(()))
    }
}

impl<W: AsyncWrite + Unpin, D: Decoder + Unpin> AsyncWrite for DecoderWriter<W, D> {
    fn poll_write(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        let me = Pin::into_inner(self);
        if me.finished {
            return Poll::Ready(Err(io::Error::other("decoder writer already finished")));
        }
        ready_poll!(me.drain_out(cx))?;
        let (p, _status) = me.dec.decode(buf, &mut me.scratch)?;
        me.out.extend_from_slice(&me.scratch[..p.written]);
        Poll::Ready(Ok(p.consumed))
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        ready_poll!(me.drain_out(cx))?;
        Pin::new(&mut me.inner).poll_flush(cx)
    }

    fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        ready_poll!(me.drain_out(cx))?;
        while !me.finished {
            let (p, status) = me.dec.finish(&mut me.scratch)?;
            me.out.extend_from_slice(&me.scratch[..p.written]);
            ready_poll!(me.drain_out(cx))?;
            if matches!(status, Status::StreamEnd) {
                me.finished = true;
            } else if p.written == 0 {
                return Poll::Ready(Err(io::Error::other("decoder stalled in finish")));
            }
        }
        Pin::new(&mut me.inner).poll_shutdown(cx)
    }
}

// ─── EncoderReader ──────────────────────────────────────────────────────

/// Async dual of [`crate::io::EncoderReader`]: you read *compressed*
/// bytes; plaintext is pulled lazily from the wrapped `R`.
pub struct EncoderReader<R: AsyncRead + Unpin, E: Encoder + Unpin> {
    enc: E,
    inner: R,
    in_buf: Vec<u8>,
    in_filled: usize,
    in_consumed: usize,
    inner_eof: bool,
    finished: bool,
}

impl<R: AsyncRead + Unpin, E: Encoder + Unpin> EncoderReader<R, E> {
    pub fn new(inner: R, enc: E) -> Self {
        Self {
            enc,
            inner,
            in_buf: vec![0u8; SCRATCH],
            in_filled: 0,
            in_consumed: 0,
            inner_eof: false,
            finished: false,
        }
    }

    pub fn get_ref(&self) -> &R {
        &self.inner
    }
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: AsyncRead + Unpin, E: Encoder + Unpin> AsyncRead for EncoderReader<R, E> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        loop {
            if me.finished {
                return Poll::Ready(Ok(()));
            }
            // Drive plaintext through encode() into the caller's buf.
            if me.in_consumed < me.in_filled {
                let avail = buf.remaining();
                if avail == 0 {
                    return Poll::Ready(Ok(()));
                }
                // SAFETY-free: write into ReadBuf's initialize_unfilled().
                let dst = buf.initialize_unfilled_to(avail);
                let (p, status) = me
                    .enc
                    .encode(&me.in_buf[me.in_consumed..me.in_filled], dst)?;
                me.in_consumed += p.consumed;
                buf.advance(p.written);
                if p.written > 0 {
                    let _ = status;
                    return Poll::Ready(Ok(()));
                }
                if matches!(status, Status::OutputFull) {
                    return Poll::Ready(Ok(()));
                }
                // Fall through to refill / finish.
            }
            if !me.inner_eof {
                let mut tmp = ReadBuf::new(&mut me.in_buf);
                ready_poll!(Pin::new(&mut me.inner).poll_read(cx, &mut tmp))?;
                let filled = tmp.filled().len();
                if filled == 0 {
                    me.inner_eof = true;
                } else {
                    me.in_consumed = 0;
                    me.in_filled = filled;
                }
                continue;
            }
            // No more plaintext. Drain enc.finish into the caller's buf.
            let avail = buf.remaining();
            if avail == 0 {
                return Poll::Ready(Ok(()));
            }
            let dst = buf.initialize_unfilled_to(avail);
            let (p, status) = me.enc.finish(dst)?;
            buf.advance(p.written);
            if matches!(status, Status::StreamEnd) {
                me.finished = true;
            }
            if p.written > 0 {
                return Poll::Ready(Ok(()));
            }
            if me.finished {
                return Poll::Ready(Ok(()));
            }
            return Poll::Ready(Ok(()));
        }
    }
}

// ─── DecoderReader ──────────────────────────────────────────────────────

/// Async dual of [`crate::io::DecoderReader`]: you read *plaintext*;
/// the wrapped `R` provides compressed bytes.
pub struct DecoderReader<R: AsyncRead + Unpin, D: Decoder + Unpin> {
    dec: D,
    inner: R,
    in_buf: Vec<u8>,
    in_filled: usize,
    in_consumed: usize,
    inner_eof: bool,
    finished: bool,
}

impl<R: AsyncRead + Unpin, D: Decoder + Unpin> DecoderReader<R, D> {
    pub fn new(inner: R, dec: D) -> Self {
        Self {
            dec,
            inner,
            in_buf: vec![0u8; SCRATCH],
            in_filled: 0,
            in_consumed: 0,
            inner_eof: false,
            finished: false,
        }
    }

    pub fn get_ref(&self) -> &R {
        &self.inner
    }
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.inner
    }
    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: AsyncRead + Unpin, D: Decoder + Unpin> AsyncRead for DecoderReader<R, D> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        let me = Pin::into_inner(self);
        loop {
            if me.finished {
                return Poll::Ready(Ok(()));
            }
            if me.in_consumed < me.in_filled {
                let avail = buf.remaining();
                if avail == 0 {
                    return Poll::Ready(Ok(()));
                }
                let dst = buf.initialize_unfilled_to(avail);
                let (p, status) = me
                    .dec
                    .decode(&me.in_buf[me.in_consumed..me.in_filled], dst)?;
                me.in_consumed += p.consumed;
                buf.advance(p.written);
                if matches!(status, Status::StreamEnd) {
                    me.finished = true;
                }
                if p.written > 0 {
                    return Poll::Ready(Ok(()));
                }
                if matches!(status, Status::OutputFull) {
                    return Poll::Ready(Ok(()));
                }
                if me.finished {
                    return Poll::Ready(Ok(()));
                }
            }
            if !me.inner_eof {
                let mut tmp = ReadBuf::new(&mut me.in_buf);
                ready_poll!(Pin::new(&mut me.inner).poll_read(cx, &mut tmp))?;
                let filled = tmp.filled().len();
                if filled == 0 {
                    me.inner_eof = true;
                } else {
                    me.in_consumed = 0;
                    me.in_filled = filled;
                }
                continue;
            }
            // EOF on inner — drain decoder tail.
            let avail = buf.remaining();
            if avail == 0 {
                return Poll::Ready(Ok(()));
            }
            let dst = buf.initialize_unfilled_to(avail);
            let (p, status) = me.dec.finish(dst)?;
            buf.advance(p.written);
            if matches!(status, Status::StreamEnd) {
                me.finished = true;
            }
            if p.written == 0 && !me.finished {
                // Inner is at EOF and finish() produced no output yet did
                // not reach StreamEnd: the stream is truncated. Returning
                // Ready(Ok) with nothing filled looks like a clean EOF and
                // would silently drop the missing tail, so surface it as
                // an error — mirroring the writer-path stall guard in
                // poll_shutdown().
                return Poll::Ready(Err(io::Error::from(Error::UnexpectedEnd)));
            }
            return Poll::Ready(Ok(()));
        }
    }
}