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
#[cfg(feature = "alloc")]
use alloc::{vec, vec::Vec};
use core::fmt::Debug;
#[cfg(feature = "std")]
use std::io::{self, Read};

use super::Decoder;

pub struct DecoderBuilder<R = (), B = ()> {
    read: R,
    buf: B,
}

impl Default for DecoderBuilder {
    fn default() -> Self {
        Self { read: (), buf: () }
    }
}

impl DecoderBuilder<(), ()> {
    #[deprecated = "DecoderBuilder is missing a reader and a buffer, which are required to build a decoder."]
    pub fn build(self) -> ! {
        panic!("See compilation warning");
    }
}

impl<R> DecoderBuilder<(R,), ()> {
    #[deprecated = "DecoderBuilder is missing a buffer, which is required to build a decoder."]
    pub fn build(self) -> ! {
        panic!("See compilation warning");
    }
}

impl<B> DecoderBuilder<(), (B,)> {
    #[deprecated = "DecoderBuilder is missing a reader, which is required to build a decoder."]
    pub fn build(self) -> ! {
        panic!("See compilation warning");
    }
}

impl<B> DecoderBuilder<(), B> {
    pub fn with_read_fn<R, E>(self, read_fn: R) -> DecoderBuilder<(R,), B>
    where
        R: FnMut(&mut [u8]) -> Result<usize, E>,
        E: Debug,
    {
        DecoderBuilder {
            read: (read_fn,),
            buf: self.buf,
        }
    }

    #[cfg(feature = "std")]
    pub fn with_reader(
        self,
        mut reader: impl Read,
    ) -> DecoderBuilder<(impl FnMut(&mut [u8]) -> Result<usize, io::Error>,), B> {
        let read = move |buf: &mut [u8]| reader.read(buf);

        DecoderBuilder {
            read: (read,),
            buf: self.buf,
        }
    }
}

impl<R> DecoderBuilder<R, ()> {
    pub fn with_buffer<B>(self, buf: B) -> DecoderBuilder<R, (B,)>
    where
        B: AsMut<[u8]>,
    {
        DecoderBuilder {
            read: self.read,
            buf: (buf,),
        }
    }

    pub fn with_stack_buffer<const SIZE: usize>(self) -> DecoderBuilder<R, ([u8; SIZE],)> {
        self.with_buffer([0; SIZE])
    }

    #[cfg(feature = "alloc")]
    pub fn with_heap_buffer(self, size: usize) -> DecoderBuilder<R, (Vec<u8>,)> {
        self.with_buffer(vec![0; size])
    }
}

impl<R, B, E> DecoderBuilder<(R,), (B,)>
where
    R: FnMut(&mut [u8]) -> Result<usize, E>,
    E: Debug,
    B: AsMut<[u8]>,
{
    pub fn build(self) -> Decoder<R, B> {
        Decoder::new(self.read.0, self.buf.0)
    }
}