stringcue 0.1.1

String Compressed Unicode Encoding - encode unicode more space efficient than utf-8 by sacrificing robustness like byte-boundaries.
Documentation
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
//! Decoding of stringcue blobs into strings.

use crate::error::DecodeError;
use crate::options::{DecodeEmpties, DecodeOptions, DecodeTerminator};
use crate::prefix::Prefix;
use alloc::string::String;
use arbitrary_int::u7;

/// A token read at a codepoint position in a blob.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Token {
    /// A Unicode character.
    Char(char),
    /// The non-unicode `CONTROL` value, used as separator and terminator.
    Control,
}

/// How decoding decides that the end of a blob is reached.
///
/// Padding of up to one prefix width is always written after the final
/// codepoint, so at blob end at most seven one-bits with no zero bits
/// behind them are padding. A run of seven one-bits is also a valid
/// `CONTROL` prefix, which the behaviors resolve differently. All
/// behaviors finish decoding at the first terminator; whatever follows it
/// is never read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EofBehavior {
    /// A terminator is required; a blob that ends without one is
    /// truncated. A trailing run of exactly seven one-bits is read as a
    /// `CONTROL` prefix, because the written terminator can alias with the
    /// padding.
    Require,
    /// A terminator is accepted, not required; the blob also ends at
    /// trailing padding of up to one prefix width.
    Tolerate,
    /// A terminator is an error; trailing padding of up to a full prefix
    /// value ends the blob without one.
    Refuse,
}

impl From<&DecodeTerminator> for EofBehavior {
    fn from(terminator: &DecodeTerminator) -> Self {
        match terminator {
            DecodeTerminator::Require => Self::Require,
            DecodeTerminator::Tolerate => Self::Tolerate,
            DecodeTerminator::Refuse(_) => Self::Refuse,
        }
    }
}

/// Bit-level cursor over a blob, reading most significant bit first.
#[derive(Debug, Clone, Copy)]
struct BitReader<'a> {
    bytes: &'a [u8],
    position: usize,
}

impl<'a> BitReader<'a> {
    /// Creates a reader over the blob, starting at its first bit.
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, position: 0 }
    }

    /// The number of bits left in the blob.
    fn remaining(&self) -> usize {
        self.bytes.len() * 8 - self.position
    }

    /// Reads `bits` bits as an unsigned value, most significant bit first,
    /// or `None` if fewer bits remain.
    ///
    /// The bytes covering the read area are assembled into a single integer
    /// and the whole area is extracted with one shift and mask, instead of
    /// reading it bit by bit.
    fn read_bits(&mut self, bits: u32) -> Option<u32> {
        let bits = bits as usize;
        if self.remaining() < bits {
            return None;
        }
        let start = self.position;
        self.position += bits;
        Some(self.extract(start, bits))
    }

    /// Extracts the `bits` bits at bit offset `start` as an unsigned value,
    /// most significant bit first.
    ///
    /// `bits` must not exceed 32 and the range must lie inside the blob.
    fn extract(&self, start: usize, bits: usize) -> u32 {
        debug_assert!(bits <= 32 && start + bits <= self.bytes.len() * 8);
        let first = start / 8;
        let last = (start + bits - 1) / 8;
        let mut window = 0u64;
        for &byte in &self.bytes[first..=last] {
            window = (window << 8) | u64::from(byte);
        }
        let shift = (last - first + 1) * 8 - start % 8 - bits;
        ((window >> shift) & ((1u64 << bits) - 1)) as u32
    }

    /// Whether every bit in the range `[start, end)` is set, checked one
    /// run of bits per intersected byte.
    fn range_is_ones(&self, start: usize, end: usize) -> bool {
        let mut offset = start;
        while offset < end {
            let run = (end - offset).min(8 - offset % 8);
            let mask = (((1u16 << run) - 1) << (8 - offset % 8 - run)) as u8;
            if self.bytes[offset / 8] & mask != mask {
                return false;
            }
            offset += run;
        }
        true
    }

    /// Whether every remaining bit is set.
    fn remaining_are_ones(&self) -> bool {
        self.range_is_ones(self.position, self.bytes.len() * 8)
    }

    /// Whether the reader sits at the end of the decodable data under the
    /// given end-of-blob behavior. Ending on the blob's end requires at
    /// most one prefix width of padding: a run of one bits shorter than a
    /// byte, with no zero bits after it.
    fn at_blob_end(&self, eof: EofBehavior) -> bool {
        let remaining = self.remaining();
        match eof {
            EofBehavior::Require => {
                remaining == 0 || (remaining < 7 && self.remaining_are_ones())
            }
            EofBehavior::Tolerate | EofBehavior::Refuse => {
                remaining < 8 && self.remaining_are_ones()
            }
        }
    }

    /// Reads one token; `None` signals the end of the decodable data.
    fn read_token(&mut self, eof: EofBehavior) -> Result<Option<Token>, DecodeError> {
        if self.at_blob_end(eof) {
            return Ok(None);
        }
        if self.remaining() < 7 {
            return Err(DecodeError::Truncated);
        }
        let prefix = Prefix::from_bits(
            u7::new(self.read_bits(7).expect("at least a prefix remains") as u8),
        );
        match prefix {
            Prefix::Ascii(code) => Ok(Some(Token::Char(
                char::from_u32(u32::from(code)).expect("an ASCII prefix encodes a character"),
            ))),
            Prefix::Control => Ok(Some(Token::Control)),
            Prefix::Tail7 { payload } => self.read_tail(u32::from(payload), 7, 0),
            Prefix::Tail8 { payload } => self.read_tail(u32::from(payload), 8, 1 << 10),
            Prefix::Tail13 { payload } => self.read_tail(u32::from(payload), 13, 1 << 11),
            Prefix::Tail18 { payload } => self.read_tail(u32::from(payload), 18, 1 << 16),
        }
    }

    /// Assembles a codepoint from its first 3 bits and its tail, and
    /// rejects codepoints the encoder cannot have produced.
    fn read_tail(
        &mut self,
        payload: u32,
        follow: u32,
        minimum: u32,
    ) -> Result<Option<Token>, DecodeError> {
        let Some(tail) = self.read_bits(follow) else {
            return Err(DecodeError::Truncated);
        };
        let codepoint = (payload << follow) | tail;
        match char::from_u32(codepoint) {
            Some(c) if codepoint >= minimum => Ok(Some(Token::Char(c))),
            _ => Err(DecodeError::InvalidCodepoint),
        }
    }
}

/// Decodes a single string from a stringcue blob.
///
/// Returns the string up to the first `CONTROL` value; the rest of the blob
/// is ignored. How a `CONTROL` terminator at the end of the blob is treated
/// is decided by [`DecodeTerminator`]:
///
/// - [`DecodeTerminator::Require`] returns [`DecodeError::Truncated`] when
///   the blob ends without a terminator.
/// - [`DecodeTerminator::Tolerate`] (default) accepts a blob with or
///   without a terminator.
/// - [`DecodeTerminator::Refuse`] returns [`DecodeError::InvalidCodepoint`]
///   when the blob contains any `CONTROL` value.
///
/// Codepoints are validated against the encoder's canonical form: in
/// addition to invalid Unicode values, a codepoint the encoder would have
/// written in a shorter length class is rejected as corruption and not
/// decoded.
///
/// # Errors
///
/// Returns [`DecodeError::Truncated`] when the blob ends mid-codepoint, or
/// when the terminator is required but missing. Returns
/// [`DecodeError::InvalidCodepoint`] when the blob contains bits that do
/// not form a valid Unicode codepoint, or a `CONTROL` value while the
/// terminator is refused.
///
/// # Examples
///
/// ```
/// let encoded = stringcue::encode("Hello, world!", Default::default());
/// let decoded = stringcue::decode(&encoded, Default::default()).expect("decoding should roundtrip encoding");
///
/// assert_eq!(decoded, "Hello, world!");
/// ```
pub fn decode(encoded: impl AsRef<[u8]>, options: DecodeOptions) -> Result<String, DecodeError> {
    let mut reader = BitReader::new(encoded.as_ref());
    let eof = EofBehavior::from(&options.terminator);
    let mut string = String::new();
    loop {
        match reader.read_token(eof)? {
            Some(Token::Char(c)) => string.push(c),
            Some(Token::Control) => {
                return if matches!(options.terminator, DecodeTerminator::Refuse(_)) {
                    Err(DecodeError::InvalidCodepoint)
                } else {
                    Ok(string)
                };
            }
            None => {
                return if options.terminator == DecodeTerminator::Require {
                    Err(DecodeError::Truncated)
                } else {
                    Ok(string)
                };
            }
        }
    }
}

/// Decodes a container of strings from one compact stringcue blob.
///
/// Strings are split at `CONTROL` separators; see [`crate::encode_all`]. The
/// whole blob is validated before iteration, so the result is an error if
/// the blob is invalid anywhere; iterating [`DecodeAll`] afterwards cannot
/// fail. The input length serves as the external length limit with the
/// default options, so a superfluous terminator is accepted.
///
/// How the terminator is treated is decided by [`DecodeTerminator`]:
///
/// - [`DecodeTerminator::Require`] returns [`DecodeError::Truncated`] when
///   the blob does not contain the terminator.
/// - [`DecodeTerminator::Tolerate`] (default) also accepts a blob without
///   the terminator, which then ends at trailing padding.
/// - [`DecodeTerminator::Refuse`] treats nothing as the terminator and
///   reads consecutive `CONTROL` values as empty elements, as configured
///   by [`DecodeEmpties`]; trailing padding of up to one prefix width ends
///   the blob.
///
/// Decoding finishes at the first terminator and ignores whatever follows
/// it. The terminator is two consecutive `CONTROL` values, so with
/// [`DecodeTerminator::Require`] or [`DecodeTerminator::Tolerate`], empty
/// elements cannot be read; [`DecodeEmpties`] only applies to
/// [`DecodeTerminator::Refuse`], where no terminator exists.
///
/// Codepoints are validated against the encoder's canonical form, as with
/// [`decode`].
///
/// # Errors
///
/// Returns [`DecodeError::Truncated`] when the blob ends mid-codepoint,
/// when the terminator is required but missing, or when the blob ends in
/// trailing bits that neither padding nor a terminator explain.
/// Returns [`DecodeError::InvalidCodepoint`] when the blob contains bits
/// that do not form a valid Unicode codepoint, or, with
/// [`DecodeTerminator::Refuse`] and [`DecodeEmpties::Reject`], empty
/// elements.
///
/// # Examples
///
/// ```
/// let strings = ["Hello", "world", "¡hola, unicode!"];
///
/// let blob = stringcue::encode_all(&strings, Default::default());
/// let decoded: Vec<String> = stringcue::decode_all(&blob, Default::default()).expect("decoding should roundtrip encoding").collect();
///
/// assert_eq!(decoded, strings);
/// ```
pub fn decode_all<'a, E: AsRef<[u8]> + ?Sized>(
    encoded: &'a E,
    options: DecodeOptions,
) -> Result<DecodeAll<'a>, DecodeError> {
    let end = validated_end(encoded.as_ref(), options)?;
    Ok(DecodeAll {
        encoded: encoded.as_ref(),
        position: 0,
        end,
        options,
    })
}

/// Validates a whole blob per the terminator option and returns the bit
/// position up to which iterating yields strings.
fn validated_end(bytes: &[u8], options: DecodeOptions) -> Result<usize, DecodeError> {
    let eof = EofBehavior::from(&options.terminator);
    match options.terminator {
        DecodeTerminator::Require => region_end(bytes, eof, false),
        DecodeTerminator::Tolerate => region_end(bytes, eof, true),
        DecodeTerminator::Refuse(empties) => {
            refused_region_end(bytes, eof, empties)
        }
    }
}

/// Scans a blob until its first terminator or the end of its decodable
/// data and returns the bit position up to which iterating yields its
/// elements. With `padding_ends`, the end of decodable data ends the scan;
/// without it, [`DecodeError::Truncated`] reports a blob without a
/// terminator.
fn region_end(
    bytes: &[u8],
    eof: EofBehavior,
    padding_ends: bool,
) -> Result<usize, DecodeError> {
    let mut reader = BitReader::new(bytes);
    let mut after_control = false;
    let mut char_end = 0;
    loop {
        match reader.read_token(eof)? {
            Some(Token::Char(_)) => {
                char_end = reader.position;
                after_control = false;
            }
            Some(Token::Control) => {
                if after_control {
                    return Ok(char_end);
                }
                after_control = true;
            }
            None => {
                return if padding_ends {
                    Ok(char_end)
                } else {
                    Err(DecodeError::Truncated)
                };
            }
        }
    }
}

/// Scans a blob that must not contain a terminator and returns the bit
/// position up to which iterating yields its elements; consecutive
/// `CONTROL` values are empty elements, treated per `empties`.
fn refused_region_end(
    bytes: &[u8],
    eof: EofBehavior,
    empties: DecodeEmpties,
) -> Result<usize, DecodeError> {
    let mut reader = BitReader::new(bytes);
    let mut has_char = false;
    let mut saw_control = false;
    loop {
        match reader.read_token(eof)? {
            Some(Token::Char(_)) => has_char = true,
            Some(Token::Control) => {
                if !has_char && empties == DecodeEmpties::Reject {
                    return Err(DecodeError::InvalidCodepoint);
                }
                has_char = false;
                saw_control = true;
            }
            None => break,
        }
    }
    if !has_char && saw_control && empties == DecodeEmpties::Reject {
        return Err(DecodeError::InvalidCodepoint);
    }
    Ok(reader.position + usize::from(saw_control && empties == DecodeEmpties::Keep))
}

/// Iterator over the strings of a decoded stringcue blob; see [`decode_all`].
#[derive(Debug, Clone, Copy)]
#[must_use = "iterators are lazy and do nothing unless consumed"]
pub struct DecodeAll<'a> {
    encoded: &'a [u8],
    position: usize,
    end: usize,
    options: DecodeOptions,
}

impl Iterator for DecodeAll<'_> {
    type Item = String;

    fn next(&mut self) -> Option<Self::Item> {
        if self.position >= self.end {
            return None;
        }
        let mut reader = BitReader::new(self.encoded);
        reader.position = self.position;
        let eof = EofBehavior::from(&self.options.terminator);
        let mut string = String::new();
        loop {
            match reader
                .read_token(eof)
                .expect("the blob was validated before iteration")
            {
                Some(Token::Char(c)) => string.push(c),
                Some(Token::Control) => {
                    if string.is_empty()
                        && self.options.terminator == DecodeTerminator::Refuse(DecodeEmpties::Skip)
                    {
                        continue;
                    }
                    self.position = reader.position;
                    return Some(string);
                }
                None => {
                    self.position = self.end;
                    if string.is_empty()
                        && !matches!(
                            self.options.terminator,
                            DecodeTerminator::Refuse(DecodeEmpties::Keep)
                        )
                    {
                        return None;
                    }
                    return Some(string);
                }
            }
        }
    }
}

#[cfg(test)]
mod tests;