enrede 0.2.0

An easy-to-use string encoding library, providing an interface similar to str/String.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
use crate::encoding::sealed::Sealed;
use crate::encoding::{NullTerminable, ValidateError};
use crate::{Encoding, Str};
use arrayvec::ArrayVec;
#[cfg(feature = "rand")]
use rand::{distr::Distribution, Rng};

mod x0208_tables;

const DECODE_MAP_0201: [char; 63] = [
    '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
    '', '', '', '', '', '', '', '', '', '', '', 'ソ', '', '', '', '', '', '', '',
    '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
    '', '', '', '', '', '',
];

/// The [JIS X 0201](https://en.wikipedia.org/wiki/JIS_X_0201) encoding.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct JisX0201;

impl Sealed for JisX0201 {}

impl Encoding for JisX0201 {
    const REPLACEMENT: char = '?';
    const MAX_LEN: usize = 1;
    type Bytes = u8;

    fn shorthand() -> &'static str {
        "jisx0201"
    }

    fn validate(bytes: &[u8]) -> Result<(), ValidateError> {
        bytes.iter().enumerate().try_for_each(|(idx, c)| {
            if (..0x20).contains(c) || (0x80..0xA1).contains(c) || (0xE0..).contains(c) {
                Err(ValidateError {
                    valid_up_to: idx,
                    error_len: Some(1),
                })
            } else {
                Ok(())
            }
        })
    }

    fn encode_char(c: char) -> Option<Self::Bytes> {
        if c == '¥' {
            Some(0x5C)
        } else if c == '' {
            Some(0x7E)
        } else if (0x20..0x80).contains(&(c as u32)) {
            Some(c as u8)
        } else {
            let pos = DECODE_MAP_0201.iter().position(|v| *v == c)? as u8;
            Some(pos + 0xA1)
        }
    }

    fn decode_char(str: &Str<Self>) -> (char, &Str<Self>) {
        let b = str.as_bytes()[0];
        if b == 0x5C {
            ('¥', &str[1..])
        } else if b == 0x7E {
            ('', &str[1..])
        } else if (..0x80).contains(&b) {
            (b as char, &str[1..])
        } else {
            (DECODE_MAP_0201[b as usize - 0xA1], &str[1..])
        }
    }

    fn char_bound(_: &Str<Self>, _: usize) -> bool {
        true
    }

    fn char_len(c: char) -> usize {
        if (0x20..0x80).contains(&(c as u32)) || DECODE_MAP_0201.contains(&c) {
            1
        } else {
            0
        }
    }
}

impl NullTerminable for JisX0201 {}

#[cfg(feature = "rand")]
impl Distribution<char> for JisX0201 {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
        // Number of JIS 0201 characters
        let c = rng.random_range(0..159);
        let c = if c < 0x60 { c + 0x20 } else { c + 0x41 };
        Self::decode_char(unsafe { Str::from_bytes_unchecked(&[c]) }).0
    }
}

/// The [JIS X 0208](https://en.wikipedia.org/wiki/JIS_X_0208) encoding.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct JisX0208;

impl Sealed for JisX0208 {}

impl Encoding for JisX0208 {
    const REPLACEMENT: char = '?';
    const MAX_LEN: usize = 2;
    type Bytes = ArrayVec<u8, 2>;

    fn shorthand() -> &'static str {
        "jisx0208"
    }

    fn validate(bytes: &[u8]) -> Result<(), ValidateError> {
        let mut row = 0;
        for (idx, b) in bytes.iter().enumerate() {
            if *b >= 0x80 {
                return Err(ValidateError {
                    valid_up_to: idx,
                    error_len: Some(1),
                });
            } else if row == 0 {
                // Tables with no valid characters - fast path
                if ((0x29..0x30).contains(b) && *b != 0x2D) || (0x75..0x7F).contains(b) {
                    return Err(ValidateError {
                        valid_up_to: idx,
                        error_len: Some(2),
                    });
                } else if (0x21..0x7F).contains(b) {
                    row = *b - 0x20;
                }
                // Characters in range 0..0x20 are ASCII control codes
            } else if row != 0 {
                if !(0x21..0x7F).contains(b)
                    || x0208_tables::DECODE_MAP_0208[(row - 1) as usize][(*b - 0x21) as usize]
                        == ''
                {
                    return Err(ValidateError {
                        valid_up_to: idx - 1,
                        error_len: Some(2),
                    });
                }
                row = 0;
            }
        }
        Ok(())
    }

    fn encode_char(c: char) -> Option<Self::Bytes> {
        if c as u32 <= 0x20 || c as u32 == 0x7F {
            Some(ArrayVec::from_iter([c as u8]))
        } else {
            let (row, col) = x0208_tables::ENCODE_MAP_0208[&c];
            Some(ArrayVec::from([row as u8 + 0x21, col as u8 + 0x21]))
        }
    }

    fn decode_char(str: &Str<Self>) -> (char, &Str<Self>) {
        let bytes = str.as_bytes();
        let first = bytes[0];
        if (..0x21).contains(&first) || first == 0x7F {
            (char::from(first), unsafe { str.get_unchecked(1..) })
        } else {
            let second = bytes[1];
            let (row, col) = (first - 0x21, second - 0x21);
            let c = x0208_tables::DECODE_MAP_0208[row as usize][col as usize];
            (c, unsafe { str.get_unchecked(2..) })
        }
    }

    fn char_bound(str: &Str<Self>, idx: usize) -> bool {
        let bytes = str.as_bytes();
        let first = bytes[0];
        // Control code bytes, space, and del - always single-byte, never used as a second byte
        if (..0x21).contains(&first) || first == 0x7F {
            true
        } else {
            // Otherwise, first and second bytes look the same - iterate to here
            for (idx2, _) in str.char_indices() {
                if idx == idx2 {
                    return true;
                } else if idx < idx2 {
                    return false;
                }
            }
            false
        }
    }

    fn char_len(c: char) -> usize {
        if (..0x21).contains(&(c as u32)) || c as u32 == 0x7F {
            1
        } else if x0208_tables::DECODE_MAP_0208
            .iter()
            .any(|row| row.iter().any(|v| *v == c))
        {
            2
        } else {
            0
        }
    }
}

impl NullTerminable for JisX0208 {}

#[cfg(feature = "rand")]
impl Distribution<char> for JisX0208 {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
        let c = rng.random_range(0..x0208_tables::RAND_MAP_0208.len() + 22);
        if c <= 21 {
            if c == 21 {
                '\x7F'
            } else {
                char::from(c as u8)
            }
        } else {
            x0208_tables::RAND_MAP_0208[c - 22]
        }
    }
}

/// The [ShiftJIS](https://en.wikipedia.org/wiki/Shift_JIS) encoding.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct ShiftJIS;

impl Sealed for ShiftJIS {}

impl Encoding for ShiftJIS {
    const REPLACEMENT: char = '?';
    const MAX_LEN: usize = 2;
    type Bytes = ArrayVec<u8, 2>;

    fn shorthand() -> &'static str {
        "shiftjis"
    }

    fn validate(bytes: &[u8]) -> Result<(), ValidateError> {
        let mut row = 0;
        for (idx, b) in bytes.iter().enumerate() {
            if row == 0 {
                // Single-byte characters
                if (0..0x80).contains(b) || (0xA1..0xE0).contains(b) {
                    continue;
                // First set of row values
                } else if (0x81..0xA0).contains(b) {
                    row = *b - 0x80;
                // Second set of row values
                } else if (0xE0..0xF0).contains(b) {
                    row = *b - 0xC1;
                } else {
                    return Err(ValidateError {
                        valid_up_to: idx,
                        error_len: Some(1),
                    });
                }
            } else if row != 0 {
                row -= 1;
                let column = if (0x9F..0xFD).contains(b) {
                    row = row * 2 + 1;
                    *b - 0x9F
                } else if (0x40..0x7F).contains(b) {
                    row *= 2;
                    *b - 0x40
                } else if (0x80..0x9F).contains(b) {
                    row *= 2;
                    *b - 0x41
                } else {
                    return Err(ValidateError {
                        valid_up_to: idx - 1,
                        error_len: Some(2),
                    });
                };
                if x0208_tables::DECODE_MAP_0208[row as usize][column as usize] == '' {
                    return Err(ValidateError {
                        valid_up_to: idx - 1,
                        error_len: Some(2),
                    });
                }
                row = 0;
            }
        }
        Ok(())
    }

    fn encode_char(c: char) -> Option<Self::Bytes> {
        match JisX0201::encode_char(c) {
            Some(c) => return Some(ArrayVec::from_iter([c])),
            None => (),
        }
        let (row, col) = x0208_tables::ENCODE_MAP_0208[&c];
        let row = row + 0x21;
        let row_e = if row <= 0x5E {
            ((row + 1) / 2) + 112
        } else {
            ((row + 1) / 2) + 176
        };
        let col_e = if row % 2 == 0 {
            col + 159
        } else {
            col + 64 + (col / 63)
        };
        Some(ArrayVec::from([row_e as u8, col_e as u8]))
    }

    fn decode_char(str: &Str<Self>) -> (char, &Str<Self>) {
        let bytes = str.as_bytes();
        let first = bytes[0];
        if (..0x80).contains(&first) || (0xA1..0xE0).contains(&first) {
            let c = if first == 0x5C {
                '¥'
            } else if first == 0x7E {
                ''
            } else if (..0x80).contains(&first) {
                first as char
            } else {
                DECODE_MAP_0201[first as usize - 0xA1]
            };
            (c, unsafe { str.get_unchecked(1..) })
        } else {
            let second = bytes[1];
            let mut row = if (0x81..0xA0).contains(&first) {
                first - 0x81
            } else {
                first - 0xC1
            };
            let col = if (0x40..0x7F).contains(&second) {
                row *= 2;
                second - 0x40
            } else if (0x80..0x9F).contains(&second) {
                row *= 2;
                second - 0x41
            // (0x9F..0xFD).contains(&second)
            } else {
                row = row * 2 + 1;
                second - 0x9F
            };
            let c = x0208_tables::DECODE_MAP_0208[row as usize][col as usize];
            (c, unsafe { str.get_unchecked(2..) })
        }
    }

    fn char_bound(str: &Str<Self>, idx: usize) -> bool {
        let bytes = str.as_bytes();
        let first = bytes[0];
        // Control code bytes, space, and del - always single-byte, never used as a second byte
        if (..0x40).contains(&first) || first == 0x7F {
            true
        } else {
            // Otherwise, first and second bytes look the same - iterate to here
            for (idx2, _) in str.char_indices() {
                if idx == idx2 {
                    return true;
                } else if idx < idx2 {
                    return false;
                }
            }
            false
        }
    }

    fn char_len(c: char) -> usize {
        if (..0x80).contains(&(c as u32)) || DECODE_MAP_0201.contains(&c) {
            1
        } else if x0208_tables::DECODE_MAP_0208
            .iter()
            .any(|row| row.iter().any(|v| *v == c))
        {
            2
        } else {
            0
        }
    }
}

impl NullTerminable for ShiftJIS {}

#[cfg(feature = "rand")]
impl Distribution<char> for ShiftJIS {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> char {
        let c = rng.random_range(0..(x0208_tables::RAND_MAP_0208.len() + 158));
        if c <= 158 {
            let c = if c < 0x60 { c + 0x20 } else { c + 0x41 };
            JisX0201::decode_char(unsafe { Str::from_bytes_unchecked(&[c as u8]) }).0
        } else {
            x0208_tables::RAND_MAP_0208[c - 159]
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const HELLO_WORLD_JIS0208: &[u8] = &[
        0x25, 0x4F, 0x25, 0x6D, 0x21, 0x3C, 0x25, 0x6F, 0x21, 0x3C, 0x25, 0x6B, 0x25, 0x49, 0x21,
        0x6F, 0x23, 0x6E, 0x24, 0x21,
    ];

    #[test]
    fn test_validate_jisx0208() {
        assert!(JisX0208::validate(HELLO_WORLD_JIS0208).is_ok());
    }

    #[test]
    fn test_decode_jisx0208() {
        let str = unsafe { Str::<JisX0208>::from_bytes_unchecked(HELLO_WORLD_JIS0208) };
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, '¥');
        let (c, str) = JisX0208::decode_char(&str);
        assert_eq!(c, 'n');
        let (c, _) = JisX0208::decode_char(&str);
        assert_eq!(c, '');
    }

    const HELLO_WORLD_SHIFTJIS: &[u8] = &[
        0x83, 0x6E, 0x83, 0x8D, 0x81, 0x5B, 0x83, 0x8F, 0x81, 0x5B, 0x83, 0x8B, 0x83, 0x68, 0x5C,
        0x6E, 0x82, 0x9F,
    ];

    #[test]
    fn test_validate_shiftjis() {
        assert!(ShiftJIS::validate(HELLO_WORLD_SHIFTJIS).is_ok());
    }

    #[test]
    fn test_encode_shiftjis() {
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x83, 0x6E]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x83, 0x8D]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x81, 0x5B]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x83, 0x8F]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x83, 0x8B]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x83, 0x68]))
        );
        assert_eq!(
            ShiftJIS::encode_char('¥'),
            Some(ArrayVec::from_iter([0x5C]))
        );
        assert_eq!(
            ShiftJIS::encode_char('n'),
            Some(ArrayVec::from_iter([0x6E]))
        );
        assert_eq!(
            ShiftJIS::encode_char(''),
            Some(ArrayVec::from_iter([0x82, 0x9F]))
        );
    }

    #[test]
    fn test_decode_shiftjis() {
        let str = unsafe { Str::<ShiftJIS>::from_bytes_unchecked(HELLO_WORLD_SHIFTJIS) };
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '¥');
        let (c, str) = ShiftJIS::decode_char(&str);
        assert_eq!(c, 'n');
        let (c, _) = ShiftJIS::decode_char(&str);
        assert_eq!(c, '');
    }
}