c8str 0.2.1

String types that are both utf-8 and null terminated
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
// SPDX-FileCopyrightText: 2024-2025 Maia S Ravn
// SPDX-License-Identifier: Zlib OR MIT OR Apache-2.0

use crate::{C8Str, C8StrError, NonZeroChar};
use alloc::vec; // macro
use alloc::{borrow::Cow, boxed::Box, ffi::CString, string::String, vec::Vec};
use core::hint::unreachable_unchecked;
use core::{
    borrow::Borrow,
    ffi::CStr,
    fmt::{self, Display},
    mem::size_of,
    ops::Deref,
};

mod sealed_string_type {
    pub trait Sealed {}
}

/// Trait for standard utf-8 string types. Implemented for `&str`, `String`, `Box<str>` and `Cow<'_, str>`
pub trait StringType: sealed_string_type::Sealed + Into<String> {
    /// Get the string as bytes
    fn as_bytes(&self) -> &[u8];

    /// Check if the string is allocated
    fn is_allocated(&self) -> bool;

    /// Check if the string is empty
    fn is_empty(&self) -> bool;

    /// Get the length of the string
    fn len(&self) -> usize;
}

impl sealed_string_type::Sealed for String {}
impl sealed_string_type::Sealed for &str {}
impl sealed_string_type::Sealed for Box<str> {}
impl sealed_string_type::Sealed for Cow<'_, str> {}

impl StringType for String {
    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        self.as_bytes()
    }

    #[inline(always)]
    fn is_allocated(&self) -> bool {
        true
    }

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

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

impl StringType for &str {
    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        (*self).as_bytes()
    }

    #[inline(always)]
    fn is_allocated(&self) -> bool {
        false
    }

    #[inline(always)]
    fn is_empty(&self) -> bool {
        (*self).is_empty()
    }

    #[inline(always)]
    fn len(&self) -> usize {
        (*self).len()
    }
}

impl StringType for Box<str> {
    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        (**self).as_bytes()
    }

    #[inline(always)]
    fn is_allocated(&self) -> bool {
        true
    }

    #[inline(always)]
    fn is_empty(&self) -> bool {
        (**self).is_empty()
    }

    #[inline(always)]
    fn len(&self) -> usize {
        (**self).len()
    }
}

impl StringType for Cow<'_, str> {
    #[inline(always)]
    fn as_bytes(&self) -> &[u8] {
        (**self).as_bytes()
    }

    #[inline(always)]
    fn is_allocated(&self) -> bool {
        matches!(self, Self::Owned(_))
    }

    #[inline(always)]
    fn is_empty(&self) -> bool {
        (**self).is_empty()
    }

    #[inline(always)]
    fn len(&self) -> usize {
        (**self).len()
    }
}

const EMPTY_C8STR: &C8Str = c8!("");

/// `C8String` is a string type combining the properties of `String` and `CString`.
/// It's the owned version of [`C8Str`].
///
/// It guarantees that:
/// - The string is valid utf-8
/// - The string ends with a null terminator
/// - The string doesn't contain any null bytes before the end
///
/// `C8String` dereferences to [`C8Str`]
#[repr(transparent)]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct C8String(Option<String>);

const _: () = assert!(size_of::<Option<C8String>>() == size_of::<String>());

impl C8String {
    #[cfg(test)]
    pub(crate) fn inner_capacity(&self) -> usize {
        match &self.0 {
            Some(s) => s.capacity(),
            None => 0,
        }
    }

    /// Create a new, empty `C8String` without allocating
    #[inline(always)]
    pub const fn new() -> C8String {
        Self(None)
    }

    /// Try to turn a vector of bytes, not including a null terminator, into a a `C8String`.
    /// This may fail if bytes of the vector aren't valid utf-8, or if it contains zero
    /// bytes.
    ///
    /// See also [`C8String::from_vec_with_nul`]
    pub fn from_vec(vec: Vec<u8>) -> Result<C8String, C8StrError> {
        if vec.is_empty() {
            return Ok(Self(None));
        }
        match CString::new(vec) {
            Ok(str) => match String::from_utf8(str.into_bytes_with_nul()) {
                Ok(str) => Ok(Self(Some(str))),
                Err(e) => Err(C8StrError::not_utf8(e.utf8_error().valid_up_to())),
            },
            Err(e) => Err(C8StrError::inner_zero(e.nul_position())),
        }
    }

    /// Try to turn a vector of bytes that included a null terminator into a a `C8String`.
    /// This may fail if bytes of the vector aren't valid utf-8, or if it contains zero
    /// bytes except for the null terminator, or if the final byte of the vector isn't zero.
    ///
    /// See also [`C8String::from_vec`]
    pub fn from_vec_with_nul(vec: Vec<u8>) -> Result<C8String, C8StrError> {
        if vec.last() != Some(&0) {
            return Err(C8StrError::missing_terminator());
        }
        match CString::from_vec_with_nul(vec) {
            Ok(str) => match String::from_utf8(str.into_bytes_with_nul()) {
                Ok(str) => Ok(Self(Some(str))),
                Err(e) => Err(C8StrError::not_utf8(e.utf8_error().valid_up_to())),
            },
            Err(_) => Err(C8StrError::inner_zero_unknown()),
        }
    }

    /// Try to turn a `String`, not including a null terminator, into a `C8String`.
    /// This may fail if the string contains zero bytes.
    ///
    /// See also [`C8String::from_string_with_nul`]
    pub fn from_string(str: impl StringType) -> Result<C8String, C8StrError> {
        if str.is_empty() {
            Ok(Self(None))
        } else {
            let mut str = str.into();
            str.push('\0');
            Self::from_string_with_nul(str)
        }
    }

    /// Try to turn a `String` that does include a null terminator into a `C8String`.
    /// This may fail if the string contains zero bytes except for the null terminator,
    /// or if it doesn't have a null terminator.
    ///
    /// See also [`C8String::from_string`]
    pub fn from_string_with_nul(str: impl StringType) -> Result<C8String, C8StrError> {
        if !str.is_allocated() && str.len() == 1 && str.as_bytes()[0] == 0 {
            return Ok(Self(None));
        }
        let str = str.into();
        C8Str::from_str_with_nul(&str)?;
        Ok(Self(Some(str)))
    }

    /// Try to turn a `CStrimg` into a `C8String`
    pub fn from_c_string(str: CString) -> Result<C8String, C8StrError> {
        let bytes = str.into_bytes_with_nul();
        Ok(Self(Some(String::from_utf8(bytes).map_err(|s| {
            C8StrError::not_utf8(s.utf8_error().valid_up_to())
        })?)))
    }

    /// Get this string as a [`C8Str`]
    pub fn as_c8_str(&self) -> &C8Str {
        match &self.0 {
            Some(s) => unsafe {
                // Safety: self.0 is valid utf-8 without inner zero bytes and a null terminator
                C8Str::from_str_with_nul_unchecked(s.as_str())
            },
            None => EMPTY_C8STR,
        }
    }

    /// Turn this string into `Box<C8Str>`
    pub fn into_boxed_c8_str(self) -> Box<C8Str> {
        let boxed = match self.0 {
            Some(s) => s,
            None => String::from("\0"),
        }
        .into_boxed_str();
        unsafe {
            // Safety: `C8Str` is a transparent wrapper around `str`
            Box::from_raw(Box::into_raw(boxed) as *mut C8Str)
        }
    }

    /// Turn this string into a vector of bytes, **not** including the null terminator
    ///
    /// See also [`C8String::into_bytes_with_nul`]
    pub fn into_bytes(self) -> Vec<u8> {
        match self.0 {
            Some(mut s) => {
                s.pop(); // pop null terminator
                s.into_bytes()
            }
            None => Vec::new(),
        }
    }

    /// Turn this string into a vector of bytes, including the null terminator
    ///
    /// See also [`C8String::into_bytes`]
    pub fn into_bytes_with_nul(self) -> Vec<u8> {
        match self.0 {
            Some(s) => s.into_bytes(),
            None => vec![0],
        }
    }

    /// Turn this string into a `String`, **not** including the null terminator
    ///
    /// See also [`C8String::into_string_with_nul`]
    pub fn into_string(self) -> String {
        match self.0 {
            Some(mut s) => {
                s.pop();
                s
            }
            None => String::new(),
        }
    }

    /// Turn this string into a `String`, including the null terminator
    ///
    /// See also [`C8String::into_string`]
    pub fn into_string_with_nul(self) -> String {
        match self.0 {
            Some(s) => s,
            None => String::from("\0"),
        }
    }

    /// Turn this string into a `CString`
    pub fn into_c_string(self) -> CString {
        unsafe { CString::from_vec_with_nul_unchecked(self.into_bytes_with_nul()) }
    }

    /// Reserve capacity for at least `additional` more bytes
    pub fn reserve(&mut self, additional: usize) {
        match &mut self.0 {
            Some(s) => s.reserve(additional),
            None => {
                // other code depends on this always converting into Some
                let mut s = String::with_capacity(additional + 1);
                s.push('\0');
                self.0 = Some(s);
            }
        }
    }

    /// Reserve capacity for at least `additional` more bytes while trying not to over-allocate
    pub fn reserve_exact(&mut self, additional: usize) {
        match &mut self.0 {
            Some(s) => s.reserve_exact(additional),
            None => {
                // other code depends on this always converting into Some
                let mut s = String::with_capacity(additional + 1);
                s.push('\0');
                self.0 = Some(s);
            }
        }
    }

    /// Push a char to the end of this string, before the null terminator
    pub fn push(&mut self, ch: NonZeroChar) {
        self.reserve(1); // for unwind safety
        let Some(s) = &mut self.0 else {
            unsafe {
                // safety: reserve always converts into Some
                unreachable_unchecked()
            }
        };
        s.pop();
        s.push(ch.get());
        s.push('\0');
    }

    /// Append another `C8Str` to the end of this string, before the null terminator
    pub fn push_c8_str(&mut self, c8_str: &C8Str) {
        self.reserve(c8_str.len()); // for unwind safety
        let Some(s) = &mut self.0 else {
            unsafe {
                // safety: reserve always converts into Some
                unreachable_unchecked()
            }
        };
        s.pop();
        s.push_str(c8_str.as_str_with_nul());
    }

    /// Append a `CStr` to the end of this string, before the null terminator
    pub fn push_c_str(&mut self, c_str: &CStr) -> Result<(), C8StrError> {
        let str = match c_str.to_str() {
            Ok(str) => str,
            Err(e) => return Err(C8StrError::not_utf8(e.valid_up_to())),
        };
        self.reserve(str.len()); // for unwind safety
        let Some(s) = &mut self.0 else {
            unsafe {
                // safety: reserve always converts into Some
                unreachable_unchecked()
            }
        };
        s.pop();
        s.push_str(str);
        s.push('\0');
        Ok(())
    }

    /// Append another `str` to the end of this string, before the null terminator
    pub fn push_str(&mut self, str: &str) -> Result<(), C8StrError> {
        if let Some(i) = str.as_bytes().iter().position(|&b| b == 0) {
            return Err(C8StrError::inner_zero(i));
        }
        self.reserve(str.len()); // for unwind safety
        let Some(s) = &mut self.0 else {
            unsafe {
                // safety: reserve always converts into Some
                unreachable_unchecked()
            }
        };
        s.pop();
        s.push_str(str);
        s.push('\0');
        Ok(())
    }

    /// Pop a char from the end of this string, before the null terminator
    pub fn pop(&mut self) -> Option<NonZeroChar> {
        match &mut self.0 {
            Some(s) => {
                s.pop(); // null terminator
                let popped = s.pop().map(|c| unsafe {
                    // Safety: the string only contains nonzero chars, except for the null terminator
                    // (which was popped above)
                    NonZeroChar::new_unchecked(c)
                });
                s.push('\0');
                popped
            }
            None => None,
        }
    }

    /// Clear the string, leaving only the null terminator
    pub fn clear(&mut self) {
        if let Some(s) = &mut self.0 {
            s.clear();
            s.push('\0');
        }
    }
}

impl AsRef<C8Str> for C8String {
    #[inline(always)]
    fn as_ref(&self) -> &C8Str {
        self.as_c8_str()
    }
}

impl AsRef<CStr> for C8String {
    #[inline(always)]
    fn as_ref(&self) -> &CStr {
        self.as_c_str()
    }
}

impl AsRef<str> for C8String {
    #[inline(always)]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<C8Str> for C8String {
    #[inline(always)]
    fn borrow(&self) -> &C8Str {
        self.as_c8_str()
    }
}

impl Default for C8String {
    #[inline(always)]
    fn default() -> Self {
        Self(None)
    }
}

impl Deref for C8String {
    type Target = C8Str;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.as_c8_str()
    }
}

impl Display for C8String {
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.as_str().fmt(f)
    }
}

impl From<&C8Str> for C8String {
    fn from(value: &C8Str) -> Self {
        if value.is_empty() {
            Self(None)
        } else {
            Self(Some(String::from(value.as_str_with_nul())))
        }
    }
}

impl From<Box<C8Str>> for C8String {
    fn from(value: Box<C8Str>) -> Self {
        if value.is_empty() {
            Self(None)
        } else {
            Self(Some(String::from(unsafe {
                // Safety: `C8Str` is a transparent wrapper around `str`
                Box::from_raw(Box::into_raw(value) as *mut str)
            })))
        }
    }
}

impl TryFrom<String> for C8String {
    type Error = C8StrError;

    #[inline(always)]
    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::from_string(value)
    }
}

impl From<C8String> for String {
    #[inline(always)]
    fn from(value: C8String) -> Self {
        value.into_string()
    }
}

impl TryFrom<CString> for C8String {
    type Error = C8StrError;

    #[inline(always)]
    fn try_from(value: CString) -> Result<Self, Self::Error> {
        Self::from_c_string(value)
    }
}

impl From<C8String> for CString {
    #[inline(always)]
    fn from(value: C8String) -> Self {
        value.into_c_string()
    }
}