heatshrink-lib 1.0.0

A minimal library implementing the heatshrink compression algorithm for no_std environments
Documentation
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! [`embedded_io`] adapters for the Heatshrink encoder and decoder.
//!
//! Enabled by the `embedded-io` feature flag.  All types are `no_std`
//! compatible; no allocator is required.
//!
//! # Available adapters
//!
//! ## Push (Write) adapters
//!
//! These implement [`embedded_io::Write`]: the caller pushes bytes in, and the
//! adapter forwards the transformed bytes to an inner `Write` sink.
//!
//! | Type | Input | Output |
//! |------|-------|--------|
//! | [`EncoderWriter`] | raw bytes | compressed bytes → inner writer |
//! | [`DecoderWriter`] | compressed bytes | decompressed bytes → inner writer |
//!
//! Call [`EncoderWriter::finish`] / [`DecoderWriter::finish`] when done to
//! flush the encoder's bit-buffer and write the final bytes.
//!
//! ## Pull (Read) adapters
//!
//! These implement [`embedded_io::Read`]: the caller pulls transformed bytes
//! out; the adapter consumes raw bytes from an inner `Read` source.
//!
//! | Type | Source | Output |
//! |------|--------|--------|
//! | [`DecoderReader`] | compressed bytes (inner reader) | decompressed bytes |
//! | [`EncoderReader`] | raw bytes (inner reader) | compressed bytes |
//!
//! # Buffer sizing (`OUT`)
//!
//! The `Read` adapters need an internal output buffer to hold bytes produced
//! by `poll()` that did not fit in the caller's buffer on the previous call.
//! Its size is the const generic `OUT` (default: `256`).  A larger value
//! reduces the number of `poll()` calls; a smaller value saves stack space.
//! `OUT` must be ≥ 1.
//!
//! # Example — compress to a `Vec`-like sink
//!
//! ```rust,no_run
//! # #[cfg(feature = "embedded-io")] {
//! use heatshrink::io::EncoderWriter;
//! use heatshrink::DefaultEncoder;
//! use embedded_io::Write as _;
//!
//! // Any type that implements embedded_io::Write can be used as the sink.
//! // Here we use a fixed-size array wrapped in a cursor-like struct.
//! let mut compressed = [0u8; 1024];
//! let mut cursor = heatshrink::io::SliceSink::new(&mut compressed);
//!
//! let mut enc: EncoderWriter<_, DefaultEncoder> = EncoderWriter::new(&mut cursor);
//! enc.write_all(b"hello heatshrink").unwrap();
//! let n = enc.finish().unwrap();
//! // `n` bytes of compressed data are now in `compressed[..n]`.
//! # }
//! ```

use crate::{Finish, Poll, SinkError};
use embedded_io::{Error, ErrorKind, ErrorType, Read, Write};

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

/// A [`Write`] adapter that compresses bytes with a Heatshrink encoder and
/// forwards the compressed output to an inner [`Write`] sink.
///
/// # Type parameters
///
/// - `W` — the inner sink (must implement [`embedded_io::Write`]).
/// - `ENC` — the encoder type (e.g. [`crate::DefaultEncoder`]).
///
/// # Usage
///
/// 1. Create with [`EncoderWriter::new`].
/// 2. Write raw data with [`embedded_io::Write::write`] /
///    [`embedded_io::Write::write_all`].
/// 3. **Call [`finish`](EncoderWriter::finish)** to flush the encoder's
///    internal bit-buffer and write the final compressed bytes.  Dropping
///    without calling `finish` will silently lose the tail of the stream.
pub struct EncoderWriter<W, ENC> {
    inner: W,
    enc: ENC,
    /// Scratch buffer used for a single `poll()` call.
    poll_buf: [u8; 256],
}

impl<W, ENC> EncoderWriter<W, ENC>
where
    ENC: Default,
{
    /// Create a new `EncoderWriter` that compresses into `inner`.
    pub fn new(inner: W) -> Self {
        Self {
            inner,
            enc: ENC::default(),
            poll_buf: [0u8; 256],
        }
    }
}

impl<W, ENC> ErrorType for EncoderWriter<W, ENC>
where
    W: ErrorType,
{
    type Error = W::Error;
}

impl<W, ENC> EncoderWriter<W, ENC>
where
    W: Write,
    ENC: EncoderOps,
{
    /// Drain all pending compressed output from the encoder into `inner`.
    fn drain_poll(&mut self) -> Result<(), W::Error> {
        loop {
            match self.enc.poll(&mut self.poll_buf) {
                Ok(Poll::More(n)) => self.inner.write_all(&self.poll_buf[..n])?,
                Ok(Poll::Empty(n)) => {
                    if n > 0 {
                        self.inner.write_all(&self.poll_buf[..n])?;
                    }
                    return Ok(());
                }
                Err(_) => return Ok(()), // empty poll_buf: cannot happen (len=256)
            }
        }
    }

    /// Signal end-of-stream: flush the encoder's bit-buffer and write all
    /// remaining compressed bytes to the inner sink.
    ///
    /// Returns `Ok(())` on success.  Must be called exactly once after all
    /// input has been written.
    pub fn finish(&mut self) -> Result<(), W::Error> {
        loop {
            match self.enc.finish() {
                Finish::Done => return self.inner.flush(),
                Finish::More => self.drain_poll()?,
            }
        }
    }
}

impl<W, ENC> Write for EncoderWriter<W, ENC>
where
    W: Write,
    ENC: EncoderOps,
{
    fn write(&mut self, buf: &[u8]) -> Result<usize, W::Error> {
        let mut consumed = 0;
        while consumed < buf.len() {
            match self.enc.sink(&buf[consumed..]) {
                Ok(n) => consumed += n,
                Err(SinkError::Full) => self.drain_poll()?,
                Err(SinkError::Misuse) => {
                    // finish() already called — treat as a no-op write of 0.
                    break;
                }
            }
        }
        // Opportunistically drain so the inner buffer doesn't fill up.
        self.drain_poll()?;
        Ok(consumed)
    }

    fn flush(&mut self) -> Result<(), W::Error> {
        self.inner.flush()
    }
}

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

/// A [`Write`] adapter that decompresses Heatshrink-compressed bytes and
/// forwards the decompressed output to an inner [`Write`] sink.
///
/// # Usage
///
/// 1. Create with [`DecoderWriter::new`].
/// 2. Write compressed data with [`embedded_io::Write::write`] /
///    [`embedded_io::Write::write_all`].
/// 3. **Call [`finish`](DecoderWriter::finish)** to assert that the decoder
///    has no pending input and flush the inner sink.
pub struct DecoderWriter<W, DEC> {
    inner: W,
    dec: DEC,
    poll_buf: [u8; 256],
}

impl<W, DEC> DecoderWriter<W, DEC>
where
    DEC: Default,
{
    /// Create a new `DecoderWriter` that decompresses into `inner`.
    pub fn new(inner: W) -> Self {
        Self {
            inner,
            dec: DEC::default(),
            poll_buf: [0u8; 256],
        }
    }
}

impl<W, DEC> ErrorType for DecoderWriter<W, DEC>
where
    W: ErrorType,
{
    type Error = W::Error;
}

impl<W, DEC> DecoderWriter<W, DEC>
where
    W: Write,
    DEC: DecoderOps,
{
    fn drain_poll(&mut self) -> Result<(), W::Error> {
        loop {
            match self.dec.poll(&mut self.poll_buf) {
                Ok(Poll::More(n)) => self.inner.write_all(&self.poll_buf[..n])?,
                Ok(Poll::Empty(n)) => {
                    if n > 0 {
                        self.inner.write_all(&self.poll_buf[..n])?;
                    }
                    return Ok(());
                }
                Err(_) => return Ok(()),
            }
        }
    }

    /// Assert end-of-stream and flush the inner sink.
    ///
    /// Decompression is stateless with respect to trailing bytes — calling
    /// `finish` simply ensures all decoded output has been forwarded and the
    /// inner sink is flushed.
    pub fn finish(&mut self) -> Result<(), W::Error> {
        self.drain_poll()?;
        self.inner.flush()
    }
}

impl<W, DEC> Write for DecoderWriter<W, DEC>
where
    W: Write,
    DEC: DecoderOps,
{
    fn write(&mut self, buf: &[u8]) -> Result<usize, W::Error> {
        let mut consumed = 0;
        while consumed < buf.len() {
            match self.dec.sink(&buf[consumed..]) {
                Ok(n) => consumed += n,
                Err(SinkError::Full) => self.drain_poll()?,
                Err(SinkError::Misuse) => break,
            }
        }
        self.drain_poll()?;
        Ok(consumed)
    }

    fn flush(&mut self) -> Result<(), W::Error> {
        self.inner.flush()
    }
}

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

/// A [`Read`] adapter that decompresses Heatshrink-compressed bytes on the
/// fly.  The caller reads decompressed bytes; the adapter fetches compressed
/// bytes from an inner [`Read`] source as needed.
///
/// # Type parameters
///
/// - `R`   — the inner source (must implement [`embedded_io::Read`]).
/// - `DEC` — the decoder type (e.g. [`crate::DefaultDecoder`]).
/// - `OUT` — size of the internal output buffer (default `256`).  Must be ≥ 1.
pub struct DecoderReader<R, DEC, const OUT: usize = 256> {
    inner: R,
    dec: DEC,
    /// Decompressed bytes waiting to be handed to the caller.
    out_buf: [u8; OUT],
    /// Slice of `out_buf` that is filled but not yet consumed: `[out_start..out_end]`.
    out_start: usize,
    out_end: usize,
    /// Compressed bytes read from `inner` but not yet sunk into the decoder.
    in_buf: [u8; 64],
    in_start: usize,
    in_end: usize,
    /// Set when the inner reader returned 0 bytes (EOF).
    eof: bool,
}

impl<R, DEC, const OUT: usize> DecoderReader<R, DEC, OUT>
where
    DEC: Default,
{
    /// Create a new `DecoderReader` wrapping a compressed `inner` source.
    pub fn new(inner: R) -> Self {
        Self {
            inner,
            dec: DEC::default(),
            out_buf: [0u8; OUT],
            out_start: 0,
            out_end: 0,
            in_buf: [0u8; 64],
            in_start: 0,
            in_end: 0,
            eof: false,
        }
    }
}

impl<R, DEC, const OUT: usize> ErrorType for DecoderReader<R, DEC, OUT>
where
    R: ErrorType,
{
    type Error = R::Error;
}

impl<R, DEC, const OUT: usize> Read for DecoderReader<R, DEC, OUT>
where
    R: Read,
    DEC: DecoderOps,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, R::Error> {
        // 1. Serve leftover decoded output from a previous oversized poll.
        if self.out_start < self.out_end {
            let n = (self.out_end - self.out_start).min(buf.len());
            buf[..n].copy_from_slice(&self.out_buf[self.out_start..self.out_start + n]);
            self.out_start += n;
            if self.out_start == self.out_end {
                self.out_start = 0;
                self.out_end = 0;
            }
            return Ok(n);
        }

        loop {
            // 2. Sink any leftover compressed bytes from a previous read that
            //    was interrupted by SinkError::Full.
            while self.in_start < self.in_end {
                match self.dec.sink(&self.in_buf[self.in_start..self.in_end]) {
                    Ok(n) => self.in_start += n,
                    Err(SinkError::Full) => break, // will poll first, then retry
                    Err(SinkError::Misuse) => return Ok(0),
                }
            }
            if self.in_start == self.in_end {
                self.in_start = 0;
                self.in_end = 0;
            }

            // 3. Poll decoded output.
            match self.dec.poll(&mut self.out_buf) {
                Ok(Poll::More(n)) | Ok(Poll::Empty(n)) if n > 0 => {
                    let give = n.min(buf.len());
                    buf[..give].copy_from_slice(&self.out_buf[..give]);
                    if n > give {
                        self.out_start = give;
                        self.out_end = n;
                    }
                    return Ok(give);
                }
                Ok(Poll::More(_)) => {
                    // Decoder needs more input — fall through to fetch from inner.
                }
                Ok(Poll::Empty(_)) => {
                    // Decoder drained.
                    if self.eof && self.in_start == self.in_end {
                        return Ok(0); // truly done
                    }
                    // Still have buffered input or inner not exhausted yet.
                }
                Err(_) => return Ok(0), // out_buf.len() > 0, cannot happen
            }

            // 4. If we still have un-sunk input buffered, loop back to sink it.
            if self.in_start < self.in_end {
                continue;
            }

            // 5. Read more compressed bytes from inner into in_buf.
            if self.eof {
                continue; // drain decoder until it signals Empty with 0
            }
            let n_read = self.inner.read(&mut self.in_buf)?;
            if n_read == 0 {
                self.eof = true;
                // Don't return yet — the decoder may still have output to give.
                continue;
            }
            self.in_start = 0;
            self.in_end = n_read;
        }
    }
}

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

/// A [`Read`] adapter that compresses bytes on the fly.  The caller reads
/// compressed bytes; the adapter fetches raw bytes from an inner [`Read`]
/// source and compresses them.
///
/// # Type parameters
///
/// - `R`   — the inner source (must implement [`embedded_io::Read`]).
/// - `ENC` — the encoder type (e.g. [`crate::DefaultEncoder`]).
/// - `OUT` — size of the internal output buffer (default `256`).  Must be ≥ 1.
///
/// # End of stream
///
/// When the inner reader returns 0 bytes (EOF), the encoder's `finish()` is
/// called automatically.  The adapter will return 0 only after all compressed
/// output has been drained.
pub struct EncoderReader<R, ENC, const OUT: usize = 256> {
    inner: R,
    enc: ENC,
    out_buf: [u8; OUT],
    out_start: usize,
    out_end: usize,
    /// Raw bytes read from `inner` but not yet sunk into the encoder.
    in_buf: [u8; 64],
    in_start: usize,
    in_end: usize,
    /// Inner reader reached EOF.
    eof: bool,
    /// `finish()` has been called on the encoder.
    finishing: bool,
}

impl<R, ENC, const OUT: usize> EncoderReader<R, ENC, OUT>
where
    ENC: Default,
{
    /// Create a new `EncoderReader` wrapping a raw `inner` source.
    pub fn new(inner: R) -> Self {
        Self {
            inner,
            enc: ENC::default(),
            out_buf: [0u8; OUT],
            out_start: 0,
            out_end: 0,
            in_buf: [0u8; 64],
            in_start: 0,
            in_end: 0,
            eof: false,
            finishing: false,
        }
    }
}

impl<R, ENC, const OUT: usize> ErrorType for EncoderReader<R, ENC, OUT>
where
    R: ErrorType,
{
    type Error = R::Error;
}

impl<R, ENC, const OUT: usize> Read for EncoderReader<R, ENC, OUT>
where
    R: Read,
    ENC: EncoderOps,
{
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, R::Error> {
        // 1. Serve leftover compressed output from a previous oversized poll.
        if self.out_start < self.out_end {
            let n = (self.out_end - self.out_start).min(buf.len());
            buf[..n].copy_from_slice(&self.out_buf[self.out_start..self.out_start + n]);
            self.out_start += n;
            if self.out_start == self.out_end {
                self.out_start = 0;
                self.out_end = 0;
            }
            return Ok(n);
        }

        loop {
            // 2. Sink any leftover raw bytes from a previous read interrupted
            //    by SinkError::Full.
            while self.in_start < self.in_end {
                match self.enc.sink(&self.in_buf[self.in_start..self.in_end]) {
                    Ok(n) => self.in_start += n,
                    Err(SinkError::Full) => break,
                    Err(SinkError::Misuse) => return Ok(0),
                }
            }
            if self.in_start == self.in_end {
                self.in_start = 0;
                self.in_end = 0;
            }

            // 3. Poll the encoder for compressed output.
            match self.enc.poll(&mut self.out_buf) {
                Ok(Poll::More(n)) | Ok(Poll::Empty(n)) if n > 0 => {
                    let give = n.min(buf.len());
                    buf[..give].copy_from_slice(&self.out_buf[..give]);
                    if n > give {
                        self.out_start = give;
                        self.out_end = n;
                    }
                    return Ok(give);
                }
                Ok(Poll::More(_)) => {
                    // Encoder needs more input — fall through to fetch from inner.
                }
                Ok(Poll::Empty(_)) => {
                    if self.finishing {
                        match self.enc.finish() {
                            Finish::Done => return Ok(0),
                            Finish::More => continue,
                        }
                    }
                    if self.eof && self.in_start == self.in_end {
                        // All input consumed; begin the finish sequence.
                        self.finishing = true;
                        continue;
                    }
                }
                Err(_) => return Ok(0),
            }

            // 4. Loop back to sink buffered input if any remains.
            if self.in_start < self.in_end {
                continue;
            }

            // 5. Fetch more raw bytes from inner.
            if self.eof || self.finishing {
                continue;
            }
            let n_read = self.inner.read(&mut self.in_buf)?;
            if n_read == 0 {
                self.eof = true;
                continue;
            }
            self.in_start = 0;
            self.in_end = n_read;
        }
    }
}

// ─── Sealed trait helpers ────────────────────────────────────────────────────
//
// `EncoderOps` and `DecoderOps` are `pub` so they can appear in the bounds of
// the `pub` adapter structs without triggering `private_bounds`.  They are
// *sealed* via a private supertrait (`private::Sealed`) so that no external
// crate can implement them — only `HeatshrinkEncoder` / `HeatshrinkDecoder`
// have implementations, which live in this module.

mod private {
    pub trait Sealed {}
}

/// Abstraction over [`crate::encoder::HeatshrinkEncoder`] used by the io
/// adapters.  This trait is sealed: it cannot be implemented outside this
/// crate.
pub trait EncoderOps: private::Sealed {
    #[doc(hidden)]
    fn sink(&mut self, input: &[u8]) -> Result<usize, SinkError>;
    #[doc(hidden)]
    fn poll(&mut self, output: &mut [u8]) -> Result<Poll, crate::PollError>;
    #[doc(hidden)]
    fn finish(&mut self) -> Finish;
}

/// Abstraction over [`crate::decoder::HeatshrinkDecoder`] used by the io
/// adapters.  This trait is sealed: it cannot be implemented outside this
/// crate.
pub trait DecoderOps: private::Sealed {
    #[doc(hidden)]
    fn sink(&mut self, input: &[u8]) -> Result<usize, SinkError>;
    #[doc(hidden)]
    fn poll(&mut self, output: &mut [u8]) -> Result<Poll, crate::PollError>;
    #[doc(hidden)]
    #[allow(dead_code)]
    fn finish(&self) -> Finish;
}

impl<const W: usize, const L: usize, const BUF: usize> private::Sealed
    for crate::encoder::HeatshrinkEncoder<W, L, BUF>
{
}

impl<const W: usize, const L: usize, const BUF: usize> EncoderOps
    for crate::encoder::HeatshrinkEncoder<W, L, BUF>
{
    #[inline]
    fn sink(&mut self, input: &[u8]) -> Result<usize, SinkError> {
        crate::encoder::HeatshrinkEncoder::sink(self, input)
    }
    #[inline]
    fn poll(&mut self, output: &mut [u8]) -> Result<Poll, crate::PollError> {
        crate::encoder::HeatshrinkEncoder::poll(self, output)
    }
    #[inline]
    fn finish(&mut self) -> Finish {
        crate::encoder::HeatshrinkEncoder::finish(self)
    }
}

impl<const W: usize, const L: usize, const I: usize, const WIN: usize> private::Sealed
    for crate::decoder::HeatshrinkDecoder<W, L, I, WIN>
{
}

impl<const W: usize, const L: usize, const I: usize, const WIN: usize> DecoderOps
    for crate::decoder::HeatshrinkDecoder<W, L, I, WIN>
{
    #[inline]
    fn sink(&mut self, input: &[u8]) -> Result<usize, SinkError> {
        crate::decoder::HeatshrinkDecoder::sink(self, input)
    }
    #[inline]
    fn poll(&mut self, output: &mut [u8]) -> Result<Poll, crate::PollError> {
        crate::decoder::HeatshrinkDecoder::poll(self, output)
    }
    #[inline]
    fn finish(&self) -> Finish {
        crate::decoder::HeatshrinkDecoder::finish(self)
    }
}

// ─── SliceSink — minimal Write impl for tests / doc-examples ─────────────────

/// A simple [`Write`] sink backed by a mutable byte slice.
///
/// Useful for tests and documentation examples where no external I/O is
/// available.  `write` returns [`ErrorKind::OutOfMemory`] when the slice is
/// full.
pub struct SliceSink<'a> {
    buf: &'a mut [u8],
    pos: usize,
}

impl<'a> SliceSink<'a> {
    /// Create a new `SliceSink` backed by `buf`.
    pub fn new(buf: &'a mut [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    /// Number of bytes written so far.
    pub fn len(&self) -> usize {
        self.pos
    }

    /// Returns `true` if no bytes have been written yet.
    pub fn is_empty(&self) -> bool {
        self.pos == 0
    }

    /// The written portion of the backing slice.
    pub fn written(&self) -> &[u8] {
        &self.buf[..self.pos]
    }
}

/// Error type for [`SliceSink`].
#[derive(Debug)]
pub struct SliceSinkError(ErrorKind);

impl Error for SliceSinkError {
    fn kind(&self) -> ErrorKind {
        self.0
    }
}

impl ErrorType for SliceSink<'_> {
    type Error = SliceSinkError;
}

impl Write for SliceSink<'_> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, SliceSinkError> {
        let space = self.buf.len() - self.pos;
        if space == 0 {
            return Err(SliceSinkError(ErrorKind::OutOfMemory));
        }
        let n = buf.len().min(space);
        self.buf[self.pos..self.pos + n].copy_from_slice(&buf[..n]);
        self.pos += n;
        Ok(n)
    }

    fn flush(&mut self) -> Result<(), SliceSinkError> {
        Ok(())
    }
}

/// A simple [`Read`] source backed by a byte slice.
///
/// Useful for tests: wraps a `&[u8]` so it can be passed to
/// [`DecoderReader`] / [`EncoderReader`].
pub struct SliceSource<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> SliceSource<'a> {
    /// Create a new `SliceSource` backed by `buf`.
    pub fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }
}

/// Error type for [`SliceSource`].
#[derive(Debug)]
pub struct SliceSourceError(ErrorKind);

impl Error for SliceSourceError {
    fn kind(&self) -> ErrorKind {
        self.0
    }
}

impl ErrorType for SliceSource<'_> {
    type Error = SliceSourceError;
}

impl Read for SliceSource<'_> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, SliceSourceError> {
        let remaining = self.buf.len() - self.pos;
        let n = remaining.min(buf.len());
        buf[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
#[cfg(feature = "embedded-io")]
mod test_io {
    use super::{
        DecoderReader, DecoderWriter, EncoderReader, EncoderWriter, SliceSink, SliceSource,
    };
    use crate::{DefaultDecoder, DefaultEncoder};
    use embedded_io::{Read as _, Write as _};

    // ── helpers ──────────────────────────────────────────────────────────────

    /// Compress `src` via EncoderWriter into a heap-less slice, return byte count.
    fn ew_compress(src: &[u8], dst: &mut [u8]) -> usize {
        let mut sink = SliceSink::new(dst);
        let mut w: EncoderWriter<_, DefaultEncoder> = EncoderWriter::new(&mut sink);
        w.write_all(src).unwrap();
        w.finish().unwrap();
        sink.len()
    }

    /// Decompress `src` via DecoderWriter into a slice, return byte count.
    fn dw_decompress(src: &[u8], dst: &mut [u8]) -> usize {
        let mut sink = SliceSink::new(dst);
        let mut w: DecoderWriter<_, DefaultDecoder> = DecoderWriter::new(&mut sink);
        w.write_all(src).unwrap();
        w.finish().unwrap();
        sink.len()
    }

    /// Decompress `src` via DecoderReader into a slice, return byte count.
    fn dr_decompress(src: &[u8], dst: &mut [u8]) -> usize {
        let source = SliceSource::new(src);
        let mut r: DecoderReader<_, DefaultDecoder> = DecoderReader::new(source);
        let mut total = 0;
        loop {
            let n = r.read(&mut dst[total..]).unwrap();
            if n == 0 {
                break;
            }
            total += n;
        }
        total
    }

    /// Compress `src` via EncoderReader into a slice, return byte count.
    fn er_compress(src: &[u8], dst: &mut [u8]) -> usize {
        let source = SliceSource::new(src);
        let mut r: EncoderReader<_, DefaultEncoder> = EncoderReader::new(source);
        let mut total = 0;
        loop {
            let n = r.read(&mut dst[total..]).unwrap();
            if n == 0 {
                break;
            }
            total += n;
        }
        total
    }

    // ── round-trip tests ─────────────────────────────────────────────────────

    /// EncoderWriter → DecoderWriter round-trip.
    #[test]
    fn writer_roundtrip_short() {
        let src = b"hello heatshrink embedded-io";
        let mut compressed = [0u8; 256];
        let mut decompressed = [0u8; 256];
        let n_enc = ew_compress(src, &mut compressed);
        let n_dec = dw_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(src, &decompressed[..n_dec]);
    }

    /// EncoderWriter → DecoderWriter round-trip with repetitive data (back-refs).
    #[test]
    fn writer_roundtrip_repetitive() {
        let src: [u8; 4096] = core::array::from_fn(|i| (i % 251) as u8);
        let mut compressed = [0u8; 4096];
        let mut decompressed = [0u8; 4096];
        let n_enc = ew_compress(&src, &mut compressed);
        let n_dec = dw_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(&src[..], &decompressed[..n_dec]);
    }

    /// EncoderWriter → DecoderWriter round-trip with pseudo-random data (literals).
    #[test]
    fn writer_roundtrip_random() {
        let src: [u8; 4096] = core::array::from_fn(|i| {
            (i.wrapping_mul(6364136223846793005usize)
                .wrapping_add(1442695040888963407)
                >> 56) as u8
        });
        let mut compressed = [0u8; 8192];
        let mut decompressed = [0u8; 8192];
        let n_enc = ew_compress(&src, &mut compressed);
        let n_dec = dw_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(&src[..], &decompressed[..n_dec]);
    }

    /// EncoderWriter → DecoderReader round-trip.
    #[test]
    fn writer_reader_roundtrip() {
        let src = b"the quick brown fox jumps over the lazy dog";
        let mut compressed = [0u8; 256];
        let mut decompressed = [0u8; 256];
        let n_enc = ew_compress(src, &mut compressed);
        let n_dec = dr_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(src, &decompressed[..n_dec]);
    }

    /// EncoderReader → DecoderWriter round-trip.
    #[test]
    fn reader_writer_roundtrip() {
        let src = b"the quick brown fox jumps over the lazy dog";
        let mut compressed = [0u8; 256];
        let mut decompressed = [0u8; 256];
        let n_enc = er_compress(src, &mut compressed);
        let n_dec = dw_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(src, &decompressed[..n_dec]);
    }

    /// EncoderReader → DecoderReader round-trip.
    #[test]
    fn reader_reader_roundtrip() {
        let src: [u8; 4096] = core::array::from_fn(|i| (i % 251) as u8);
        let mut compressed = [0u8; 4096];
        let mut decompressed = [0u8; 4096];
        let n_enc = er_compress(&src, &mut compressed);
        let n_dec = dr_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(&src[..], &decompressed[..n_dec]);
    }

    /// Small caller buffer forces the Read adapters to exercise the internal
    /// output buffer (out_start / out_end bookkeeping).
    #[test]
    fn reader_small_output_buf() {
        let src: [u8; 512] = core::array::from_fn(|i| (i % 137) as u8);
        let mut compressed = [0u8; 1024];
        let mut decompressed = [0u8; 1024];

        // Compress with EncoderReader, read 1 byte at a time.
        let source = SliceSource::new(&src);
        let mut r: EncoderReader<_, DefaultEncoder> = EncoderReader::new(source);
        let mut n_enc = 0;
        loop {
            let n = r.read(&mut compressed[n_enc..n_enc + 1]).unwrap();
            if n == 0 {
                break;
            }
            n_enc += n;
        }

        // Decompress with DecoderReader, read 3 bytes at a time.
        let source2 = SliceSource::new(&compressed[..n_enc]);
        let mut r2: DecoderReader<_, DefaultDecoder> = DecoderReader::new(source2);
        let mut n_dec = 0;
        let mut tmp = [0u8; 3];
        loop {
            let n = r2.read(&mut tmp).unwrap();
            if n == 0 {
                break;
            }
            decompressed[n_dec..n_dec + n].copy_from_slice(&tmp[..n]);
            n_dec += n;
        }

        assert_eq!(&src[..], &decompressed[..n_dec]);
    }

    /// Empty input must produce a valid (empty) round-trip.
    #[test]
    fn writer_roundtrip_empty() {
        let src: &[u8] = &[];
        let mut compressed = [0u8; 64];
        let mut decompressed = [0u8; 64];
        let n_enc = ew_compress(src, &mut compressed);
        let n_dec = dw_decompress(&compressed[..n_enc], &mut decompressed);
        assert_eq!(src, &decompressed[..n_dec]);
    }
}