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
/*!
# UTF-8 Builder

Build and validate UTF-8 data from chunks. Each chunk doesn't have to be a complete UTF-8 data.

## Motives and Examples

When we want our Rust program to input a UTF-8 data, we can store all data in the memory and use `String::from_utf8(vec)` to validate it and convert it into a `String` instance.

However, it would be better if we perform UTF-8 validation while fetching and storing the data into the memory. In such a way, if the data is not UTF-8, we don't have to waste the memory space and time to store all of it.

```rust
use utf8_builder::Utf8Builder;

const TEXT1: &str = "is is English.";
const TEXT2: &str = "這是中文。";

let mut builder = Utf8Builder::new();

builder.push(b'T').unwrap();
builder.push_char('h').unwrap();
builder.push_str(TEXT1).unwrap();
builder.push_chunk(TEXT2.as_bytes()).unwrap();

let result = builder.finalize().unwrap();

assert_eq!(format!("Th{}{}", TEXT1, TEXT2), result);
```

## No Std

Disable the default features to compile this crate without std.

```toml
[dependencies.utf8-builder]
version = "*"
default-features = false
```
*/

#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

mod error;

use core::cmp::Ordering;

use alloc::string::String;
use alloc::vec::Vec;

pub use error::Utf8Error;

/// A builder for Building and validating UTF-8 data from chunks.
#[derive(Debug, Clone, Default)]
pub struct Utf8Builder {
    buffer: Vec<u8>,
    /// the length for the incomplete character
    sl: u8,
    /// the valid expected length for the incomplete character
    sel: u8,
}

impl Utf8Builder {
    /// Constructs a new, empty `Utf8Builder`.
    #[inline]
    pub const fn new() -> Self {
        Utf8Builder {
            buffer: Vec::new(),
            sl: 0,
            sel: 0,
        }
    }

    /// Constructs a new, empty `with_capacity` with a specific capacity.
    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        Utf8Builder {
            buffer: Vec::with_capacity(capacity),
            sl: 0,
            sel: 0,
        }
    }

    /// Reserves capacity for at least `additional` more elements to be inserted in the given `Utf8Builder`.
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.buffer.reserve(additional);
    }

    /// Returns the number of elements in the buffer.
    #[inline]
    pub fn len(&self) -> usize {
        self.buffer.len()
    }

    /// Returns `true` if the builder contains no data.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.buffer.is_empty()
    }
}

impl Utf8Builder {
    /// Returns whether the current data are valid UTF-8
    #[inline]
    pub fn is_valid(&self) -> bool {
        self.sl == 0
    }

    /// Try to get the `String` instance.
    #[inline]
    pub fn finalize(self) -> Result<String, Utf8Error> {
        if self.is_valid() {
            let s = unsafe { String::from_utf8_unchecked(self.buffer) };

            Ok(s)
        } else {
            Err(Utf8Error)
        }
    }
}

impl Utf8Builder {
    /// Pushes a byte.
    pub fn push(&mut self, b: u8) -> Result<(), Utf8Error> {
        if self.sl == 0 {
            let w = utf8_width::get_width(b);

            match w {
                0 => return Err(Utf8Error),
                1 => {
                    self.buffer.push(b);
                }
                _ => {
                    self.buffer.push(b);
                    self.sl = 1;
                    self.sel = w as u8;
                }
            }
        } else if self.sl + 1 == self.sel {
            self.buffer.push(b);

            self.sl = 0;
            // self.sel = 0; // no need
        } else {
            self.buffer.push(b);

            self.sl += 1;
        }

        Ok(())
    }

    /// Pushes a `&str`.
    #[inline]
    pub fn push_str(&mut self, s: &str) -> Result<(), Utf8Error> {
        if self.sl == 0 {
            self.buffer.extend_from_slice(s.as_bytes());

            Ok(())
        } else {
            Err(Utf8Error)
        }
    }

    /// Pushes a char.
    pub fn push_char(&mut self, c: char) -> Result<(), Utf8Error> {
        if self.sl == 0 {
            self.buffer.reserve(4);

            let len = self.buffer.len();

            unsafe {
                self.buffer.set_len(len + 4);
            }

            let c = c.encode_utf8(&mut self.buffer[len..]).len();

            unsafe {
                self.buffer.set_len(len + c);
            }

            Ok(())
        } else {
            Err(Utf8Error)
        }
    }

    /// Pushes a chunk.
    pub fn push_chunk(&mut self, chunk: &[u8]) -> Result<(), Utf8Error> {
        let chunk_size = chunk.len();

        if chunk_size == 0 {
            return Ok(());
        }

        let mut e = if self.sl > 0 {
            let r = (self.sel - self.sl) as usize;

            match r.cmp(&chunk_size) {
                Ordering::Greater => {
                    let sl = self.sl as usize;
                    let nsl = sl + chunk_size;

                    self.buffer.extend_from_slice(chunk);

                    self.sl = nsl as u8;

                    return Ok(());
                }
                Ordering::Equal => {
                    self.buffer.extend_from_slice(chunk);

                    self.sl = 0;
                    // self.sel = 0; // no need

                    return Ok(());
                }
                Ordering::Less => {
                    self.buffer.extend_from_slice(&chunk[..r]);

                    self.sl = 0;
                    // self.sel = 0; // no need

                    r
                }
            }
        } else {
            0usize
        };

        loop {
            let w = utf8_width::get_width(chunk[e]);

            if w == 0 {
                return Err(Utf8Error);
            }

            let r = chunk_size - e;

            if r >= w {
                self.buffer.extend_from_slice(&chunk[e..e + w]);

                e += w;

                if e == chunk_size {
                    break;
                }
            } else {
                self.buffer.extend_from_slice(&chunk[e..]);

                self.sl = r as u8;
                self.sel = w as u8;

                break;
            }
        }

        Ok(())
    }
}

impl From<&str> for Utf8Builder {
    #[inline]
    fn from(s: &str) -> Self {
        Utf8Builder {
            buffer: s.as_bytes().to_vec(),
            sl: 0,
            sel: 0,
        }
    }
}

impl From<String> for Utf8Builder {
    #[inline]
    fn from(s: String) -> Self {
        Utf8Builder {
            buffer: s.into_bytes(),
            sl: 0,
            sel: 0,
        }
    }
}