string32 0.2.0

A string that is indexed by u32 instead of usize
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
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
use std::borrow::{Borrow, BorrowMut, Cow};
use std::cmp;
use std::convert::{TryFrom, TryInto};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::iter::FromIterator;
use std::mem;
use std::ops;
use std::string;

use mediumvec::Vec32;
use usize_cast::IntoUsize;

use super::{Str32, TryFromStrError, TryFromStringError};

/// A string that is indexed by `u32` instead of `usize`.
///
/// On 64-bit platforms, `String32` only requires 16 bytes to store the pointer, length, and capacity. [`String`] by comparison requires 24 bytes, plus padding.
#[derive(Clone, Debug, Default, Eq)]
#[repr(transparent)]
pub struct String32(Vec32<u8>);

impl String32 {
    /// Create an empty `String32`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let s = String32::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self(Vec32::new())
    }

    /// Create an empty `String32` with enough capacity to hold `cap` bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::with_capacity(1);
    /// let cap = s.capacity();
    /// s.push('\n');
    /// assert_eq!(cap, s.capacity());
    /// ```
    #[must_use]
    pub fn with_capacity(cap: u32) -> Self {
        Self(Vec32::with_capacity(cap))
    }

    /// Return the capacity of this `String32` in bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::new();
    /// assert_eq!(0, s.capacity());
    /// s.push('\n');
    /// assert!(s.capacity() > 0);
    /// ```
    #[must_use]
    pub fn capacity(&self) -> u32 {
        self.0.capacity()
    }

    /// A helper to call arbitrary [`String`] methods on a `String32.`
    ///
    /// # Panics
    ///
    /// Panics if the resulting string would require more than [`u32::MAX`] bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::new();
    /// s.as_string(|s| s.push_str("test"));
    /// assert_eq!(s, "test");
    /// ```
    pub fn as_string<F, T>(&mut self, f: F) -> T
    where
        F: FnOnce(&mut String) -> T,
    {
        let mut s = mem::take(self).into();
        let ret = f(&mut s);
        *self = s.try_into().unwrap();
        ret
    }

    /// Push a `char` to the end of this `String32`.
    ///
    /// # Panics
    ///
    /// Panics if the resulting string would require more than [`u32::MAX`] bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::new();
    /// s.push('\n');
    /// assert_eq!(s, "\n");
    /// ```
    pub fn push(&mut self, ch: char) {
        self.as_string(|s| s.push(ch));
    }

    /// Append a string slice to the end of this `String32`.
    ///
    /// # Panics
    ///
    /// Panics if the resulting string would require more than [`u32::MAX`] bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::new();
    /// s.push_str("test");
    /// assert_eq!(s, "test");
    /// ```
    pub fn push_str<S>(&mut self, s: S)
    where
        S: AsRef<str>,
    {
        self.as_string(|st| st.push_str(s.as_ref()));
    }

    /// Pop a `char` from the end of this `String32`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("\n").unwrap();
    /// assert_eq!(s.pop(), Some('\n'));
    /// assert_eq!(s.pop(), None);
    /// ```
    pub fn pop(&mut self) -> Option<char> {
        self.as_string(String::pop)
    }

    /// Return the `char` at a given byte index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is not a UTF-8 code point boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("abbc").unwrap();
    /// assert_eq!(s.remove(1), 'b');
    /// assert_eq!(s, "abc");
    /// ```
    pub fn remove(&mut self, idx: u32) -> char {
        self.as_string(|s| s.remove(idx.into_usize()))
    }

    /// Insert a `char` at a given byte index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is not a UTF-8 code point boundary, or if the resulting string would require more than [`u32::MAX`] bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("ac").unwrap();
    /// s.insert(1, 'b');
    /// assert_eq!(s, "abc");
    /// ```
    pub fn insert(&mut self, idx: u32, ch: char) {
        self.as_string(|s| s.insert(idx.into_usize(), ch));
    }

    /// Insert a string slice at the given byte index.
    ///
    /// # Panics
    ///
    /// Panics if `idx` is not a UTF-8 code point boundary, or if the resulting string would require more than [`u32::MAX`] bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("ad").unwrap();
    /// s.insert_str(1, "bc");
    /// assert_eq!(s, "abcd");
    /// ```
    pub fn insert_str<S>(&mut self, idx: u32, s: S)
    where
        S: AsRef<str>,
    {
        self.as_string(|st| st.insert_str(idx.into_usize(), s.as_ref()));
    }

    /// Reserve space for additional bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("abc").unwrap();
    /// s.reserve(10);
    /// println!("{}", s.capacity());
    /// assert!(s.capacity() >= 13);
    /// ```
    pub fn reserve(&mut self, additional: u32) {
        self.0.reserve(additional)
    }

    /// Reserve space for an exact number of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::with_capacity(5);
    /// s.reserve_exact(10);
    /// assert!(s.capacity() >= 10);
    /// ```
    pub fn reserve_exact(&mut self, additional: u32) {
        self.0.reserve_exact(additional)
    }

    /// Shrink the capacity of this `String32` to match its length.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// let mut s = String32::with_capacity(10);
    /// s.shrink_to_fit();
    /// assert_eq!(0, s.capacity());
    /// ```
    pub fn shrink_to_fit(&mut self) {
        self.as_string(String::shrink_to_fit);
    }

    /// Shortens this `String32` to the specified length.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("abcde").unwrap();
    /// s.truncate(3);
    /// assert_eq!(s, "abc");
    /// ```
    pub fn truncate(&mut self, new_len: u32) {
        self.as_string(|s| s.truncate(new_len.into_usize()));
    }

    /// Truncates the `String32` into an empty string.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s = String32::try_from("abc").unwrap();
    /// s.clear();
    /// assert!(s.is_empty());
    /// ```
    pub fn clear(&mut self) {
        self.0.clear()
    }

    /// Converts a `String32` into a vector of bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let s = String32::try_from("123").unwrap();
    /// let v = s.into_bytes();
    /// assert_eq!(v, b"123");
    /// ```
    #[must_use]
    pub fn into_bytes(self) -> Vec<u8> {
        self.0.into_vec()
    }

    /// Converts a `String32` into a [`Box<str>`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let s = String32::try_from("123").unwrap();
    /// let b = s.into_boxed_str();
    /// ```
    #[must_use]
    pub fn into_boxed_str(self) -> Box<str> {
        String::from(self).into_boxed_str()
    }

    /// Splits the `String32` into two at the given byte index.
    ///
    /// # Panics
    ///
    /// Panics if the index is out-of-bounds or is not a UTF-8 code point boundary.
    ///
    /// # Examples
    ///
    /// ```
    /// # use string32::String32;
    /// # use std::convert::TryFrom;
    /// let mut s1 = String32::try_from("123abc").unwrap();
    /// let s2 = s1.split_off(3);
    /// assert_eq!("123", s1);
    /// assert_eq!("abc", s2);
    /// ```
    #[must_use = "if you plan to discard the second half, consider using `String32::truncate` instead"]
    pub fn split_off(&mut self, at: u32) -> Self {
        self.as_string(|s| s.split_off(at.into_usize()).try_into().unwrap())
    }

    /// Create a new `String32` from a raw pointer and corresponding length/capacity.
    ///
    /// # Safety
    ///
    /// See [`String::from_raw_parts`].
    pub unsafe fn from_raw_parts(buf: *mut u8, len: u32, cap: u32) -> Self {
        Self(Vec32::from_vec(Vec::from_raw_parts(
            buf,
            len.into_usize(),
            cap.into_usize(),
        )))
    }

    /// Decodes a UTF-8 encoded vector of bytes into a `String32`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the slice is not valid UTF-8.
    ///
    /// # Panics
    ///
    /// Panics if the provided [`Vec<u8>`] holds more than [`u32::MAX`] bytes.
    pub fn from_utf8(v: Vec<u8>) -> Result<Self, string::FromUtf8Error> {
        String::from_utf8(v).map(|s| s.try_into().unwrap())
    }

    /// Decodes a UTF-16 encoded slice into a `String32`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the slice is not valid UTF-16.
    ///
    /// # Panics
    ///
    /// Panics if the resulting UTF-8 representation would require more than [`u32::MAX`] bytes.
    pub fn from_utf16(v: &[u16]) -> Result<Self, string::FromUtf16Error> {
        String::from_utf16(v).map(|s| s.try_into().unwrap())
    }

    /// Lossily decodes a UTF-16 encoded slice into a `String32`.
    ///
    /// # Panics
    ///
    /// Panics if the resulting UTF-8 representation would require more than [`u32::MAX`] bytes.
    #[must_use]
    pub fn from_utf16_lossy(v: &[u16]) -> Self {
        String::from_utf16_lossy(v).try_into().unwrap()
    }
}

impl ops::Add<&str> for String32 {
    type Output = Self;

    #[must_use]
    fn add(mut self, rhs: &str) -> Self {
        self.push_str(rhs);
        self
    }
}

impl ops::Add<&Str32> for String32 {
    type Output = Self;

    #[must_use]
    fn add(mut self, rhs: &Str32) -> Self {
        self.push_str(rhs);
        self
    }
}

impl ops::AddAssign<&str> for String32 {
    fn add_assign(&mut self, rhs: &str) {
        self.push_str(rhs);
    }
}

impl ops::AddAssign<&Str32> for String32 {
    fn add_assign(&mut self, rhs: &Str32) {
        self.push_str(rhs);
    }
}

impl AsMut<Str32> for String32 {
    fn as_mut(&mut self) -> &mut Str32 {
        self
    }
}

impl AsRef<Str32> for String32 {
    fn as_ref(&self) -> &Str32 {
        &*self
    }
}

impl AsRef<[u8]> for String32 {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl AsRef<str> for String32 {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<Str32> for String32 {
    fn borrow(&self) -> &Str32 {
        &*self
    }
}

impl BorrowMut<Str32> for String32 {
    fn borrow_mut(&mut self) -> &mut Str32 {
        &mut *self
    }
}

impl ops::Deref for String32 {
    type Target = Str32;

    fn deref(&self) -> &Str32 {
        let ptr = self.0.as_ref() as *const [u8] as *const str as *const Str32;
        unsafe {
            // safety: relies on `&Str32` and `&str` having the same layout
            &*ptr
        }
    }
}

impl ops::DerefMut for String32 {
    fn deref_mut(&mut self) -> &mut Str32 {
        let ptr = self.0.as_mut() as *mut [u8] as *mut str as *mut Str32;
        unsafe {
            // safety: relies on `&mut Str32` and `&mut str` having the same layout
            &mut *ptr
        }
    }
}

impl fmt::Display for String32 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Str32 as fmt::Display>::fmt(self, f)
    }
}

impl From<&Str32> for String32 {
    fn from(s: &Str32) -> Self {
        s.to_owned()
    }
}

#[allow(clippy::fallible_impl_from)]
impl From<String32> for String {
    fn from(s: String32) -> Self {
        if cfg!(debug_assertions) {
            Self::from_utf8(s.0.into_vec()).unwrap()
        } else {
            unsafe {
                // safety: we never store a non-utf8 Vec32<u8> in a String32
                Self::from_utf8_unchecked(s.0.into_vec())
            }
        }
    }
}

impl From<String32> for Vec<u8> {
    fn from(s: String32) -> Self {
        s.0.into_vec()
    }
}

impl FromIterator<char> for String32 {
    fn from_iter<I: IntoIterator<Item = char>>(iter: I) -> Self {
        String::from_iter(iter).try_into().unwrap()
    }
}

impl<'a> FromIterator<&'a char> for String32 {
    fn from_iter<I: IntoIterator<Item = &'a char>>(iter: I) -> Self {
        String::from_iter(iter).try_into().unwrap()
    }
}

impl<'a> FromIterator<&'a str> for String32 {
    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
        String::from_iter(iter).try_into().unwrap()
    }
}

impl<'a> FromIterator<&'a Str32> for String32 {
    fn from_iter<I: IntoIterator<Item = &'a Str32>>(iter: I) -> Self {
        String::from_iter(iter.into_iter().map(Str32::as_str))
            .try_into()
            .unwrap()
    }
}

impl FromIterator<Box<str>> for String32 {
    fn from_iter<I: IntoIterator<Item = Box<str>>>(iter: I) -> Self {
        String::from_iter(iter).try_into().unwrap()
    }
}

impl FromIterator<Box<Str32>> for String32 {
    fn from_iter<I: IntoIterator<Item = Box<Str32>>>(iter: I) -> Self {
        String::from_iter(iter.into_iter().map(Str32::into_boxed_str))
            .try_into()
            .unwrap()
    }
}

impl FromIterator<String> for String32 {
    fn from_iter<I: IntoIterator<Item = String>>(iter: I) -> Self {
        String::from_iter(iter).try_into().unwrap()
    }
}

impl FromIterator<Self> for String32 {
    fn from_iter<I: IntoIterator<Item = Self>>(iter: I) -> Self {
        String::from_iter(iter.into_iter().map(String::from))
            .try_into()
            .unwrap()
    }
}

impl Hash for String32 {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state);
    }
}

impl Ord for String32 {
    fn cmp(&self, rhs: &Self) -> cmp::Ordering {
        <Str32 as Ord>::cmp(self, rhs)
    }
}

impl PartialEq for String32 {
    fn eq(&self, rhs: &Self) -> bool {
        <Str32 as PartialEq>::eq(self, rhs)
    }
}

impl PartialOrd for String32 {
    fn partial_cmp(&self, rhs: &Self) -> Option<cmp::Ordering> {
        <Str32 as PartialOrd>::partial_cmp(self, rhs)
    }
}

macro_rules! impl_cmp {
    ($lhs:ty, $rhs: ty) => {
        impl<'a, 'b> PartialEq<$rhs> for $lhs {
            fn eq(&self, rhs: &$rhs) -> bool {
                <[u8] as PartialEq>::eq(self.as_bytes(), rhs.as_bytes())
            }
        }

        impl<'a, 'b> PartialEq<$lhs> for $rhs {
            fn eq(&self, rhs: &$lhs) -> bool {
                <[u8] as PartialEq>::eq(self.as_bytes(), rhs.as_bytes())
            }
        }

        impl<'a, 'b> PartialOrd<$rhs> for $lhs {
            fn partial_cmp(&self, rhs: &$rhs) -> Option<cmp::Ordering> {
                <[u8] as PartialOrd>::partial_cmp(self.as_bytes(), rhs.as_bytes())
            }
        }

        impl<'a, 'b> PartialOrd<$lhs> for $rhs {
            fn partial_cmp(&self, rhs: &$lhs) -> Option<cmp::Ordering> {
                <[u8] as PartialOrd>::partial_cmp(self.as_bytes(), rhs.as_bytes())
            }
        }
    };
}

impl_cmp!(String32, Str32);
impl_cmp!(String32, &'a Str32);
impl_cmp!(String32, String);
impl_cmp!(String32, str);
impl_cmp!(String32, &'a str);
impl_cmp!(String32, Cow<'a, Str32>);
impl_cmp!(String32, Cow<'a, str>);
impl_cmp!(String32, Box<str>);
impl_cmp!(String32, Box<Str32>);
impl_cmp!(Str32, &'a Str32);
impl_cmp!(Str32, String);
impl_cmp!(Str32, str);
impl_cmp!(Str32, &'a str);
impl_cmp!(Str32, Cow<'a, Str32>);
impl_cmp!(Str32, Cow<'a, str>);
impl_cmp!(Str32, Box<str>);
impl_cmp!(Str32, Box<Str32>);
impl_cmp!(&'a Str32, String);
impl_cmp!(&'a Str32, str);
impl_cmp!(&'a Str32, Cow<'b, Str32>);
impl_cmp!(&'a Str32, Cow<'b, str>);
impl_cmp!(&'a Str32, Box<str>);
impl_cmp!(&'a Str32, Box<Str32>);

impl TryFrom<String> for String32 {
    type Error = TryFromStringError<String>;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match u32::try_from(s.len()) {
            Ok(_) => Ok(Self(Vec32::from_vec(s.into_bytes()))),
            Err(_) => Err(TryFromStringError(s)),
        }
    }
}

impl TryFrom<Box<str>> for String32 {
    type Error = TryFromStringError<Box<str>>;

    fn try_from(s: Box<str>) -> Result<Self, Self::Error> {
        match u32::try_from(s.len()) {
            Ok(_) => Ok(Self(Vec32::from_vec(String::from(s).into_bytes()))),
            Err(_) => Err(TryFromStringError(s)),
        }
    }
}

impl TryFrom<&str> for String32 {
    type Error = TryFromStrError;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match u32::try_from(s.len()) {
            Ok(_) => Ok(Self(Vec32::from_vec(s.to_owned().into_bytes()))),
            Err(_) => Err(TryFromStrError(())),
        }
    }
}