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
use ::core::future::Future;

use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
use tokio_util::bytes::{Buf as _, BytesMut};
use tokio_util::codec::{Decoder, Encoder};

fn invalid_utf8() -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidInput, "value is not valid UTF8")
}

pub trait AsyncReadUtf8: AsyncRead {
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(level = "trace", ret, skip_all)
    )]
    fn read_char_utf8(&mut self) -> impl Future<Output = std::io::Result<char>>
    where
        Self: Unpin,
    {
        async move {
            let b = self.read_u8().await?;
            let i = if b & 0x80 == 0 {
                u32::from(b)
            } else if b & 0b1110_0000 == 0b1100_0000 {
                let b2 = self.read_u8().await?;
                if b2 & 0b1100_0000 != 0b1000_0000 {
                    return Err(invalid_utf8());
                }
                u32::from(b & 0b0001_1111) << 6 | u32::from(b2 & 0b0011_1111)
            } else if b & 0b1111_0000 == 0b1110_0000 {
                let mut buf = [0; 2];
                self.read_exact(&mut buf).await?;
                if buf[0] & 0b1100_0000 != 0b1000_0000 || buf[1] & 0b1100_0000 != 0b1000_0000 {
                    return Err(invalid_utf8());
                }
                u32::from(b & 0b0000_1111) << 12
                    | u32::from(buf[0] & 0b0011_1111) << 6
                    | u32::from(buf[1] & 0b0011_1111)
            } else if b & 0b1111_1000 == 0b1111_0000 {
                let mut buf = [0; 3];
                self.read_exact(&mut buf).await?;
                if buf[0] & 0b1100_0000 != 0b1000_0000
                    || buf[1] & 0b1100_0000 != 0b1000_0000
                    || buf[2] & 0b1100_0000 != 0b1000_0000
                {
                    return Err(invalid_utf8());
                }
                u32::from(b & 0b0000_0111) << 18
                    | u32::from(buf[0] & 0b0011_1111) << 12
                    | u32::from(buf[1] & 0b0011_1111) << 6
                    | u32::from(buf[2] & 0b0011_1111)
            } else {
                return Err(invalid_utf8());
            };
            i.try_into()
                .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))
        }
    }
}

impl<T: AsyncRead> AsyncReadUtf8 for T {}

pub trait AsyncWriteUtf8: AsyncWrite {
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(level = "trace", ret, skip_all)
    )]
    fn write_char_utf8(&mut self, x: char) -> impl Future<Output = std::io::Result<()>>
    where
        Self: Unpin,
    {
        async move { self.write_all(x.encode_utf8(&mut [0; 4]).as_bytes()).await }
    }
}

impl<T: AsyncWrite> AsyncWriteUtf8 for T {}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct Utf8Codec;

impl Decoder for Utf8Codec {
    type Item = char;
    type Error = std::io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        let Some(b) = src.first().copied() else {
            src.reserve(1);
            return Ok(None);
        };
        let i = if b & 0x80 == 0 {
            src.advance(1);
            u32::from(b)
        } else if b & 0b1110_0000 == 0b1100_0000 {
            let Some(b2) = src.get(1).copied() else {
                src.reserve(1);
                return Ok(None);
            };
            if b2 & 0b1100_0000 != 0b1000_0000 {
                return Err(invalid_utf8());
            }
            src.advance(2);
            u32::from(b & 0b0001_1111) << 6 | u32::from(b2 & 0b0011_1111)
        } else if b & 0b1111_0000 == 0b1110_0000 {
            let Some(b2) = src.get(1).copied() else {
                src.reserve(2);
                return Ok(None);
            };
            let Some(b3) = src.get(2).copied() else {
                src.reserve(1);
                return Ok(None);
            };
            if b2 & 0b1100_0000 != 0b1000_0000 || b3 & 0b1100_0000 != 0b1000_0000 {
                return Err(invalid_utf8());
            }
            src.advance(3);
            u32::from(b & 0b0000_1111) << 12
                | u32::from(b2 & 0b0011_1111) << 6
                | u32::from(b3 & 0b0011_1111)
        } else if b & 0b1111_1000 == 0b1111_0000 {
            let Some(b2) = src.get(1).copied() else {
                src.reserve(3);
                return Ok(None);
            };
            let Some(b3) = src.get(2).copied() else {
                src.reserve(2);
                return Ok(None);
            };
            let Some(b4) = src.get(3).copied() else {
                src.reserve(1);
                return Ok(None);
            };
            if b2 & 0b1100_0000 != 0b1000_0000
                || b3 & 0b1100_0000 != 0b1000_0000
                || b4 & 0b1100_0000 != 0b1000_0000
            {
                return Err(invalid_utf8());
            }
            src.advance(4);
            u32::from(b & 0b0000_0111) << 18
                | u32::from(b2 & 0b0011_1111) << 12
                | u32::from(b3 & 0b0011_1111) << 6
                | u32::from(b4 & 0b0011_1111)
        } else {
            return Err(invalid_utf8());
        };
        let c = i
            .try_into()
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Ok(Some(c))
    }
}

impl Encoder<char> for Utf8Codec {
    type Error = std::io::Error;

    fn encode(&mut self, x: char, dst: &mut BytesMut) -> Result<(), Self::Error> {
        dst.extend_from_slice(x.encode_utf8(&mut [0; 4]).as_bytes());
        Ok(())
    }
}

impl Encoder<&char> for Utf8Codec {
    type Error = std::io::Error;

    fn encode(&mut self, x: &char, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(*x, dst)
    }
}

impl Encoder<&&char> for Utf8Codec {
    type Error = std::io::Error;

    fn encode(&mut self, x: &&char, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(**x, dst)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test_log::test(tokio::test)]
    async fn codec() {
        let v = '$'
            .encode_utf8(&mut [0; 1])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `$`");
        assert_eq!(v, '$');

        let v = '@'
            .encode_utf8(&mut [0; 1])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `@`");
        assert_eq!(v, '@');

        let v = 'И'
            .encode_utf8(&mut [0; 2])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `И`");
        assert_eq!(v, 'И');

        let v = 'ह'
            .encode_utf8(&mut [0; 3])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `ह`");
        assert_eq!(v, 'ह');

        let v = '€'
            .encode_utf8(&mut [0; 3])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `€`");
        assert_eq!(v, '€');

        let v = '한'
            .encode_utf8(&mut [0; 3])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `한`");
        assert_eq!(v, '한');

        let v = '𐍈'
            .encode_utf8(&mut [0; 4])
            .as_bytes()
            .read_char_utf8()
            .await
            .expect("failed to read `𐍈`");
        assert_eq!(v, '𐍈');
    }
}