json/
buffer.rs

1//! Buffer structures to enable decoding strings without allocating.
2use std::str;
3
4/// UTF-8 encoding buffer over an u8-slice.
5pub struct Utf8Buffer<'r> {
6    buf: &'r mut [u8],
7    idx: usize
8}
9
10impl<'r> Utf8Buffer<'r> {
11    pub fn new(b: &'r mut [u8]) -> Utf8Buffer<'r> {
12        Utf8Buffer { buf: b, idx: 0 }
13    }
14
15    pub fn reset(&mut self) {
16        self.idx = 0
17    }
18
19    pub fn as_str(&self) -> &str {
20        unsafe { str::from_utf8_unchecked(&self.buf[0 .. self.idx]) }
21    }
22
23    pub fn is_full(&self) -> bool {
24        self.idx >= self.buf.len()
25    }
26
27    pub fn push(&mut self, c: char) {
28        let len = c.len_utf8();
29        if self.idx + len > self.buf.len() {
30            return ()
31        }
32        self.idx += c.encode_utf8(&mut self.buf[self.idx ..]).len()
33    }
34}
35
36pub trait Buffer {
37    fn push(&mut self, c: char);
38    fn is_full(&self) -> bool;
39}
40
41impl Buffer for String {
42    fn push(&mut self, c: char) { self.push(c) }
43    fn is_full(&self) -> bool   { false }
44}
45
46impl<'r> Buffer for Utf8Buffer<'r> {
47    fn push(&mut self, c: char) { self.push(c)   }
48    fn is_full(&self) -> bool   { self.is_full() }
49}
50