Coverage Report

Created: 2026-01-19 07:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/qoi-0.4.1/src/decode.rs
Line
Count
Source
1
#[cfg(any(feature = "std", feature = "alloc"))]
2
use alloc::{vec, vec::Vec};
3
#[cfg(feature = "std")]
4
use std::io::Read;
5
6
// TODO: can be removed once https://github.com/rust-lang/rust/issues/74985 is stable
7
use bytemuck::{cast_slice_mut, Pod};
8
9
use crate::consts::{
10
    QOI_HEADER_SIZE, QOI_OP_DIFF, QOI_OP_INDEX, QOI_OP_LUMA, QOI_OP_RGB, QOI_OP_RGBA, QOI_OP_RUN,
11
    QOI_PADDING, QOI_PADDING_SIZE,
12
};
13
use crate::error::{Error, Result};
14
use crate::header::Header;
15
use crate::pixel::{Pixel, SupportedChannels};
16
use crate::types::Channels;
17
use crate::utils::{cold, unlikely};
18
19
const QOI_OP_INDEX_END: u8 = QOI_OP_INDEX | 0x3f;
20
const QOI_OP_RUN_END: u8 = QOI_OP_RUN | 0x3d; // <- note, 0x3d (not 0x3f)
21
const QOI_OP_DIFF_END: u8 = QOI_OP_DIFF | 0x3f;
22
const QOI_OP_LUMA_END: u8 = QOI_OP_LUMA | 0x3f;
23
24
#[inline]
25
0
fn decode_impl_slice<const N: usize, const RGBA: bool>(data: &[u8], out: &mut [u8]) -> Result<usize>
26
0
where
27
0
    Pixel<N>: SupportedChannels,
28
0
    [u8; N]: Pod,
29
{
30
0
    let mut pixels = cast_slice_mut::<_, [u8; N]>(out);
31
0
    let data_len = data.len();
32
0
    let mut data = data;
33
34
0
    let mut index = [Pixel::<4>::new(); 256];
35
0
    let mut px = Pixel::<N>::new().with_a(0xff);
36
    let mut px_rgba: Pixel<4>;
37
38
0
    while let [px_out, ptail @ ..] = pixels {
39
0
        pixels = ptail;
40
0
        match data {
41
0
            [b1 @ QOI_OP_INDEX..=QOI_OP_INDEX_END, dtail @ ..] => {
42
0
                px_rgba = index[*b1 as usize];
43
0
                px.update(px_rgba);
44
0
                *px_out = px.into();
45
0
                data = dtail;
46
0
                continue;
47
            }
48
0
            [QOI_OP_RGB, r, g, b, dtail @ ..] => {
49
0
                px.update_rgb(*r, *g, *b);
50
0
                data = dtail;
51
0
            }
52
0
            [QOI_OP_RGBA, r, g, b, a, dtail @ ..] if RGBA => {
53
0
                px.update_rgba(*r, *g, *b, *a);
54
0
                data = dtail;
55
0
            }
56
0
            [b1 @ QOI_OP_RUN..=QOI_OP_RUN_END, dtail @ ..] => {
57
0
                *px_out = px.into();
58
0
                let run = ((b1 & 0x3f) as usize).min(pixels.len());
59
0
                let (phead, ptail) = pixels.split_at_mut(run); // can't panic
60
0
                phead.fill(px.into());
61
0
                pixels = ptail;
62
0
                data = dtail;
63
0
                continue;
64
            }
65
0
            [b1 @ QOI_OP_DIFF..=QOI_OP_DIFF_END, dtail @ ..] => {
66
0
                px.update_diff(*b1);
67
0
                data = dtail;
68
0
            }
69
0
            [b1 @ QOI_OP_LUMA..=QOI_OP_LUMA_END, b2, dtail @ ..] => {
70
0
                px.update_luma(*b1, *b2);
71
0
                data = dtail;
72
0
            }
73
            _ => {
74
0
                cold();
75
0
                if unlikely(data.len() < QOI_PADDING_SIZE) {
76
0
                    return Err(Error::UnexpectedBufferEnd);
77
0
                }
78
            }
79
        }
80
81
0
        px_rgba = px.as_rgba(0xff);
82
0
        index[px_rgba.hash_index() as usize] = px_rgba;
83
0
        *px_out = px.into();
84
    }
85
86
0
    if unlikely(data.len() < QOI_PADDING_SIZE) {
87
0
        return Err(Error::UnexpectedBufferEnd);
88
0
    } else if unlikely(data[..QOI_PADDING_SIZE] != QOI_PADDING) {
89
0
        return Err(Error::InvalidPadding);
90
0
    }
91
92
0
    Ok(data_len.saturating_sub(data.len()).saturating_sub(QOI_PADDING_SIZE))
93
0
}
94
95
#[inline]
96
0
fn decode_impl_slice_all(
97
0
    data: &[u8], out: &mut [u8], channels: u8, src_channels: u8,
98
0
) -> Result<usize> {
99
0
    match (channels, src_channels) {
100
0
        (3, 3) => decode_impl_slice::<3, false>(data, out),
101
0
        (3, 4) => decode_impl_slice::<3, true>(data, out),
102
0
        (4, 3) => decode_impl_slice::<4, false>(data, out),
103
0
        (4, 4) => decode_impl_slice::<4, true>(data, out),
104
        _ => {
105
0
            cold();
106
0
            Err(Error::InvalidChannels { channels })
107
        }
108
    }
109
0
}
110
111
/// Decode the image into a pre-allocated buffer.
112
///
113
/// Note: the resulting number of channels will match the header. In order to change
114
/// the number of channels, use [`Decoder::with_channels`].
115
#[inline]
116
0
pub fn decode_to_buf(buf: impl AsMut<[u8]>, data: impl AsRef<[u8]>) -> Result<Header> {
117
0
    let mut decoder = Decoder::new(&data)?;
118
0
    decoder.decode_to_buf(buf)?;
119
0
    Ok(*decoder.header())
120
0
}
121
122
/// Decode the image into a newly allocated vector.
123
///
124
/// Note: the resulting number of channels will match the header. In order to change
125
/// the number of channels, use [`Decoder::with_channels`].
126
#[cfg(any(feature = "std", feature = "alloc"))]
127
#[inline]
128
0
pub fn decode_to_vec(data: impl AsRef<[u8]>) -> Result<(Header, Vec<u8>)> {
129
0
    let mut decoder = Decoder::new(&data)?;
130
0
    let out = decoder.decode_to_vec()?;
131
0
    Ok((*decoder.header(), out))
132
0
}
133
134
/// Decode the image header from a slice of bytes.
135
#[inline]
136
0
pub fn decode_header(data: impl AsRef<[u8]>) -> Result<Header> {
137
0
    Header::decode(data)
138
0
}
139
140
#[cfg(any(feature = "std"))]
141
#[inline]
142
0
fn decode_impl_stream<R: Read, const N: usize, const RGBA: bool>(
143
0
    data: &mut R, out: &mut [u8],
144
0
) -> Result<()>
145
0
where
146
0
    Pixel<N>: SupportedChannels,
147
0
    [u8; N]: Pod,
148
{
149
0
    let mut pixels = cast_slice_mut::<_, [u8; N]>(out);
150
151
0
    let mut index = [Pixel::<N>::new(); 256];
152
0
    let mut px = Pixel::<N>::new().with_a(0xff);
153
154
0
    while let [px_out, ptail @ ..] = pixels {
155
0
        pixels = ptail;
156
0
        let mut p = [0];
157
0
        data.read_exact(&mut p)?;
158
0
        let [b1] = p;
159
0
        match b1 {
160
0
            QOI_OP_INDEX..=QOI_OP_INDEX_END => {
161
0
                px = index[b1 as usize];
162
0
                *px_out = px.into();
163
0
                continue;
164
            }
165
            QOI_OP_RGB => {
166
0
                let mut p = [0; 3];
167
0
                data.read_exact(&mut p)?;
168
0
                px.update_rgb(p[0], p[1], p[2]);
169
            }
170
0
            QOI_OP_RGBA if RGBA => {
171
0
                let mut p = [0; 4];
172
0
                data.read_exact(&mut p)?;
173
0
                px.update_rgba(p[0], p[1], p[2], p[3]);
174
            }
175
0
            QOI_OP_RUN..=QOI_OP_RUN_END => {
176
0
                *px_out = px.into();
177
0
                let run = ((b1 & 0x3f) as usize).min(pixels.len());
178
0
                let (phead, ptail) = pixels.split_at_mut(run); // can't panic
179
0
                phead.fill(px.into());
180
0
                pixels = ptail;
181
0
                continue;
182
            }
183
0
            QOI_OP_DIFF..=QOI_OP_DIFF_END => {
184
0
                px.update_diff(b1);
185
0
            }
186
0
            QOI_OP_LUMA..=QOI_OP_LUMA_END => {
187
0
                let mut p = [0];
188
0
                data.read_exact(&mut p)?;
189
0
                let [b2] = p;
190
0
                px.update_luma(b1, b2);
191
            }
192
0
            _ => {
193
0
                cold();
194
0
            }
195
        }
196
197
0
        index[px.hash_index() as usize] = px;
198
0
        *px_out = px.into();
199
    }
200
201
0
    let mut p = [0_u8; QOI_PADDING_SIZE];
202
0
    data.read_exact(&mut p)?;
203
0
    if unlikely(p != QOI_PADDING) {
204
0
        return Err(Error::InvalidPadding);
205
0
    }
206
207
0
    Ok(())
208
0
}
Unexecuted instantiation: qoi::decode::decode_impl_stream::<std::io::cursor::Cursor<&[u8]>, 3, false>
Unexecuted instantiation: qoi::decode::decode_impl_stream::<std::io::cursor::Cursor<&[u8]>, 3, true>
Unexecuted instantiation: qoi::decode::decode_impl_stream::<std::io::cursor::Cursor<&[u8]>, 4, false>
Unexecuted instantiation: qoi::decode::decode_impl_stream::<std::io::cursor::Cursor<&[u8]>, 4, true>
Unexecuted instantiation: qoi::decode::decode_impl_stream::<_, _, _>
209
210
#[cfg(feature = "std")]
211
#[inline]
212
0
fn decode_impl_stream_all<R: Read>(
213
0
    data: &mut R, out: &mut [u8], channels: u8, src_channels: u8,
214
0
) -> Result<()> {
215
0
    match (channels, src_channels) {
216
0
        (3, 3) => decode_impl_stream::<_, 3, false>(data, out),
217
0
        (3, 4) => decode_impl_stream::<_, 3, true>(data, out),
218
0
        (4, 3) => decode_impl_stream::<_, 4, false>(data, out),
219
0
        (4, 4) => decode_impl_stream::<_, 4, true>(data, out),
220
        _ => {
221
0
            cold();
222
0
            Err(Error::InvalidChannels { channels })
223
        }
224
    }
225
0
}
Unexecuted instantiation: qoi::decode::decode_impl_stream_all::<std::io::cursor::Cursor<&[u8]>>
Unexecuted instantiation: qoi::decode::decode_impl_stream_all::<_>
226
227
#[doc(hidden)]
228
pub trait Reader: Sized {
229
    fn decode_header(&mut self) -> Result<Header>;
230
    fn decode_image(&mut self, out: &mut [u8], channels: u8, src_channels: u8) -> Result<()>;
231
}
232
233
pub struct Bytes<'a>(&'a [u8]);
234
235
impl<'a> Bytes<'a> {
236
    #[inline]
237
0
    pub const fn new(buf: &'a [u8]) -> Self {
238
0
        Self(buf)
239
0
    }
240
241
    #[inline]
242
0
    pub const fn as_slice(&self) -> &[u8] {
243
0
        self.0
244
0
    }
245
}
246
247
impl<'a> Reader for Bytes<'a> {
248
    #[inline]
249
0
    fn decode_header(&mut self) -> Result<Header> {
250
0
        let header = Header::decode(self.0)?;
251
0
        self.0 = &self.0[QOI_HEADER_SIZE..]; // can't panic
252
0
        Ok(header)
253
0
    }
254
255
    #[inline]
256
0
    fn decode_image(&mut self, out: &mut [u8], channels: u8, src_channels: u8) -> Result<()> {
257
0
        let n_read = decode_impl_slice_all(self.0, out, channels, src_channels)?;
258
0
        self.0 = &self.0[n_read..];
259
0
        Ok(())
260
0
    }
261
}
262
263
#[cfg(feature = "std")]
264
impl<R: Read> Reader for R {
265
    #[inline]
266
0
    fn decode_header(&mut self) -> Result<Header> {
267
0
        let mut b = [0; QOI_HEADER_SIZE];
268
0
        self.read_exact(&mut b)?;
269
0
        Header::decode(b)
270
0
    }
Unexecuted instantiation: <std::io::cursor::Cursor<&[u8]> as qoi::decode::Reader>::decode_header
Unexecuted instantiation: <_ as qoi::decode::Reader>::decode_header
271
272
    #[inline]
273
0
    fn decode_image(&mut self, out: &mut [u8], channels: u8, src_channels: u8) -> Result<()> {
274
0
        decode_impl_stream_all(self, out, channels, src_channels)
275
0
    }
Unexecuted instantiation: <std::io::cursor::Cursor<&[u8]> as qoi::decode::Reader>::decode_image
Unexecuted instantiation: <_ as qoi::decode::Reader>::decode_image
276
}
277
278
/// Decode QOI images from slices or from streams.
279
#[derive(Clone)]
280
pub struct Decoder<R> {
281
    reader: R,
282
    header: Header,
283
    channels: Channels,
284
}
285
286
impl<'a> Decoder<Bytes<'a>> {
287
    /// Creates a new decoder from a slice of bytes.
288
    ///
289
    /// The header will be decoded immediately upon construction.
290
    ///
291
    /// Note: this provides the most efficient decoding, but requires the source data to
292
    /// be loaded in memory in order to decode it. In order to decode from a generic
293
    /// stream, use [`Decoder::from_stream`] instead.
294
    #[inline]
295
0
    pub fn new(data: &'a (impl AsRef<[u8]> + ?Sized)) -> Result<Self> {
296
0
        Self::new_impl(Bytes::new(data.as_ref()))
297
0
    }
298
299
    /// Returns the undecoded tail of the input slice of bytes.
300
    #[inline]
301
0
    pub const fn data(&self) -> &[u8] {
302
0
        self.reader.as_slice()
303
0
    }
304
}
305
306
#[cfg(feature = "std")]
307
impl<R: Read> Decoder<R> {
308
    /// Creates a new decoder from a generic reader that implements [`Read`](std::io::Read).
309
    ///
310
    /// The header will be decoded immediately upon construction.
311
    ///
312
    /// Note: while it's possible to pass a `&[u8]` slice here since it implements `Read`, it
313
    /// would be more efficient to use a specialized constructor instead: [`Decoder::new`].
314
    #[inline]
315
0
    pub fn from_stream(reader: R) -> Result<Self> {
316
0
        Self::new_impl(reader)
317
0
    }
Unexecuted instantiation: <qoi::decode::Decoder<std::io::cursor::Cursor<&[u8]>>>::from_stream
Unexecuted instantiation: <qoi::decode::Decoder<_>>::from_stream
318
319
    /// Returns an immutable reference to the underlying reader.
320
    #[inline]
321
0
    pub const fn reader(&self) -> &R {
322
0
        &self.reader
323
0
    }
324
325
    /// Consumes the decoder and returns the underlying reader back.
326
    #[inline]
327
    #[allow(clippy::missing_const_for_fn)]
328
0
    pub fn into_reader(self) -> R {
329
0
        self.reader
330
0
    }
331
}
332
333
impl<R: Reader> Decoder<R> {
334
    #[inline]
335
0
    fn new_impl(mut reader: R) -> Result<Self> {
336
0
        let header = reader.decode_header()?;
337
0
        Ok(Self { reader, header, channels: header.channels })
338
0
    }
Unexecuted instantiation: <qoi::decode::Decoder<std::io::cursor::Cursor<&[u8]>>>::new_impl
Unexecuted instantiation: <qoi::decode::Decoder<_>>::new_impl
339
340
    /// Returns a new decoder with modified number of channels.
341
    ///
342
    /// By default, the number of channels in the decoded image will be equal
343
    /// to whatever is specified in the header. However, it is also possible
344
    /// to decode RGB into RGBA (in which case the alpha channel will be set
345
    /// to 255), and vice versa (in which case the alpha channel will be ignored).
346
    #[inline]
347
0
    pub const fn with_channels(mut self, channels: Channels) -> Self {
348
0
        self.channels = channels;
349
0
        self
350
0
    }
351
352
    /// Returns the number of channels in the decoded image.
353
    ///
354
    /// Note: this may differ from the number of channels specified in the header.
355
    #[inline]
356
0
    pub const fn channels(&self) -> Channels {
357
0
        self.channels
358
0
    }
359
360
    /// Returns the decoded image header.
361
    #[inline]
362
0
    pub const fn header(&self) -> &Header {
363
0
        &self.header
364
0
    }
Unexecuted instantiation: <qoi::decode::Decoder<std::io::cursor::Cursor<&[u8]>>>::header
Unexecuted instantiation: <qoi::decode::Decoder<_>>::header
365
366
    /// The number of bytes the decoded image will take.
367
    ///
368
    /// Can be used to pre-allocate the buffer to decode the image into.
369
    #[inline]
370
0
    pub const fn required_buf_len(&self) -> usize {
371
0
        self.header.n_pixels().saturating_mul(self.channels.as_u8() as usize)
372
0
    }
Unexecuted instantiation: <qoi::decode::Decoder<std::io::cursor::Cursor<&[u8]>>>::required_buf_len
Unexecuted instantiation: <qoi::decode::Decoder<_>>::required_buf_len
373
374
    /// Decodes the image to a pre-allocated buffer and returns the number of bytes written.
375
    ///
376
    /// The minimum size of the buffer can be found via [`Decoder::required_buf_len`].
377
    #[inline]
378
0
    pub fn decode_to_buf(&mut self, mut buf: impl AsMut<[u8]>) -> Result<usize> {
379
0
        let buf = buf.as_mut();
380
0
        let size = self.required_buf_len();
381
0
        if unlikely(buf.len() < size) {
382
0
            return Err(Error::OutputBufferTooSmall { size: buf.len(), required: size });
383
0
        }
384
0
        self.reader.decode_image(buf, self.channels.as_u8(), self.header.channels.as_u8())?;
385
0
        Ok(size)
386
0
    }
Unexecuted instantiation: <qoi::decode::Decoder<std::io::cursor::Cursor<&[u8]>>>::decode_to_buf::<&mut [u8]>
Unexecuted instantiation: <qoi::decode::Decoder<_>>::decode_to_buf::<_>
387
388
    /// Decodes the image into a newly allocated vector of bytes and returns it.
389
    #[cfg(any(feature = "std", feature = "alloc"))]
390
    #[inline]
391
0
    pub fn decode_to_vec(&mut self) -> Result<Vec<u8>> {
392
0
        let mut out = vec![0; self.header.n_pixels() * self.channels.as_u8() as usize];
393
0
        let _ = self.decode_to_buf(&mut out)?;
394
0
        Ok(out)
395
0
    }
396
}