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
use crate::error::DecodeError;
use futures_core::{ready, Stream};
use futures_io::AsyncRead;
use pin_project_lite::pin_project;
use std::pin::Pin;
use std::task::{Context, Poll};

const DEFAULT_BUF_SIZE: usize = 8 * 1024;
const MINIMUM_BUF_SIZE: usize = 4; // Maximum utf-8 character byte length

pub type Result<T> = std::result::Result<T, DecodeError>;

pin_project! {
    pub struct Utf8Decoder<R> {
        #[pin]
        reader: R,
        buf: Box<[u8]>,
        remains: usize,
    }
}

impl<R> Utf8Decoder<R> {
    /// Create a new incremental UTF-8 decoder from `reader`
    pub fn new(reader: R) -> Self {
        Utf8Decoder::with_capacity(DEFAULT_BUF_SIZE, reader)
    }

    /// Create a new incremental UTF-8 decoder from `reader` with specified capacity
    pub fn with_capacity(capacity: usize, reader: R) -> Self {
        debug_assert!(
            capacity >= MINIMUM_BUF_SIZE,
            "capacity must be at least {} but {} is specified",
            MINIMUM_BUF_SIZE,
            capacity,
        );
        unsafe {
            let mut buffer = Vec::with_capacity(capacity);
            buffer.set_len(capacity);
            Self {
                reader,
                buf: buffer.into_boxed_slice(),
                remains: 0,
            }
        }
    }

    /// Consumes this decoder, returning the underlying reader.
    pub fn into_inner(self) -> R {
        self.reader
    }

    /// Acquires a reference to the underlying reader that this
    /// decoder is pulling from.
    pub fn get_ref(&self) -> &R {
        &self.reader
    }

    /// Acquires a mutable reference to the underlying reader that
    /// this decoder is pulling from.
    pub fn get_mut(&mut self) -> &mut R {
        &mut self.reader
    }
}

impl<R> Stream for Utf8Decoder<R>
where
    R: AsyncRead + Unpin,
{
    type Item = Result<String>;

    fn poll_next(
        self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<<Self as Stream>::Item>> {
        let this = self.project();
        let reader = this.reader;
        let buf = this.buf;
        let (decoded, remains) = ready!(decode_next(reader, cx, buf, *this.remains))?;
        *this.remains = remains;
        if decoded.is_empty() {
            cx.waker().wake_by_ref();
            Poll::Pending
        } else {
            Poll::Ready(Some(Ok(decoded)))
        }
    }
}

fn decode_next<'a, R>(
    reader: Pin<&mut R>,
    cx: &mut Context<'_>,
    buf: &'a mut [u8],
    s: usize,
) -> Poll<Result<(String, usize)>>
where
    R: AsyncRead,
{
    debug_assert!(buf.len() > s);
    let n = ready!(reader.poll_read(cx, &mut buf[s..]))?;
    let e = s + n;
    debug_assert!(buf.len() >= e);
    let result = match std::str::from_utf8(&buf[..e]) {
        Ok(decoded) => Ok((decoded.to_string(), 0)),
        Err(err) => match err.error_len() {
            Some(_) => {
                // An unexpected byte was encounted. While this decoder is not
                // lossy decoding, return the error itself and stop decoding.
                Err(err.into())
            }
            None => {
                // The end of the input was reached unexpectedly. This is what
                // this decoder exists for.
                let (valid, after_valid) = buf.split_at(err.valid_up_to());
                // Copy 'valid' into the Heap as String
                let decoded = unsafe { std::str::from_utf8_unchecked(valid) };
                let decoded = decoded.to_string();
                // Copy 'after_valid' at the front of the 'buf'
                let remains = e - valid.len();
                unsafe {
                    // +-------------------------------------------------------------+
                    // |                            buf                              |
                    // +----------------+--------------------------------------------+
                    // |     valid      | after_valid                                |
                    // +----------------+--------------------------------------------+
                    // |////////////////|#####.......................................|
                    // +----------------+--------------------------------------------+
                    //                               |
                    //                               v
                    // +-------------------------------------------------------------+
                    // |                            buf                              |
                    // +----------------+--------------------------------------------+
                    // |     valid      | after_valid                                |
                    // +----------------+--------------------------------------------+
                    // |#####...........|............................                |
                    // +----------------+--------------------------------------------+
                    //
                    // XXX: Can we use 'copy_nonoverlapping' here?
                    // std::ptr::copy_nonoverlapping(after_valid.as_ptr(), buf.as_mut_ptr(), remains);
                    std::ptr::copy(after_valid.as_ptr(), buf.as_mut_ptr(), remains);
                }
                Ok((decoded, remains))
            }
        },
    };
    Poll::Ready(result)
}

#[cfg(test)]
mod tests {
    use super::*;
    use anyhow::Result;
    use futures::channel::mpsc;
    use futures::io;
    use futures::prelude::*;

    async fn timeout<T>(future: impl Future<Output = T> + Unpin) -> Result<T> {
        let result =
            async_std::future::timeout(std::time::Duration::from_millis(100), future).await?;
        Ok(result)
    }

    #[async_std::test]
    async fn decoder_decode_demo() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        tx.send(Ok(vec![240])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![159])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![146])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![150])).await?;
        assert_eq!("💖", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_background() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        let consumer = async_std::task::spawn(async move { decoder.next().await });
        tx.send(Ok(vec![240])).await?;
        tx.send(Ok(vec![159])).await?;
        tx.send(Ok(vec![146])).await?;
        tx.send(Ok(vec![150])).await?;
        assert_eq!("💖", timeout(consumer).await?.unwrap()?);

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_1byte_character() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        tx.send(Ok(vec![0x24])).await?;
        assert_eq!("\u{0024}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_2byte_character() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        // Complete
        tx.send(Ok(vec![0xC2, 0xA2])).await?;
        assert_eq!("\u{00A2}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        // Incremental
        tx.send(Ok(vec![0xC2])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0xA2])).await?;
        assert_eq!("\u{00A2}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_3byte_character() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        // Complete
        tx.send(Ok(vec![0xE0, 0xA4, 0xB9])).await?;
        assert_eq!("\u{0939}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        // Incremental
        tx.send(Ok(vec![0xE0])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0xA4])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0xB9])).await?;
        assert_eq!("\u{0939}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_4byte_character() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        // Complete
        tx.send(Ok(vec![0xF0, 0x90, 0x8D, 0x88])).await?;
        assert_eq!("\u{10348}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        // Incremental
        tx.send(Ok(vec![0xF0])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0x90])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0x8D])).await?;
        assert!(timeout(decoder.next()).await.is_err());
        tx.send(Ok(vec![0x88])).await?;
        assert_eq!("\u{10348}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_ok() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::new(rx.into_async_read());

        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        assert_eq!(
            "\u{0024}\u{00A2}\u{0939}\u{10348}",
            timeout(decoder.next()).await?.unwrap()?
        );
        assert_eq!(
            "\u{0024}\u{00A2}\u{0939}\u{10348}",
            timeout(decoder.next()).await?.unwrap()?
        );
        assert_eq!(
            "\u{0024}\u{00A2}\u{0939}\u{10348}",
            timeout(decoder.next()).await?.unwrap()?
        );
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn decoder_decode_ok_with_minimum_capacity() -> Result<()> {
        let (mut tx, rx) = mpsc::unbounded::<io::Result<Vec<u8>>>();
        let mut decoder = Utf8Decoder::with_capacity(MINIMUM_BUF_SIZE, rx.into_async_read());

        // Complete
        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        tx.send(Ok(vec![
            0x24, 0xC2, 0xA2, 0xE0, 0xA4, 0xB9, 0xF0, 0x90, 0x8D, 0x88,
        ]))
        .await?;
        assert_eq!("\u{0024}\u{00A2}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{0939}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{10348}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{0024}\u{00A2}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{0939}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{10348}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{0024}\u{00A2}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{0939}", timeout(decoder.next()).await?.unwrap()?);
        assert_eq!("\u{10348}", timeout(decoder.next()).await?.unwrap()?);
        assert!(timeout(decoder.next()).await.is_err());

        Ok(())
    }
}