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
use super::*;
use crate::{encode, encode_all};
use alloc::vec::Vec;

/// The bits of `a`, `b` and the `CONTROL` value as prefixes.
const A: &str = "1100001";
const B: &str = "1100010";
const CONTROL: &str = "1111111";

/// Encoding options that write the terminator.
fn write_terminator() -> crate::EncodeOptions {
    crate::EncodeOptions {
        terminator: crate::EncodeTerminator::Write,
    }
}

/// Encoding options that encode empty elements.
fn encode_empties() -> crate::EncodeOptions {
    crate::EncodeOptions {
        terminator: crate::EncodeTerminator::Omit(crate::EncodeEmpties::Encode),
    }
}

/// A blob from its bits, padded with ones to the next byte boundary.
fn blob_of(bits: &str) -> Vec<u8> {
    let mut bytes = Vec::new();
    let mut byte = 0u8;
    let mut count = 0;
    for bit in bits.bytes() {
        byte = (byte << 1) | u8::from(bit == b'1');
        count += 1;
        if count == 8 {
            bytes.push(byte);
            byte = 0;
            count = 0;
        }
    }
    if count > 0 {
        let padding = 8 - count;
        bytes.push((byte << padding) | ((1 << padding) - 1));
    }
    bytes
}

#[test]
fn read_bits_extracts_runs_across_byte_boundaries() {
    let bytes = [0b10110001, 0b01011100, 0b11100010, 0xFF];
    for start in 0..bytes.len() * 8 {
        for bits in 1..=25usize {
            if start + bits > bytes.len() * 8 {
                break;
            }
            let mut reader = BitReader {
                bytes: &bytes,
                position: start,
            };
            let expected = (start..start + bits).fold(0u32, |value, offset| {
                (value << 1) | u32::from(bytes[offset / 8] >> (7 - offset % 8) & 1)
            });
            assert_eq!(reader.read_bits(bits as u32), Some(expected));
            assert_eq!(reader.position, start + bits);
        }
    }
    let mut reader = BitReader::new(&bytes);
    assert_eq!(reader.read_bits(33), None);
    assert_eq!(reader.position, 0);
}

#[test]
fn remaining_are_ones_reads_runs_per_byte() {
    let bytes = [0b01111111, 0xFF];
    assert!(!BitReader::new(&bytes).remaining_are_ones());
    assert!(BitReader {
        bytes: &bytes,
        position: 1,
    }
    .remaining_are_ones());
    assert!(BitReader {
        bytes: &bytes,
        position: 16,
    }
    .remaining_are_ones());
}

#[test]
fn decode_roundtrips_encode() {
    let encoded = encode("Hello, world!", Default::default());
    assert_eq!(
        decode(&encoded, Default::default()),
        Ok(String::from("Hello, world!"))
    );
}

#[test]
fn decode_all_roundtrips_encode_all() {
    let strings = ["a", "b"];
    let blob = encode_all(strings, Default::default());
    let decoded: Vec<String> = decode_all(&blob, Default::default())
        .expect("decoding should roundtrip encoding")
        .collect();
    assert_eq!(decoded, strings);
}

#[test]
fn decode_roundtrips_unicode() {
    let string = "\u{80}\u{7FF}\u{FFFF}\u{10FFFF}¡hola, unicode!\0\t\u{7F}";
    let encoded = encode(string, Default::default());
    assert_eq!(
        decode(&encoded, Default::default()),
        Ok(String::from(string))
    );
}

#[test]
fn decode_rejects_truncated_data() {
    let encoded = encode("Hello", Default::default());
    assert_eq!(
        decode(&encoded[..encoded.len() - 1], Default::default()),
        Err(DecodeError::Truncated)
    );
}

#[test]
fn decode_rejects_tail_truncated_mid_codepoint() {
    let encoded = encode("\u{10FFFF}", Default::default());
    assert_eq!(
        decode(&encoded[..encoded.len() - 1], Default::default()),
        Err(DecodeError::Truncated)
    );
}

#[test]
fn decode_stops_at_the_first_control() {
    let blob = encode_all(["a", "b"], Default::default());
    assert_eq!(decode(&blob, Default::default()), Ok(String::from("a")));
}

#[test]
fn decode_requires_the_terminator_when_configured() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Require,
    };
    assert_eq!(
        decode(encode("a", Default::default()), options),
        Err(DecodeError::Truncated)
    );
    assert_eq!(
        decode(encode("a", write_terminator()), options),
        Ok(String::from("a"))
    );
    assert_eq!(decode("", options), Err(DecodeError::Truncated));
}

#[test]
fn required_terminator_aliases_with_padding() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Require,
    };
    let encoded = encode("\u{10FFFF}", write_terminator());
    assert!(decode(&encoded, options).is_ok());
}

#[test]
fn refused_terminator_is_an_error() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Refuse(Default::default()),
    };
    assert_eq!(
        decode(encode("a", write_terminator()), options),
        Err(DecodeError::InvalidCodepoint)
    );
    assert_eq!(
        decode(encode("", write_terminator()), options),
        Err(DecodeError::InvalidCodepoint)
    );
    assert_eq!(
        decode(encode("a", Default::default()), options),
        Ok(String::from("a"))
    );
    assert_eq!(
        decode(encode("\u{10FFFF}", Default::default()), options),
        Ok(String::from("\u{10FFFF}"))
    );
}

#[test]
fn non_canonical_codepoints_are_invalid() {
    let blob = blob_of([T8_PREFIX, "00000000"].concat().as_str());
    assert_eq!(
        decode(&blob, Default::default()),
        Err(DecodeError::InvalidCodepoint)
    );
}

#[test]
fn surrogates_are_invalid() {
    let blob = blob_of([T13_PREFIX, "1100000000000"].concat().as_str());
    assert_eq!(
        decode(&blob, Default::default()),
        Err(DecodeError::InvalidCodepoint)
    );
}

#[test]
fn out_of_range_codepoints_are_invalid() {
    let blob = blob_of([T18_PREFIX, "010000000000000000"].concat().as_str());
    assert_eq!(
        decode(&blob, Default::default()),
        Err(DecodeError::InvalidCodepoint)
    );
}

/// The prefix bits of the `Tail8` length class with payload zero.
const T8_PREFIX: &str = "0001000";

/// The prefix bits of the `Tail13` length class with payload six.
const T13_PREFIX: &str = "0010110";

/// The prefix bits of the `Tail18` length class with payload four.
const T18_PREFIX: &str = "0011100";

#[test]
fn decode_all_accepts_a_superfluous_written_terminator() {
    let strings = ["a", "b"];
    let blob = encode_all(strings, write_terminator());
    let decoded: Vec<String> = decode_all(&blob, Default::default())
        .expect("the terminator is accepted though superfluous")
        .collect();
    assert_eq!(decoded, strings);
}

#[test]
fn decode_all_rejects_a_zero_byte_after_padding() {
    let blob = encode_all(["a", "b"], Default::default());
    let mut corrupted = blob;
    corrupted.push(0);
    assert!(matches!(
        decode_all(&corrupted, Default::default()),
        Err(DecodeError::Truncated)
    ));
}

#[test]
fn decode_all_rejects_garbage_after_padding() {
    let blob = encode_all(["a", "b"], Default::default());
    let mut corrupted = blob;
    corrupted.push(1);
    assert!(matches!(
        decode_all(&corrupted, Default::default()),
        Err(DecodeError::Truncated)
    ));
}

#[test]
fn decode_all_requires_the_terminator_when_configured() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Require,
    };
    let strings = ["a", "b"];
    let blob = encode_all(strings, write_terminator());
    let decoded: Vec<String> = decode_all(&blob, options)
        .expect("the blob ends with the terminator")
        .collect();
    assert_eq!(decoded, strings);

    let unterminated = encode_all(strings, Default::default());
    assert!(matches!(
        decode_all(&unterminated, options),
        Err(DecodeError::Truncated)
    ));

    let nothing: [&str; 0] = [];
    let empty = encode_all(nothing, write_terminator());
    let decoded: Vec<String> = decode_all(&empty, options)
        .expect("the terminator alone is the terminator of no elements")
        .collect();
    assert!(decoded.is_empty());
}

#[test]
fn decode_all_finishes_at_the_first_terminator() {
    let options = [
        DecodeOptions::default(),
        DecodeOptions {
            terminator: DecodeTerminator::Require,
        },
    ];
    let bits = [A, CONTROL, CONTROL, B, CONTROL, CONTROL].concat();
    let blob = blob_of(&bits);
    for options in options {
        let decoded: Vec<String> = decode_all(&blob, options)
            .expect("the first two consecutive controls are the terminator")
            .collect();
        assert_eq!(decoded, ["a"]);
    }

    let encoded = encode_all(["a", "", "b"], encode_empties());
    for options in options {
        let decoded: Vec<String> = decode_all(&encoded, options)
            .expect("the empty element encodes the terminator")
            .collect();
        assert_eq!(decoded, ["a"]);
    }
}

#[test]
fn decode_all_ignores_what_follows_the_terminator() {
    let options = [
        DecodeOptions::default(),
        DecodeOptions {
            terminator: DecodeTerminator::Require,
        },
    ];
    let blob = encode_all(["a", "b"], write_terminator());
    let mut followed = blob;
    followed.push(0xFF);
    followed.push(0x01);
    for options in options {
        let decoded: Vec<String> = decode_all(&followed, options)
            .expect("decoding finishes at the terminator")
            .collect();
        assert_eq!(decoded, ["a", "b"]);
    }
}

#[test]
fn decode_all_accepts_the_single_string_terminator() {
    let blob = encode("a", write_terminator());
    let decoded: Vec<String> = decode_all(&blob, Default::default())
        .expect("the terminator is indistinguishable from a trailing empty element")
        .collect();
    assert_eq!(decoded, ["a"]);
}

#[test]
fn decode_all_refuse_keeps_empty_elements() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Refuse(DecodeEmpties::Keep),
    };
    let blob = encode_all(["a", ""], encode_empties());
    let decoded: Vec<String> = decode_all(&blob, options)
        .expect("consecutive separators are empty elements")
        .collect();
    assert_eq!(decoded, ["a", ""]);

    let bits = [CONTROL, A, CONTROL].concat();
    let mixed = blob_of(&bits);
    let decoded: Vec<String> = decode_all(&mixed, options)
        .expect("consecutive separators are empty elements")
        .collect();
    assert_eq!(decoded, ["", "a", ""]);
}

#[test]
fn decode_all_refuse_skips_empty_elements() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Refuse(DecodeEmpties::Skip),
    };
    let blob = encode_all(["a", "", "b"], encode_empties());
    let decoded: Vec<String> = decode_all(&blob, options)
        .expect("consecutive separators are empty elements")
        .collect();
    assert_eq!(decoded, ["a", "b"]);
}

#[test]
fn decode_all_refuse_rejects_empty_elements() {
    let options = DecodeOptions {
        terminator: DecodeTerminator::Refuse(DecodeEmpties::Reject),
    };
    let trailing = encode_all(["a", ""], encode_empties());
    assert!(matches!(
        decode_all(&trailing, options),
        Err(DecodeError::InvalidCodepoint)
    ));

    let middle = encode_all(["a", "", "b"], encode_empties());
    assert!(matches!(
        decode_all(&middle, options),
        Err(DecodeError::InvalidCodepoint)
    ));
}

#[test]
fn empty_blobs_decode_by_terminator_option() {
    let blob = encode("", Default::default());
    let decoded: Vec<String> = decode_all(&blob, Default::default())
        .expect("an empty blob is an empty container")
        .collect();
    assert!(decoded.is_empty());
    assert_eq!(decode(&blob, Default::default()), Ok(String::new()));

    let options = DecodeOptions {
        terminator: DecodeTerminator::Require,
    };
    assert!(matches!(decode_all(&blob, options), Err(DecodeError::Truncated)));
    assert_eq!(decode(&blob, options), Err(DecodeError::Truncated));

    let options = DecodeOptions {
        terminator: DecodeTerminator::Refuse(Default::default()),
    };
    let decoded: Vec<String> = decode_all(&blob, options)
        .expect("an empty blob is an empty container")
        .collect();
    assert!(decoded.is_empty());
}