spinoso_string/enc/binary/
mod.rs

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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
use alloc::collections::TryReserveError;
use core::fmt;
use core::ops::Range;
use core::slice::SliceIndex;

use bstr::ByteSlice;
use scolapasta_strbuf::Buf;

use crate::codepoints::InvalidCodepointError;
use crate::iter::{Bytes, IntoIter, Iter, IterMut};
use crate::ord::OrdError;

mod codepoints;
mod eq;
mod impls;
mod inspect;
#[cfg(feature = "std")]
mod io;

pub use codepoints::Codepoints;
pub use inspect::Inspect;

#[repr(transparent)]
#[derive(Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct BinaryString {
    inner: Buf,
}

// Constructors
impl BinaryString {
    pub const fn new(buf: Buf) -> Self {
        Self { inner: buf }
    }
}

impl fmt::Debug for BinaryString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BinaryString")
            .field("buf", &self.inner.as_bstr())
            .finish()
    }
}

// Raw
impl BinaryString {
    #[inline]
    #[must_use]
    pub fn into_buf(self) -> Buf {
        self.inner
    }

    #[inline]
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        self.inner.as_slice()
    }

    #[inline]
    #[must_use]
    pub fn as_mut_slice(&mut self) -> &mut [u8] {
        self.inner.as_mut_slice()
    }

    #[inline]
    #[must_use]
    pub fn as_ptr(&self) -> *const u8 {
        self.inner.as_ptr()
    }

    #[inline]
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.inner.as_mut_ptr()
    }
}

// Core Iterators
impl BinaryString {
    #[inline]
    #[must_use]
    pub fn iter(&self) -> Iter<'_> {
        Iter::from_slice(&self.inner)
    }

    #[inline]
    #[must_use]
    pub fn iter_mut(&mut self) -> IterMut<'_> {
        IterMut::from_mut_slice(&mut self.inner)
    }

    #[inline]
    #[must_use]
    pub fn bytes(&self) -> Bytes<'_> {
        Bytes::from_slice(&self.inner)
    }

    #[inline]
    #[must_use]
    pub fn into_iter(self) -> IntoIter {
        IntoIter::from_vec(self.inner.into_inner())
    }
}

// Size and Capacity
impl BinaryString {
    #[inline]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    #[inline]
    pub unsafe fn set_len(&mut self, len: usize) {
        self.inner.set_len(len);
    }

    #[inline]
    #[must_use]
    pub fn capacity(&self) -> usize {
        self.inner.capacity()
    }

    #[inline]
    pub fn clear(&mut self) {
        self.inner.clear();
    }

    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    #[inline]
    pub fn truncate(&mut self, len: usize) {
        self.inner.truncate(len);
    }

    #[inline]
    #[must_use]
    pub fn char_len(&self) -> usize {
        self.len()
    }
}

// Memory management
impl BinaryString {
    #[inline]
    pub fn reserve(&mut self, additional: usize) {
        self.inner.reserve(additional);
    }

    #[inline]
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve(additional)
    }

    #[inline]
    pub fn reserve_exact(&mut self, additional: usize) {
        self.inner.reserve_exact(additional);
    }

    #[inline]
    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
        self.inner.try_reserve_exact(additional)
    }

    #[inline]
    pub fn shrink_to_fit(&mut self) {
        self.inner.shrink_to_fit();
    }

    #[inline]
    pub fn shrink_to(&mut self, min_capacity: usize) {
        self.inner.shrink_to(min_capacity);
    }
}

// Indexing
impl BinaryString {
    #[inline]
    #[must_use]
    pub fn get<I>(&self, index: I) -> Option<&I::Output>
    where
        I: SliceIndex<[u8]>,
    {
        self.inner.get(index)
    }

    #[inline]
    #[must_use]
    pub fn get_char(&self, index: usize) -> Option<&'_ [u8]> {
        self.get(index..=index)
    }

    #[inline]
    #[must_use]
    pub fn get_char_slice(&self, range: Range<usize>) -> Option<&'_ [u8]> {
        let Range { start, end } = range;

        self.inner.get(start..end).or_else(|| {
            if start > self.inner.len() {
                None
            } else if end <= start {
                Some(&[])
            } else {
                self.inner.get(start..)
            }
        })
    }

    #[inline]
    #[must_use]
    pub fn get_mut<I>(&mut self, index: I) -> Option<&mut I::Output>
    where
        I: SliceIndex<[u8]>,
    {
        self.inner.get_mut(index)
    }

    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked<I>(&self, index: I) -> &I::Output
    where
        I: SliceIndex<[u8]>,
    {
        self.inner.get_unchecked(index)
    }

    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked_mut<I>(&mut self, index: I) -> &mut I::Output
    where
        I: SliceIndex<[u8]>,
    {
        self.inner.get_unchecked_mut(index)
    }
}

// Pushing and popping bytes, codepoints, and strings.
impl BinaryString {
    #[inline]
    pub fn push_byte(&mut self, byte: u8) {
        self.inner.push_byte(byte);
    }

    #[inline]
    pub fn try_push_codepoint(&mut self, codepoint: i64) -> Result<(), InvalidCodepointError> {
        if let Ok(byte) = u8::try_from(codepoint) {
            self.push_byte(byte);
            Ok(())
        } else {
            Err(InvalidCodepointError::codepoint_out_of_range(codepoint))
        }
    }

    #[inline]
    pub fn try_push_int(&mut self, int: i64) -> Result<(), InvalidCodepointError> {
        self.try_push_codepoint(int)
    }

    #[inline]
    pub fn push_char(&mut self, ch: char) {
        self.inner.push_char(ch);
    }

    #[inline]
    pub fn push_str(&mut self, s: &str) {
        self.inner.push_str(s);
    }

    #[inline]
    pub fn extend_from_slice(&mut self, other: &[u8]) {
        self.inner.extend_from_slice(other);
    }
}

// Encoding
impl BinaryString {
    #[inline]
    #[must_use]
    pub fn is_ascii_only(&self) -> bool {
        self.inner.is_ascii()
    }

    #[inline]
    #[must_use]
    #[allow(clippy::unused_self)]
    pub fn is_valid_encoding(&self) -> bool {
        true
    }
}

// Casing
impl BinaryString {
    #[inline]
    pub fn make_capitalized(&mut self) {
        if let Some((head, tail)) = self.inner.split_first_mut() {
            head.make_ascii_uppercase();
            tail.make_ascii_lowercase();
        }
    }

    #[inline]
    pub fn make_lowercase(&mut self) {
        self.inner.make_ascii_lowercase();
    }

    #[inline]
    pub fn make_uppercase(&mut self) {
        self.inner.make_ascii_uppercase();
    }
}

impl BinaryString {
    #[inline]
    #[must_use]
    pub fn chr(&self) -> &[u8] {
        self.inner.get(0..1).unwrap_or_default()
    }

    #[inline]
    pub fn ord(&self) -> Result<u32, OrdError> {
        let byte = self.inner.first().copied().ok_or_else(OrdError::empty_string)?;
        Ok(u32::from(byte))
    }

    #[inline]
    #[must_use]
    pub fn ends_with(&self, slice: &[u8]) -> bool {
        self.inner.ends_with(slice)
    }

    #[inline]
    pub fn reverse(&mut self) {
        self.inner.reverse();
    }
}

// Index
impl BinaryString {
    #[inline]
    #[must_use]
    pub fn index(&self, needle: &[u8], offset: usize) -> Option<usize> {
        let buf = self.get(offset..)?;
        let index = buf.find(needle)?;
        Some(index + offset)
    }

    #[inline]
    #[must_use]
    pub fn rindex(&self, needle: &[u8], offset: usize) -> Option<usize> {
        let buf = self.get(..=offset).unwrap_or_else(|| self.as_slice());
        let index = buf.rfind(needle)?;
        Some(index)
    }
}

#[cfg(test)]
mod tests {
    use alloc::string::String;
    use alloc::vec::Vec;

    use quickcheck::quickcheck;

    use super::BinaryString;

    quickcheck! {
        fn fuzz_char_len_utf8_contents_binary_string(contents: String) -> bool {
            let expected = contents.len();
            let s = BinaryString::from(contents);
            s.char_len() == expected
        }

        fn fuzz_len_utf8_contents_binary_string(contents: String) -> bool {
            let expected = contents.len();
            let s = BinaryString::from(contents);
            s.len() == expected
        }

        fn fuzz_char_len_binary_contents_binary_string(contents: Vec<u8>) -> bool {
            let expected = contents.len();
            let s = BinaryString::from(contents);
            s.char_len() == expected
        }

        fn fuzz_len_binary_contents_binary_string(contents: Vec<u8>) -> bool {
            let expected = contents.len();
            let s = BinaryString::from(contents);
            s.len() == expected
        }
    }

    #[test]
    fn constructs_empty_buffer() {
        let s = BinaryString::from(Vec::new());
        assert_eq!(0, s.len());
    }

    #[test]
    fn casing_binary_string_empty() {
        let mut s = BinaryString::from(b"");

        s.make_capitalized();
        assert_eq!(s, "");

        s.make_lowercase();
        assert_eq!(s, "");

        s.make_uppercase();
        assert_eq!(s, "");
    }

    #[test]
    fn casing_binary_string_ascii() {
        let lower = BinaryString::from(b"abc");
        let mid_upper = BinaryString::from(b"aBc");
        let upper = BinaryString::from(b"ABC");
        let long = BinaryString::from(b"aBC, 123, ABC, baby you and me girl");

        let capitalize: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_capitalized();
            value
        };
        let lowercase: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_lowercase();
            value
        };
        let uppercase: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_uppercase();
            value
        };

        assert_eq!(capitalize(&lower), "Abc");
        assert_eq!(capitalize(&mid_upper), "Abc");
        assert_eq!(capitalize(&upper), "Abc");
        assert_eq!(capitalize(&long), "Abc, 123, abc, baby you and me girl");

        assert_eq!(lowercase(&lower), "abc");
        assert_eq!(lowercase(&mid_upper), "abc");
        assert_eq!(lowercase(&upper), "abc");
        assert_eq!(lowercase(&long), "abc, 123, abc, baby you and me girl");

        assert_eq!(uppercase(&lower), "ABC");
        assert_eq!(uppercase(&mid_upper), "ABC");
        assert_eq!(uppercase(&upper), "ABC");
        assert_eq!(uppercase(&long), "ABC, 123, ABC, BABY YOU AND ME GIRL");
    }

    #[test]
    fn casing_binary_string_utf8() {
        let sharp_s = BinaryString::from("ß");
        let tomorrow = BinaryString::from("αύριο");
        let year = BinaryString::from("έτος");
        // two-byte characters
        // https://github.com/minimaxir/big-list-of-naughty-strings/blob/894882e7/blns.txt#L198-L200
        let two_byte_chars = BinaryString::from("𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆");
        // Changes length when case changes
        // https://github.com/minimaxir/big-list-of-naughty-strings/blob/894882e7/blns.txt#L226-L232
        let varying_length = BinaryString::from("zȺȾ");
        let rtl = BinaryString::from("مرحبا الخرشوف");

        let capitalize: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_capitalized();
            value
        };
        let lowercase: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_lowercase();
            value
        };
        let uppercase: fn(&BinaryString) -> BinaryString = |value: &BinaryString| {
            let mut value = value.clone();
            value.make_uppercase();
            value
        };

        assert_eq!(capitalize(&sharp_s), "ß");
        assert_eq!(capitalize(&tomorrow), "αύριο");
        assert_eq!(capitalize(&year), "έτος");
        assert_eq!(
            capitalize(&two_byte_chars),
            "𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆"
        );
        assert_eq!(capitalize(&varying_length), "ZȺȾ");
        assert_eq!(capitalize(&rtl), "مرحبا الخرشوف");

        assert_eq!(lowercase(&sharp_s), "ß");
        assert_eq!(lowercase(&tomorrow), "αύριο");
        assert_eq!(lowercase(&year), "έτος");
        assert_eq!(
            lowercase(&two_byte_chars),
            "𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆"
        );
        assert_eq!(lowercase(&varying_length), "zȺȾ");
        assert_eq!(lowercase(&rtl), "مرحبا الخرشوف");

        assert_eq!(uppercase(&sharp_s), "ß");
        assert_eq!(uppercase(&tomorrow), "αύριο");
        assert_eq!(uppercase(&year), "έτος");
        assert_eq!(
            uppercase(&two_byte_chars),
            "𐐜 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐙𐐊𐐡𐐝𐐓/𐐝𐐇𐐗𐐊𐐤𐐔 𐐒𐐋𐐗 𐐒𐐌 𐐜 𐐡𐐀𐐖𐐇𐐤𐐓𐐝 𐐱𐑂 𐑄 𐐔𐐇𐐝𐐀𐐡𐐇𐐓 𐐏𐐆𐐅𐐤𐐆𐐚𐐊𐐡𐐝𐐆𐐓𐐆"
        );
        assert_eq!(uppercase(&varying_length), "ZȺȾ");
        assert_eq!(uppercase(&rtl), "مرحبا الخرشوف");
    }

    #[test]
    fn casing_binary_string_invalid_utf8() {
        let mut s = BinaryString::from(b"\xFF\xFE");

        s.make_capitalized();
        assert_eq!(s, &b"\xFF\xFE"[..]);

        s.make_lowercase();
        assert_eq!(s, &b"\xFF\xFE"[..]);

        s.make_uppercase();
        assert_eq!(s, &b"\xFF\xFE"[..]);
    }

    #[test]
    fn casing_binary_string_unicode_replacement_character() {
        let mut s = BinaryString::from("�");
        s.make_capitalized();
        assert_eq!(s, "�");
    }

    #[test]
    fn get_char_slice_valid_range() {
        let s = BinaryString::from("abc");
        assert_eq!(s.get_char_slice(0..0), Some(&b""[..]));
        assert_eq!(s.get_char_slice(0..1), Some(&b"a"[..]));
        assert_eq!(s.get_char_slice(0..2), Some(&b"ab"[..]));
        assert_eq!(s.get_char_slice(0..3), Some(&b"abc"[..]));
        assert_eq!(s.get_char_slice(0..4), Some(&b"abc"[..]));
        assert_eq!(s.get_char_slice(1..1), Some(&b""[..]));
        assert_eq!(s.get_char_slice(1..2), Some(&b"b"[..]));
        assert_eq!(s.get_char_slice(1..3), Some(&b"bc"[..]));
    }

    #[test]
    #[allow(clippy::reversed_empty_ranges)]
    fn get_char_slice_invalid_range() {
        let s = BinaryString::from("abc");
        assert_eq!(s.get_char_slice(4..5), None);
        assert_eq!(s.get_char_slice(4..1), None);
        assert_eq!(s.get_char_slice(3..1), Some(&b""[..]));
        assert_eq!(s.get_char_slice(2..1), Some(&b""[..]));
    }

    #[test]
    fn index_with_default_offset() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.index("f".as_bytes(), 0), Some(0));
        assert_eq!(s.index("o".as_bytes(), 0), Some(1));
        assert_eq!(s.index("oo".as_bytes(), 0), Some(1));
        assert_eq!(s.index("ooo".as_bytes(), 0), None);
    }

    #[test]
    fn index_with_different_offset() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.index("o".as_bytes(), 1), Some(1));
        assert_eq!(s.index("o".as_bytes(), 2), Some(2));
        assert_eq!(s.index("o".as_bytes(), 3), None);
    }

    #[test]
    fn index_offset_no_overflow() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.index("o".as_bytes(), usize::MAX), None);
    }

    #[test]
    fn index_empties() {
        // ```console
        // [3.2.2] > "".index ""
        // => 0
        // [3.2.2] > "".index "a"
        // => nil
        // [3.2.2] > "a".index ""
        // => 0
        // ```
        let s = BinaryString::from("");
        assert_eq!(s.index(b"", 0), Some(0));

        assert_eq!(s.index(b"a", 0), None);

        let s = BinaryString::from("a");
        assert_eq!(s.index(b"", 0), Some(0));
    }

    #[test]
    fn rindex_with_default_offset() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.rindex("f".as_bytes(), 2), Some(0));
        assert_eq!(s.rindex("o".as_bytes(), 2), Some(2));
        assert_eq!(s.rindex("oo".as_bytes(), 2), Some(1));
        assert_eq!(s.rindex("ooo".as_bytes(), 2), None);
    }

    #[test]
    fn rindex_with_different_offset() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.rindex("o".as_bytes(), 3), Some(2));
        assert_eq!(s.rindex("o".as_bytes(), 2), Some(2));
        assert_eq!(s.rindex("o".as_bytes(), 1), Some(1));
        assert_eq!(s.rindex("o".as_bytes(), 0), None);
    }

    #[test]
    fn rindex_offset_no_overflow() {
        let s = BinaryString::from(b"foo");
        assert_eq!(s.rindex("o".as_bytes(), usize::MAX), Some(2));
    }

    #[test]
    fn rindex_empties() {
        // ```console
        // [3.2.2] > "".rindex ""
        // => 0
        // [3.2.2] > "".rindex "a"
        // => nil
        // [3.2.2] > "a".rindex ""
        // => 1
        // ```
        let s = BinaryString::from("");
        assert_eq!(s.rindex(b"", usize::MAX), Some(0));
        assert_eq!(s.rindex(b"", 1), Some(0));
        assert_eq!(s.rindex(b"", 0), Some(0));

        assert_eq!(s.rindex(b"a", usize::MAX), None);
        assert_eq!(s.rindex(b"a", 1), None);
        assert_eq!(s.rindex(b"a", 0), None);

        let s = BinaryString::from("a");
        assert_eq!(s.rindex(b"", usize::MAX), Some(1));
        assert_eq!(s.rindex(b"", 1), Some(1));
    }
}