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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use std::cmp;
use std::io;

use encoding_rs::{CoderResult, Decoder, Encoding};

/// This is the minimum amount of space that a decoder-to-utf8-with-replacement
/// will use for any state and any input.
const TINY_BUFFER_SIZE: usize = 7;

/// A tiny transcoder performs transcoding incrementally even when a caller
/// provided buffer is not large enough.
///
/// This use case comes up when implementing streaming transcoding in cases
/// where it is permissible to provide incomplete UTF-8 sequences to the
/// caller (e.g., when decoding into a `&[u8]` where the caller must be capable
/// of handling invalid UTF-8). In particular, this type specifically handles
/// cases where a caller provided buffer is too small to store a full UTF-8
/// sequence. Thus, this type should be used in cases where the caller provided
/// buffer has length 3 or fewer.
///
/// This could likely be done with better performance by allocating a larger
/// buffer for these cases, but we instead opt to handle this without
/// allocation under the assumption that tiny caller provided buffers are
/// probably a pathological case.
#[derive(Clone, Debug)]
pub struct TinyTranscoder {
    /// This is where we store the results of a transcoding. Since we are
    /// always decoding to UTF-8, 7 bytes is sufficient to represent any
    /// codepoint.
    partial: [u8; TINY_BUFFER_SIZE],
    /// The number of bytes written in `partial`.
    len: usize,
    /// The position in `partial` at which the next byte should be read.
    pos: usize,
}

impl TinyTranscoder {
    /// Create a new tiny transcoder that is ready for use.
    pub fn new() -> TinyTranscoder {
        TinyTranscoder { partial: [0; TINY_BUFFER_SIZE], len: 0, pos: 0 }
    }

    /// Transcode the contents of `src` into this buffer using the provided
    /// decoder, and return the number of bytes consumed in `src` and the
    /// number of bytes written to this transcoder.
    ///
    /// The results of transcoding can be read using the TinyTranscoder's
    /// `io::Read` implementation.
    ///
    /// If `last` is true, then this signals to the decoder that we've reached
    /// EOF and `src` must be empty. Otherwise, if `last` is false, then
    /// `src` must be non-empty. Violating either of these constraits will
    /// cause a panic.
    ///
    /// Finally, if this transcoder still has unconsumed bytes from a previous
    /// transcode, then this panics. Callers must consume all bytes from a
    /// previous transcoding before performing another one.
    pub fn transcode(
        &mut self,
        decoder: &mut Decoder,
        src: &[u8],
        last: bool,
    ) -> (usize, usize) {
        assert!(self.as_slice().is_empty(), "transcoder has unconsumed bytes");
        if last {
            assert!(src.is_empty(), "src must be empty when last==true");
        }
        let (res, nin, nout, _) =
            decoder.decode_to_utf8(src, &mut self.partial[..], last);
        if last {
            assert_eq!(
                res,
                CoderResult::InputEmpty,
                "input should be exhausted",
            );
        }
        self.pos = 0;
        self.len = nout;
        (nin, nout)
    }

    /// Return the the bytes remaining to be read as a slice.
    fn as_slice(&self) -> &[u8] {
        &self.partial[self.pos..self.len]
    }
}

impl io::Read for TinyTranscoder {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.pos >= self.len {
            return Ok(0);
        }
        let mut count = 0;
        for (src, dst) in self.as_slice().iter().zip(buf) {
            *dst = *src;
            count += 1;
        }
        self.pos += count;
        Ok(count)
    }
}

/// `BomPeeker` wraps `R` and satisfies the `io::Read` interface while also
/// providing a peek at the BOM if one exists. Peeking at the BOM does not
/// advance the reader.
#[derive(Debug)]
pub struct BomPeeker<R> {
    rdr: R,
    strip: bool,
    bom: Option<PossibleBom>,
    nread: usize,
}

impl<R: io::Read> BomPeeker<R> {
    /// Create a new BomPeeker that includes the BOM in calls to `read`.
    ///
    /// The first three bytes can be read using the `peek_bom` method, but
    /// will not advance the reader.
    pub fn with_bom(rdr: R) -> BomPeeker<R> {
        BomPeeker { rdr: rdr, strip: false, bom: None, nread: 0 }
    }

    /// Create a new BomPeeker that never includes the BOM in calls to `read`.
    pub fn without_bom(rdr: R) -> BomPeeker<R> {
        BomPeeker { rdr: rdr, strip: true, bom: None, nread: 0 }
    }

    /// Peek at the first three bytes of the underlying reader.
    ///
    /// This does not advance the reader provided by `BomPeeker`.
    ///
    /// If the underlying reader does not have at least two bytes available,
    /// then `None` is returned.
    pub fn peek_bom(&mut self) -> io::Result<PossibleBom> {
        if let Some(bom) = self.bom {
            return Ok(bom);
        }
        // If the underlying reader fails or panics, make sure we set at least
        // an empty BOM so that we don't end up here again..
        self.bom = Some(PossibleBom::new());

        // OK, try to read the BOM.
        let mut buf = [0u8; 3];
        let bom_len = read_full(&mut self.rdr, &mut buf)?;
        self.bom = Some(PossibleBom { bytes: buf, len: bom_len });
        Ok(self.bom.unwrap())
    }
}

impl<R: io::Read> io::Read for BomPeeker<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.nread < 3 {
            let bom = self.peek_bom()?;

            // If we don't have a valid BOM (e.g., no encoding for it), then
            // we always pass through the first 3 bytes. Otherwise, if we have
            // a valid BOM, we only pass it thru if we don't want to strip it.
            let bom = bom.as_slice(!self.strip);
            if self.nread < bom.len() {
                let rest = &bom[self.nread..];
                let len = cmp::min(buf.len(), rest.len());
                buf[..len].copy_from_slice(&rest[..len]);
                self.nread += len;
                return Ok(len);
            }
        }
        let nread = self.rdr.read(buf)?;
        self.nread += nread;
        Ok(nread)
    }
}

/// A PossibleBom is a sequence of bytes at the beginning of a stream that
/// may represent an actual BOM. To detect the BOM, this must contain at
/// least 3 bytes.
///
/// If this is a valid UTF-8 or UTF-16 BOM, then an encoding_rs decoder can
/// be built from the BOM.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct PossibleBom {
    bytes: [u8; 3],
    len: usize,
}

impl PossibleBom {
    /// Build a new empty BOM.
    fn new() -> PossibleBom {
        PossibleBom { bytes: [0; 3], len: 0 }
    }

    /// Return the BOM as a normal slice.
    ///
    /// If `bom` is true, then this includes any leading BOM bytes. Otherwise,
    /// this only includes non-BOM bytes.
    fn as_slice(&self, bom: bool) -> &[u8] {
        let slice = &self.bytes[0..self.len];
        if bom || slice.len() <= 1 {
            slice
        } else if &slice[0..2] == b"\xFF\xFE" || &slice[0..2] == b"\xFE\xFF" {
            &slice[2..]
        } else if slice == b"\xEF\xBB\xBF" {
            &[]
        } else {
            slice
        }
    }

    /// If this is a valid UTF-8 or UTF-16 BOM, return its corresponding
    /// encoding. Otherwise, return `None`.
    pub fn encoding(&self) -> Option<&'static Encoding> {
        let bom = self.as_slice(true);
        if bom.len() < 3 {
            return None;
        }
        if let Some((enc, _)) = Encoding::for_bom(bom) {
            return Some(enc);
        }
        None
    }
}

/// Like `io::Read::read_exact`, except it never returns `UnexpectedEof` and
/// instead returns the number of bytes read if EOF is seen before filling
/// `buf`.
pub fn read_full<R: io::Read>(
    mut rdr: R,
    mut buf: &mut [u8],
) -> io::Result<usize> {
    let mut nread = 0;
    while !buf.is_empty() {
        match rdr.read(buf) {
            Ok(0) => break,
            Ok(n) => {
                nread += n;
                let tmp = buf;
                buf = &mut tmp[n..];
            }
            Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(nread)
}

#[cfg(test)]
mod tests {
    use super::{BomPeeker, PossibleBom, TinyTranscoder};
    use encoding_rs::Encoding;
    use std::io::Read;

    #[test]
    fn tiny_utf16_normal() {
        let enc = Encoding::for_label(b"utf-16le").unwrap();
        let mut dec = enc.new_decoder_with_bom_removal();
        let mut bytes = &b"f\x00o\x00o\x00b\x00a\x00r\x00b\x00a\x00z\x00"[..];
        let mut tiny = TinyTranscoder::new();
        let mut tmp = [0u8; 1];

        let (nin, nout) = tiny.transcode(&mut dec, bytes, false);
        assert_eq!(nin, 14);
        assert_eq!(nout, 7);
        bytes = &bytes[nin..];

        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'f'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'o'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'o'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'b'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'a'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'r'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'b'; 1]);

        let (nin, nout) = tiny.transcode(&mut dec, bytes, false);
        assert_eq!(nin, 4);
        assert_eq!(nout, 2);
        bytes = &bytes[nin..];

        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'a'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'z'; 1]);

        let (nin, nout) = tiny.transcode(&mut dec, bytes, true);
        assert_eq!(nin, 0);
        assert_eq!(nout, 0);

        assert_eq!(tiny.read(&mut tmp).unwrap(), 0);
    }

    #[test]
    fn tiny_utf16_invalid() {
        let enc = Encoding::for_label(b"utf-16le").unwrap();
        let mut dec = enc.new_decoder_with_bom_removal();
        let mut bytes = &b"\x00"[..];
        let mut tiny = TinyTranscoder::new();
        let mut tmp = [0u8; 1];

        let (nin, nout) = tiny.transcode(&mut dec, bytes, false);
        assert_eq!(nin, 1);
        assert_eq!(nout, 0);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 0);
        bytes = &bytes[nin..];

        let (nin, nout) = tiny.transcode(&mut dec, bytes, true);
        assert_eq!(nin, 0);
        assert_eq!(nout, 3);

        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'\xEF'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'\xBF'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 1);
        assert_eq!(tmp, [b'\xBD'; 1]);
        assert_eq!(tiny.read(&mut tmp).unwrap(), 0);
    }

    #[test]
    fn peeker_empty() {
        let buf = [];
        let mut peeker = BomPeeker::with_bom(&buf[..]);
        assert_eq!(PossibleBom::new(), peeker.peek_bom().unwrap());

        let mut tmp = [0; 100];
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_one() {
        let buf = [1];
        let mut peeker = BomPeeker::with_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [1, 0, 0], len: 1 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_two() {
        let buf = [1, 2];
        let mut peeker = BomPeeker::with_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [1, 2, 0], len: 2 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(2, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(2, tmp[1]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_three() {
        let buf = [1, 2, 3];
        let mut peeker = BomPeeker::with_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [1, 2, 3], len: 3 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(3, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(2, tmp[1]);
        assert_eq!(3, tmp[2]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_four() {
        let buf = [1, 2, 3, 4];
        let mut peeker = BomPeeker::with_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [1, 2, 3], len: 3 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(3, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(2, tmp[1]);
        assert_eq!(3, tmp[2]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(4, tmp[0]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_one_at_a_time() {
        let buf = [1, 2, 3, 4];
        let mut peeker = BomPeeker::with_bom(&buf[..]);

        let mut tmp = [0; 1];
        assert_eq!(0, peeker.read(&mut tmp[..0]).unwrap());
        assert_eq!(0, tmp[0]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(2, tmp[0]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(3, tmp[0]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(4, tmp[0]);
    }

    #[test]
    fn peeker_without_bom() {
        let buf = [b'\xEF', b'\xBB', b'\xBF', b'a'];
        let mut peeker = BomPeeker::without_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [b'\xEF', b'\xBB', b'\xBF'], len: 3 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(b'a', tmp[0]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }

    #[test]
    fn peeker_without_bom_nobom() {
        let buf = [1, 2, 3, 4];
        let mut peeker = BomPeeker::without_bom(&buf[..]);
        assert_eq!(
            PossibleBom { bytes: [1, 2, 3], len: 3 },
            peeker.peek_bom().unwrap()
        );

        let mut tmp = [0; 100];
        assert_eq!(3, peeker.read(&mut tmp).unwrap());
        assert_eq!(1, tmp[0]);
        assert_eq!(2, tmp[1]);
        assert_eq!(3, tmp[2]);
        assert_eq!(1, peeker.read(&mut tmp).unwrap());
        assert_eq!(4, tmp[0]);
        assert_eq!(0, peeker.read(&mut tmp).unwrap());
    }
}