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
//! A dynamically sized, null terminated, C string.
use crate::{
    alloc::NSTDAllocError,
    core::{
        cstr::{
            nstd_core_cstr_as_bytes, nstd_core_cstr_get_null, nstd_core_cstr_mut_new,
            nstd_core_cstr_new, NSTDCStr, NSTDCStrMut,
        },
        slice::NSTDSlice,
    },
    vec::{
        nstd_vec_as_mut_ptr, nstd_vec_as_ptr, nstd_vec_as_slice, nstd_vec_cap, nstd_vec_clear,
        nstd_vec_clone, nstd_vec_extend, nstd_vec_from_slice, nstd_vec_get_mut, nstd_vec_len,
        nstd_vec_new_with_cap, nstd_vec_pop, nstd_vec_push, NSTDVec,
    },
    NSTDChar, NSTDUInt,
};
use core::ptr::addr_of;

/// A dynamically sized, null terminated, C string.
///
/// Managed C strings (`NSTDCString`) will always contain a null byte until freed.
#[repr(C)]
#[derive(Debug, Hash)]
pub struct NSTDCString {
    /// The underlying vector of `NSTDChar`s.
    bytes: NSTDVec,
}

/// Creates a new empty `NSTDCString`.
///
/// # Returns
///
/// `NSTDCString cstring` - The new C string.
///
/// # Panics
///
/// This function will panic if allocating for the null byte fails.
///
/// # Example
///
/// ```
/// use nstd_sys::cstring::nstd_cstring_new;
///
/// let cstring = nstd_cstring_new();
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_new() -> NSTDCString {
    nstd_cstring_new_with_cap(1)
}

/// Creates a new `NSTDCString` initialized with the given capacity.
///
/// # Parameters:
///
/// - `NSTDUInt cap` - The number of bytes to allocate ahead of time.
///
/// # Returns
///
/// `NSTDCString cstring` - The new C string.
///
/// # Panics
///
/// This function will panic if either `cap` is zero or allocating fails.
///
/// # Example
///
/// ```
/// use nstd_sys::cstring::nstd_cstring_new_with_cap;
///
/// let cstring = nstd_cstring_new_with_cap(10);
/// ```
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_new_with_cap(cap: NSTDUInt) -> NSTDCString {
    let mut bytes = nstd_vec_new_with_cap(1, cap);
    let nul: NSTDChar = 0;
    // SAFETY: `nul` is stored on the stack.
    unsafe {
        let errc = nstd_vec_push(&mut bytes, addr_of!(nul).cast());
        assert!(errc == NSTDAllocError::NSTD_ALLOC_ERROR_NONE);
    }
    NSTDCString { bytes }
}

/// Creates an owned version of an unowned C string slice.
///
/// # Parameters:
///
/// - `const NSTDCStr *cstr` - The unowned C string slice.
///
/// # Returns
///
/// `NSTDCString cstring` The new owned version of `cstr`.
///
/// # Panics
///
/// This operation will panic in the following situations:
///
/// - `cstr` contains a null byte.
///
/// - `cstr`'s length is greater than `NSTDInt`'s max value.
///
/// - Allocating fails.
///
/// # Safety
///
/// The caller of this function must ensure that `cstr`'s data is valid for reads.
///
/// # Example
///
/// ```
/// use nstd_sys::{core::cstr::nstd_core_cstr_from_raw, cstring::nstd_cstring_from_cstr};
///
/// unsafe {
///     let cstr = nstd_core_cstr_from_raw("C string\0".as_ptr().cast());
///     let cstring = nstd_cstring_from_cstr(&cstr);
/// }
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_cstring_from_cstr(cstr: &NSTDCStr) -> NSTDCString {
    assert!(nstd_core_cstr_get_null(cstr).is_null());
    let bytes = nstd_core_cstr_as_bytes(cstr);
    let mut bytes = nstd_vec_from_slice(&bytes);
    let null: NSTDChar = 0;
    let null = addr_of!(null).cast();
    assert!(nstd_vec_push(&mut bytes, null) == NSTDAllocError::NSTD_ALLOC_ERROR_NONE);
    NSTDCString { bytes }
}

/// Creates a deep copy of an `NSTDCString`.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string to create a deep copy of.
///
/// # Returns
///
/// `NSTDCString cloned` - A new deep copy of `cstring`.
///
/// # Panics
///
/// This function will panic if allocating for the new C string fails.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_clone(cstring: &NSTDCString) -> NSTDCString {
    NSTDCString {
        bytes: nstd_vec_clone(&cstring.bytes),
    }
}

/// Creates a C string slice containing the contents of `cstring`.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDCStr cstr` - The new C string slice.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_as_cstr(cstring: &NSTDCString) -> NSTDCStr {
    let ptr = nstd_vec_as_ptr(&cstring.bytes).cast();
    let len = nstd_vec_len(&cstring.bytes);
    nstd_core_cstr_new(ptr, len)
}

/// Creates a C string slice containing the contents of `cstring`.
///
/// # Parameters:
///
/// - `NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDCStrMut cstr` - The new C string slice.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_as_cstr_mut(cstring: &mut NSTDCString) -> NSTDCStrMut {
    let ptr = nstd_vec_as_mut_ptr(&mut cstring.bytes).cast();
    let len = nstd_vec_len(&cstring.bytes);
    nstd_core_cstr_mut_new(ptr, len)
}

/// Returns an immutable byte slice of the C string's active data, including the null byte.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDSlice bytes` - The C string's active data.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_as_bytes(cstring: &NSTDCString) -> NSTDSlice {
    nstd_vec_as_slice(&cstring.bytes)
}

/// Returns a raw pointer to a C string's memory.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `const NSTDChar *ptr` - A raw pointer to a C string's memory.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_as_ptr(cstring: &NSTDCString) -> *const NSTDChar {
    nstd_vec_as_ptr(&cstring.bytes).cast()
}

/// Returns ownership of an `NSTDCString`'s raw data, taking ownership of said C string.
///
/// # Parameters:
///
/// - `NSTDCString cstring` - The C string.
///
/// # Returns
///
/// `NSTDVec bytes` - The C string's raw data.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_into_bytes(cstring: NSTDCString) -> NSTDVec {
    cstring.bytes
}

/// Returns the number of `char`s in a C string, excluding the null terminator.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDUInt len` - The length of the C string without it's null byte.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_len(cstring: &NSTDCString) -> NSTDUInt {
    nstd_vec_len(&cstring.bytes) - 1
}

/// Returns the number of `char`s in a C string, including the null terminator.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDUInt len` - The length of the C string including it's null byte.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_len_with_null(cstring: &NSTDCString) -> NSTDUInt {
    nstd_vec_len(&cstring.bytes)
}

/// Returns a C string's capacity.
///
/// This is the max number of *bytes* the C string can contain without reallocating.
///
/// # Parameters:
///
/// - `const NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDUInt cap` - The C string's capacity.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_cap(cstring: &NSTDCString) -> NSTDUInt {
    nstd_vec_cap(&cstring.bytes)
}

/// Appends an `NSTDChar` to the end of an `NSTDCString`.
///
/// This will have no effect if `chr` is a null byte (0).
///
/// # Parameters:
///
/// - `NSTDCString *cstring` - The C string.
///
/// - `NSTDChar chr` - The C char to append to the C string.
///
/// # Panics
///
/// This operation panics if `chr` cannot be appended to the C string.
///
/// # Example
///
/// ```
/// use nstd_sys::{
///     cstring::{nstd_cstring_new, nstd_cstring_push},
///     NSTDChar,
/// };
///
/// let mut cstring = nstd_cstring_new();
/// nstd_cstring_push(&mut cstring, b'!' as NSTDChar);
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_push(cstring: &mut NSTDCString, chr: NSTDChar) {
    // SAFETY: C strings always contain an exclusive null byte at the end.
    unsafe {
        if chr != 0 {
            // Push a new null byte onto the end of the C string.
            let nulpos = nstd_vec_len(&cstring.bytes) - 1;
            let mut nul = nstd_vec_get_mut(&mut cstring.bytes, nulpos).cast::<NSTDChar>();
            let errc = nstd_vec_push(&mut cstring.bytes, nul.cast());
            assert!(errc == NSTDAllocError::NSTD_ALLOC_ERROR_NONE);
            // Write `chr` over the old null byte.
            nul = nstd_vec_get_mut(&mut cstring.bytes, nulpos).cast();
            *nul = chr;
        }
    }
}

/// Appends a C string slice to the end of a C string.
///
/// # Parameters:
///
/// - `NSTDCString *cstring` - The C string.
///
/// - `const NSTDCStr *cstr` - The C string slice to append to the end of `cstring`.
///
/// # Returns
///
/// `NSTDAllocError errc` - The allocation operation error code.
///
/// # Panics
///
/// This operation will panic in the following situations:
///
/// - `cstr` contains a null byte.
///
/// - `cstr`'s length is greater than `NSTDInt`'s max value.
///
/// - Appending the new null byte to the end of the C string fails.
///
/// - The new length in bytes exceeds `NSTDInt`'s max value.
///
/// # Safety
///
/// This operation can cause undefined behavior in the case that `cstr`'s data is invalid.
///
/// # Example
///
/// ```
/// use nstd_sys::{
///     alloc::NSTDAllocError::NSTD_ALLOC_ERROR_NONE,
///     core::cstr::nstd_core_cstr_from_raw,
///     cstring::{nstd_cstring_new, nstd_cstring_push_cstr},
///     NSTDChar,
/// };
///
/// let mut cstring = nstd_cstring_new();
/// unsafe {
///     let cstr = nstd_core_cstr_from_raw("baNaNa\0".as_ptr().cast());
///     assert!(nstd_cstring_push_cstr(&mut cstring, &cstr) == NSTD_ALLOC_ERROR_NONE);
/// }
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub unsafe extern "C" fn nstd_cstring_push_cstr(
    cstring: &mut NSTDCString,
    cstr: &NSTDCStr,
) -> NSTDAllocError {
    // Make sure the C string slice doesn't contain a null byte.
    assert!(nstd_core_cstr_get_null(cstr).is_null());
    // Pop the old null byte.
    let nul = *nstd_vec_pop(&mut cstring.bytes).cast::<NSTDChar>();
    // Append the C string slice.
    let bytes = nstd_core_cstr_as_bytes(cstr);
    let errc = nstd_vec_extend(&mut cstring.bytes, &bytes);
    // Push a new null byte.
    let pusherrc = nstd_vec_push(&mut cstring.bytes, addr_of!(nul).cast());
    assert!(pusherrc == NSTDAllocError::NSTD_ALLOC_ERROR_NONE);
    errc
}

/// Removes the last character from a C string and returns it.
///
/// # Parameters:
///
/// - `NSTDCString *cstring` - The C string.
///
/// # Returns
///
/// `NSTDChar chr` - The removed character, or null if the C string is empty.
///
/// # Panics
///
/// This function will panic if getting a pointer to the C string's last character fails.
///
/// # Example
///
/// ```
/// use nstd_sys::{
///     core::cstr::nstd_core_cstr_from_raw,
///     cstring::{nstd_cstring_from_cstr, nstd_cstring_pop},
///     NSTDChar,
/// };
///
/// unsafe {
///     let cstr = nstd_core_cstr_from_raw("123\0".as_ptr().cast());
///     let mut cstring = nstd_cstring_from_cstr(&cstr);
///     assert!(nstd_cstring_pop(&mut cstring) == b'3' as NSTDChar);
/// }
/// ```
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_pop(cstring: &mut NSTDCString) -> NSTDChar {
    let mut ret = 0;
    let len = nstd_cstring_len(cstring);
    if len > 0 {
        // SAFETY: The C string's length is at least 1.
        unsafe {
            // Write the last character in the C string to the return value.
            let last = nstd_vec_get_mut(&mut cstring.bytes, len - 1).cast::<NSTDChar>();
            ret = *last;
            // Set the last byte to null.
            *last = 0;
            // Pop the old null byte.
            nstd_vec_pop(&mut cstring.bytes);
        }
    }
    ret
}

/// Sets a C string's length to zero.
///
/// # Parameters:
///
/// - `NSTDCString *cstring` - The C string to clear.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
pub extern "C" fn nstd_cstring_clear(cstring: &mut NSTDCString) {
    nstd_vec_clear(&mut cstring.bytes);
}

/// Frees an instance of `NSTDCString`.
///
/// # Parameters:
///
/// - `NSTDCString cstring` - The C string to free.
///
/// # Panics
///
/// Panics if deallocating fails.
#[inline]
#[cfg_attr(feature = "clib", no_mangle)]
#[allow(unused_variables)]
pub extern "C" fn nstd_cstring_free(cstring: NSTDCString) {}