cesu8-str 1.2.1

CESU-8 and Java CESU-8 string validation and manipulation.
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
use crate::internal::InternalStr;
use crate::{validate_cesu8_internal, EncodingError};

use super::iter::{Cesu8CharIndices, Cesu8Chars};

use core::ops::RangeBounds;

#[cfg(feature = "alloc")]
use super::Cesu8String;

#[cfg(feature = "alloc")]
use alloc::borrow::ToOwned;
#[cfg(feature = "alloc")]
use alloc::boxed::Box;

/// A CESU-8 encoded string slice.
#[repr(transparent)]
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Cesu8Str {
    pub(crate) internal: InternalStr,
}

impl Cesu8Str {
    /// Converts a slice of bytes to a `Cesu8Str`.
    ///
    /// A CESU-8 string slice ([`Cesu8Str`]) is made of bytes ([`u8`]), and a
    /// byte slice ([`[u8]`][byteslice]) is made of bytes, so this function
    /// converts betwen the two. Not all byte slices are valid string slices,
    /// however `Cesu8Str` requires that it is valid CESU-8. [`from_cesu8`]
    /// checks to ensure that the bytes are valid CESU-8, and then does the
    /// conversion.
    ///
    /// [byteslice]: slice
    /// [`from_cesu8`]: Self::from_cesu8
    ///
    /// If you are sure that the byte slice is valid CESU-8, and you don't want
    /// to incur the overhead of the validity check, there is an unsafe
    /// version of this function [`from_cesu8_unchecked`], which has the
    /// same behavior but skips the check.
    ///
    /// [`from_cesu8_unchecked`]: Self::from_cesu8_unchecked
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if the slice is not CESU-8 with
    /// a description as to why the provided slice is
    /// not CESU-8.
    #[inline]
    pub const fn from_cesu8(v: &[u8]) -> Result<&Cesu8Str, EncodingError> {
        match validate_cesu8_internal::<false>(v) {
            Ok(()) => Ok(unsafe { Cesu8Str::from_cesu8_unchecked(v) }),
            Err(e) => Err(e),
        }
    }

    /// Converts a mutable slice of bytes to a mutable `Cesu8Str`.
    ///
    /// A CESU-8 string slice ([`Cesu8Str`]) is made of bytes ([`u8`]), and a
    /// byte slice ([`[u8]`][byteslice]) is made of bytes, so this function
    /// converts betwen the two. Not all byte slices are valid string slices,
    /// however `Cesu8Str` requires that it is valid CESU-8. [`from_cesu8`]
    /// checks to ensure that the bytes are valid CESU-8, and then does the
    /// conversion.
    ///
    /// [byteslice]: slice
    /// [`from_cesu8`]: Self::from_cesu8
    ///
    /// If you are sure that the byte slice is valid CESU-8, and you don't want
    /// to incur the overhead of the validity check, there is an unsafe
    /// version of this function [`from_cesu8_unchecked_mut`], which has the
    /// same behavior but skips the check.
    ///
    /// [`from_cesu8_unchecked_mut`]: Self::from_cesu8_unchecked_mut
    ///
    /// # Errors
    ///
    /// Returns [`Err`] if the slice is not CESU-8 with
    /// a description as to why the provided slice is
    /// not CESU-8.
    #[inline]
    pub fn from_cesu8_mut(v: &mut [u8]) -> Result<&mut Cesu8Str, EncodingError> {
        match validate_cesu8_internal::<false>(v) {
            Ok(()) => Ok(unsafe { Cesu8Str::from_cesu8_unchecked_mut(v) }),
            Err(e) => Err(e),
        }
    }

    /// Converts a slice of bytes to a `Cesu8Str` without checking that the
    /// string contains valid CESU-8.
    ///
    /// See the safe version, [`from_cesu8`], for more details.
    ///
    /// [`from_cesu8`]: Self::from_cesu8
    ///
    /// # Safety
    ///
    /// The bytes passed in must be valid CESU-8.
    #[inline]
    #[must_use]
    pub const unsafe fn from_cesu8_unchecked(v: &[u8]) -> &Cesu8Str {
        unsafe { &*(v as *const [u8] as *const Cesu8Str) }
    }

    /// Converts a mutable slice of bytes to a mutable `Cesu8Str` without
    /// checking that the string contains valid CESU-8.
    ///
    /// See the safe version, [`from_cesu8_mut`], for more details.
    ///
    /// [`from_cesu8_mut`]: Self::from_cesu8_mut
    ///
    /// # Safety
    ///
    /// The bytes passed in must be valid CESU-8.
    #[inline]
    #[must_use]
    pub unsafe fn from_cesu8_unchecked_mut(v: &mut [u8]) -> &mut Cesu8Str {
        unsafe { &mut *(v as *mut [u8] as *mut Cesu8Str) }
    }

    /// Converts a boxed slice of bytes to a boxed string slice without checking
    /// that the string contains valid CESU-8.
    ///
    /// # Safety
    ///
    /// The bytes passed in must be valid CESU-8.
    #[cfg(feature = "alloc")]
    #[inline]
    #[must_use]
    pub unsafe fn from_boxed_cesu8_unchecked(v: Box<[u8]>) -> Box<Cesu8Str> {
        unsafe { Box::from_raw(Box::into_raw(v) as *mut Cesu8Str) }
    }

    /// Converts an `InternalStr` to a `Cesu8Str` without checking that the
    /// string contains valid CESU-8.
    ///
    /// # Safety
    ///
    /// The string passed in must be valid CESU-8.
    #[inline]
    #[must_use]
    pub(crate) const unsafe fn from_internal_unchecked(v: &InternalStr) -> &Cesu8Str {
        unsafe { &*(v as *const InternalStr as *const Cesu8Str) }
    }

    /// Converts a mutable `InternalStr` to a mutable `Cesu8Str` without
    /// checking that the string contains valid CESU-8.
    ///
    /// # Safety
    ///
    /// The string passed in must be valid CESU-8.
    #[inline]
    #[must_use]
    pub(crate) unsafe fn from_internal_unchecked_mut(v: &mut InternalStr) -> &mut Cesu8Str {
        unsafe { &mut *(v as *mut InternalStr as *mut Cesu8Str) }
    }

    /// Converts an `InternalStr` into a boxed string slice without checking
    /// that the string contains valid CESU-8.
    ///
    /// # Safety
    ///
    /// The string passed in must be valid CESU-8.
    #[cfg(feature = "alloc")]
    #[inline]
    #[must_use]
    pub(crate) unsafe fn from_boxed_internal_unchecked(v: Box<InternalStr>) -> Box<Cesu8Str> {
        unsafe { Box::from_raw(Box::into_raw(v) as *mut Cesu8Str) }
    }

    /// Returns the length of `self`.
    ///
    /// This length is in bytes, not [`char`]s or graphemes. In other words, it
    /// might not be what a human considers the length of the string.
    #[inline]
    #[must_use]
    pub const fn len(&self) -> usize {
        self.internal.len()
    }

    /// Returns `true` if `self` has a length of zero bytes.
    #[inline]
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.internal.is_empty()
    }

    /// Checks that the `index`-th byte is the first byte in a CESU-8 code point
    /// sequence or the end of the string.
    ///
    /// The start and end of the string (when `index == self.len()`) are
    /// considered to be boundaries.
    ///
    /// Returns `false` if `index is greater than self.len()`.
    #[inline]
    #[must_use]
    pub fn is_char_boundary(&self, index: usize) -> bool {
        self.internal.is_char_boundary(index)
    }

    /// Converts a string slice to a byte slice.
    #[inline]
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8] {
        self.internal.as_bytes()
    }

    /// Converts a mutable string slice to a mutable byte slice.
    ///
    /// # Safety
    ///
    /// The caller must ensure that the content of the slice is valid CESU-8
    /// before the borrow ends and the underlying `Cesu8Str` is used.
    ///
    /// Use of a `Cesu8Str` whose contents are not valid CESU-8 is undefined
    /// behavior.
    #[inline]
    #[must_use]
    pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8] {
        self.internal.as_bytes_mut()
    }

    /// Converts a string slice to a raw pointer.
    ///
    /// As string slices are a slice of bytes, the raw pointer points to a
    /// [`u8`]. This pointer will be pointing to the first bytes of the string
    /// slice.
    ///
    /// The caller must ensure that the returned pointer is never written to. If
    /// you need to mutate the contents of the string slice, use [`as_mut_ptr`].
    ///
    /// [`as_mut_ptr`]: Self::as_mut_ptr
    #[inline]
    #[must_use]
    pub const fn as_ptr(&self) -> *const u8 {
        self.internal.as_ptr()
    }

    /// Converts a mutable string slice to a raw pointer.
    ///
    /// As string slices are a slice of bytes, the raw pointer points to a
    /// [`u8`]. This pointer will be pointing to the first byte of the string
    /// slice.
    ///
    /// It is your responsibility to make sure that the string slice only gets
    /// modified in a way that it remains valid CESU-8.
    #[inline]
    #[must_use]
    pub fn as_mut_ptr(&mut self) -> *mut u8 {
        self.internal.as_mut_ptr()
    }

    /// Returns a subslice of `Cesu8Str`.
    ///
    /// This is the non-panicking alternative to indexing the `str`. Returns
    /// [`None`] whenever equivalent indexing operations would panic.
    #[inline]
    #[must_use]
    pub fn get<I: RangeBounds<usize>>(&self, index: I) -> Option<&Cesu8Str> {
        self.internal
            .get(index)
            .map(|internal| unsafe { Cesu8Str::from_internal_unchecked(internal) })
    }

    /// Returns a mutable subslice of `Cesu8Str`.
    ///
    /// This is the non-panicking alternative to indexing the `Cesu8Str`.
    /// Returns [`None`] whenver equivalent indexing operations would panic.
    #[inline]
    #[must_use]
    pub fn get_mut<I: RangeBounds<usize>>(&mut self, index: I) -> Option<&mut Cesu8Str> {
        self.internal
            .get_mut(index)
            .map(|internal| unsafe { Cesu8Str::from_internal_unchecked_mut(internal) })
    }

    /// Returns an unchecked subslice of `Cesu8Str`.
    ///
    /// This is the unchecked alternative to indexing the `Cesu8Str`.
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible for ensuring that:
    /// * The starting index does not exceed the ending index;
    /// * The indices are within the bounds of the original slice;
    /// * The indices fall on CESU-8 sequence boundaries.
    ///
    /// Failing that, the returned string slice may reference invalid memory or
    /// violate the invariants communicated by the `Cesu8Str` type.
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked<I: RangeBounds<usize>>(&self, index: I) -> &Cesu8Str {
        unsafe { Cesu8Str::from_internal_unchecked(self.internal.get_unchecked(index)) }
    }

    /// Returns a mutable, unchecked subslice of `Cesu8Str`.
    ///
    /// This the unchecked alternative to indexing the `Cesu8Str`.
    ///
    /// # Safety
    ///
    /// Callers of this function are responsible for ensuring that:
    /// * The starting index does not exceed the ending index;
    /// * The indices are within the bounds of the original slice;
    /// * The indices fall on CESU-8 sequence boundaries.
    ///
    /// Failing that, the returned string slice may reference invalid memory or
    /// violate the invariants communicated by the `Cesu8Str` type.
    #[inline]
    #[must_use]
    pub unsafe fn get_unchecked_mut<I: RangeBounds<usize>>(&mut self, index: I) -> &mut Cesu8Str {
        unsafe { Cesu8Str::from_internal_unchecked_mut(self.internal.get_unchecked_mut(index)) }
    }

    /// Divide one string slice into two at an index.
    ///
    /// The argument, `mid`, should be a byte offset from the start of the
    /// string. It must also be on the boundary of a CESU-8 character.
    ///
    /// The two slices returned go from the string of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get mutable string slices instead, see the [`split_at_mut`] method.
    ///
    /// [`split_at_mut`]: Self::split_at_mut
    #[inline]
    #[must_use]
    pub fn split_at(&self, mid: usize) -> (&Cesu8Str, &Cesu8Str) {
        let (left, right) = self.internal.split_at(mid);
        unsafe {
            (
                Cesu8Str::from_internal_unchecked(left),
                Cesu8Str::from_internal_unchecked(right),
            )
        }
    }

    /// Divide one mutable string slice into two at an index.
    ///
    /// The argument, `mid`, should be a byte offset from the start of the
    /// string. It must also be on the boundary of a CESU-8 character.
    ///
    /// The two slices returned go from the string of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get immutable string slices instead, see the [`split_at`] method.
    ///
    /// [`split_at`]: Self::split_at
    #[inline]
    #[must_use]
    pub fn split_at_mut(&mut self, mid: usize) -> (&mut Cesu8Str, &mut Cesu8Str) {
        let (left, right) = self.internal.split_at_mut(mid);
        unsafe {
            (
                Cesu8Str::from_internal_unchecked_mut(left),
                Cesu8Str::from_internal_unchecked_mut(right),
            )
        }
    }

    /// Divide one string slice into two at an index.
    ///
    /// The argument, `mid`, should be a valid byte offset from the start of the
    /// string. It must also be on the boundary of a CESU-8 code point. The
    /// method returns `None` if that's not the case.
    ///
    /// The two slices returned go from the start of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get mutable string slices instead, see the [`split_at_mut_checked`]
    /// method.
    ///
    /// [`split_at_mut_checked`]: Self::split_at_mut_checked
    #[inline]
    #[must_use]
    pub fn split_at_checked(&self, mid: usize) -> Option<(&Cesu8Str, &Cesu8Str)> {
        let (left, right) = self.internal.split_at_checked(mid)?;
        Some(unsafe {
            (
                Cesu8Str::from_internal_unchecked(left),
                Cesu8Str::from_internal_unchecked(right),
            )
        })
    }

    /// Divide one mutable string slice into two at an index.
    ///
    /// The argument, `mid`, should be a valid byte offset from the start of the
    /// string. It must also be on the boundary of a CESU-8 code point. The
    /// method returns `None` if that's not the case.
    ///
    /// The two slices returned go from the start of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get immutable string slices instead, see the [`split_at_checked`]
    /// method.
    ///
    /// [`split_at_checked`]: Self::split_at_checked
    #[inline]
    #[must_use]
    pub fn split_at_mut_checked(&mut self, mid: usize) -> Option<(&mut Cesu8Str, &mut Cesu8Str)> {
        let (left, right) = self.internal.split_at_mut_checked(mid)?;
        Some(unsafe {
            (
                Cesu8Str::from_internal_unchecked_mut(left),
                Cesu8Str::from_internal_unchecked_mut(right),
            )
        })
    }

    /// Divide a string into two at an index.
    ///
    /// The two slices returned go from the start of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get mutable string slices instead, see the [`split_at_mut_unchecked`]
    /// method.
    ///
    /// [`split_at_mut_unchecked`]: Self::split_at_mut_unchecked
    ///
    /// # Safety
    ///
    /// The caller must ensure that `mid` is a valid byte offset from the start
    /// of the string and falls on the boundary of a CESU-8 character.
    #[inline]
    #[must_use]
    pub unsafe fn split_at_unchecked(&self, mid: usize) -> (&Cesu8Str, &Cesu8Str) {
        let (left, right) = self.internal.split_at_unchecked(mid);
        unsafe {
            (
                Cesu8Str::from_internal_unchecked(left),
                Cesu8Str::from_internal_unchecked(right),
            )
        }
    }

    /// Divide a mutable string into two at an index.
    ///
    /// The two slices returned go from the start of the string slice to `mid`,
    /// and from `mid` to the end of the string slice.
    ///
    /// To get immutable string slices instead, see the [`split_at_unchecked`]
    /// method.
    ///
    /// [`split_at_unchecked`]: Self::split_at_unchecked
    ///
    /// # Safety
    ///
    /// The caller must ensure that `mid` is a valid byte offset from the start
    /// of the string and falls on the boundary of a CESU-8 character.
    #[inline]
    #[must_use]
    pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut Cesu8Str, &mut Cesu8Str) {
        let (left, right) = self.internal.split_at_mut_unchecked(mid);
        unsafe {
            (
                Cesu8Str::from_internal_unchecked_mut(left),
                Cesu8Str::from_internal_unchecked_mut(right),
            )
        }
    }

    /// Returns an iterator over the [`char`]s of a string slice.
    ///
    /// As an `Cesu8Str` consists of valid CESU-8, we can iterate through a
    /// string by [`char`]. This method returns such an iterator.
    ///
    /// It's important to remember that [`char`] represents a Unicode Scalar
    /// Value, and might not match your idea of what a 'character' is. Iteration
    /// over grapheme clusters may be what you actually want. This functionality
    /// is not provided by this crate.
    #[inline]
    pub fn chars(&self) -> Cesu8Chars {
        Cesu8Chars {
            iter: self.internal.chars(),
        }
    }

    /// Returns an iterator over the [`char`]s of a string slice, and their
    /// positions.
    ///
    /// As an `Cesu8Str` consists of valid CESU-8, we can iterate through a
    /// string by [`char`]. This method returns an iterator of both these
    /// [`char`]s, as well as their byte positions.
    ///
    /// The iterator yields tuples. The position is first,
    /// the [`char`] is second.
    #[inline]
    pub fn char_indices(&self) -> Cesu8CharIndices {
        Cesu8CharIndices {
            iter: self.internal.char_indices(),
        }
    }

    /// Checks if all characters in this string are within the ASCII range.
    #[inline]
    #[must_use]
    pub const fn is_ascii(&self) -> bool {
        self.internal.is_ascii()
    }
}

#[cfg(feature = "alloc")]
impl ToOwned for Cesu8Str {
    type Owned = Cesu8String;

    #[inline]
    fn to_owned(&self) -> Self::Owned {
        let vec = self.as_bytes().to_owned();
        unsafe { Cesu8String::from_cesu8_unchecked(vec) }
    }
}

impl AsRef<[u8]> for Cesu8Str {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl core::fmt::Debug for Cesu8Str {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Debug::fmt(&self.internal, f)
    }
}

impl core::fmt::Display for Cesu8Str {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        core::fmt::Display::fmt(&self.internal, f)
    }
}