qoi/
utils.rs

1#[cfg(feature = "std")]
2use std::io::Write;
3
4use crate::error::Result;
5
6#[inline(always)]
7#[cold]
8pub const fn cold() {}
9
10#[inline(always)]
11#[allow(unused)]
12pub const fn likely(b: bool) -> bool {
13    if !b {
14        cold();
15    }
16    b
17}
18
19#[inline(always)]
20pub const fn unlikely(b: bool) -> bool {
21    if b {
22        cold();
23    }
24    b
25}
26
27pub trait Writer: Sized {
28    fn write_one(self, v: u8) -> Result<Self>;
29    fn write_many(self, v: &[u8]) -> Result<Self>;
30    fn capacity(&self) -> usize;
31}
32
33pub struct BytesMut<'a>(&'a mut [u8]);
34
35impl<'a> BytesMut<'a> {
36    pub fn new(buf: &'a mut [u8]) -> Self {
37        Self(buf)
38    }
39
40    #[inline]
41    pub fn write_one(self, v: u8) -> Self {
42        if let Some((first, tail)) = self.0.split_first_mut() {
43            *first = v;
44            Self(tail)
45        } else {
46            unreachable!()
47        }
48    }
49
50    #[inline]
51    pub fn write_many(self, v: &[u8]) -> Self {
52        if v.len() <= self.0.len() {
53            let (head, tail) = self.0.split_at_mut(v.len());
54            head.copy_from_slice(v);
55            Self(tail)
56        } else {
57            unreachable!()
58        }
59    }
60}
61
62impl<'a> Writer for BytesMut<'a> {
63    #[inline]
64    fn write_one(self, v: u8) -> Result<Self> {
65        Ok(BytesMut::write_one(self, v))
66    }
67
68    #[inline]
69    fn write_many(self, v: &[u8]) -> Result<Self> {
70        Ok(BytesMut::write_many(self, v))
71    }
72
73    #[inline]
74    fn capacity(&self) -> usize {
75        self.0.len()
76    }
77}
78
79#[cfg(feature = "std")]
80pub struct GenericWriter<W> {
81    writer: W,
82    n_written: usize,
83}
84
85#[cfg(feature = "std")]
86impl<W: Write> GenericWriter<W> {
87    pub const fn new(writer: W) -> Self {
88        Self { writer, n_written: 0 }
89    }
90}
91
92#[cfg(feature = "std")]
93impl<W: Write> Writer for GenericWriter<W> {
94    fn write_one(mut self, v: u8) -> Result<Self> {
95        self.n_written += 1;
96        self.writer.write_all(&[v]).map(|_| self).map_err(Into::into)
97    }
98
99    fn write_many(mut self, v: &[u8]) -> Result<Self> {
100        self.n_written += v.len();
101        self.writer.write_all(v).map(|_| self).map_err(Into::into)
102    }
103
104    fn capacity(&self) -> usize {
105        usize::MAX - self.n_written
106    }
107}