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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
use crate::{EmbeddedNulError, InvalidUTF8Error};
use ffizz_passby::OpaqueStruct;
use std::ffi::{CStr, CString, OsString};
use std::path::PathBuf;

/// A FzString carries a single string between Rust and C code, represented from the C side as
/// an opaque struct.
///
/// The two environments carry some different requirements: C generally requires that strings be
/// NUL-terminated, while Rust requires that strings be valid UTF-8.  Rust also permits NUL
/// characters in the middle of a string.
///
/// This type accepts whatever kind of data it receives without error, and converts -- potentially
/// with an error -- when output of a different kind is required.
///
/// A number of `From<T>` implementations are provided to convert from common Rust types. The
/// `fz_string_..` utility functions provide conversions from various string formats.
///
/// FzStrings also have a special "Null" state, similar to the None variant of Option.  For user
/// convenience, a NULL pointer is treated as a pointer to the Null variant wherever a pointer is
/// accepted.  Rust code should use the `_nonnull` methods where the Null variant is not allowed.
/// Note that the Null variant is not necessarily represented with an all-zero byte pattern.
///
/// A FzString points to allocated memory, and must be freed to avoid memory leaks.
#[derive(PartialEq, Eq, Debug)]
pub enum FzString<'a> {
    /// An un-set FzString.
    Null,
    /// An owned Rust string (not NUL-terminated, valid UTF-8).
    String(String),
    /// An owned C String (NUL-terminated, may contain invalid UTF-8).
    CString(CString),
    /// A borrowed C string.
    CStr(&'a CStr),
    /// An owned bunch of bytes (not NUL-terminated, may contain invalid UTF-8).
    Bytes(Vec<u8>),
}

/// fz_string_t represents a string suitable for use with this crate, as an opaque stack-allocated
/// value.
///
/// This value can contain either a string or a special "Null" variant indicating there is no
/// string.  When functions take a `fz_string_t*` as an argument, the NULL pointer is treated as
/// the Null variant.  Note that the Null variant is not necessarily represented as the zero value
/// of the struct.
///
/// # Safety
///
/// A fz_string_t must always be initialized before it is passed as an argument.  Functions
/// returning a `fz_string_t` return an initialized value.
///
/// Each initialized fz_string_t must be freed, either by calling fz_string_free or by
/// passing the string to a function which takes ownership of the string.
///
/// For a given fz_string_t value, API functions must not be called concurrently.  This includes
/// "read only" functions such as fz_string_content.
///
/// ```c
/// typedef struct fz_string_t {
///     uint64_t __reserved[4];
/// };
/// ```
#[repr(C)]
pub struct fz_string_t {
    // size for a determinant, pointer, length, and capacity; conservatively assuming
    // 64 bits for each, and assuring 64-bit alignment.
    __reserved: [u64; 4],
}

impl OpaqueStruct for FzString<'_> {
    type CType = fz_string_t;

    fn null_value() -> Self {
        FzString::Null
    }
}

impl Default for FzString<'_> {
    fn default() -> Self {
        FzString::Null
    }
}

impl<'a> FzString<'a> {
    /// Check if this is a Null FzString.
    pub fn is_null(&self) -> bool {
        matches!(self, Self::Null)
    }

    /// Convert this value to `&str`.
    ///
    /// If required, the FzString is converted in-place to a String variant. If this conversion
    /// fails because the content is not valid UTF-8, an error is returned.
    ///
    /// The Null FzString is represented as None.
    pub fn as_str(&mut self) -> Result<Option<&str>, InvalidUTF8Error> {
        // first, convert in-place from bytes
        if let FzString::Bytes(_) = self {
            self.bytes_to_string()?;
        }

        Ok(match self {
            FzString::CString(cstring) => {
                Some(cstring.as_c_str().to_str().map_err(|_| InvalidUTF8Error)?)
            }
            FzString::CStr(cstr) => Some(cstr.to_str().map_err(|_| InvalidUTF8Error)?),
            FzString::String(ref string) => Some(string.as_ref()),
            FzString::Bytes(_) => unreachable!(), // handled above
            FzString::Null => None,
        })
    }

    /// Convert this FzString, assuming it is not Null, into `&str`.
    ///
    /// This is a simple wrapper that will panic on the Null variant.  This is useful when
    /// the C API prohibits NULL.
    pub fn as_str_nonnull(&mut self) -> Result<&str, InvalidUTF8Error> {
        self.as_str()
            .map(|opt| opt.expect("unexpected NULL string"))
    }

    /// Convert this value to a CStr: a slice of bytes containing a valid, NUL-terminated C string.
    ///
    /// If required, the FzString is converted in-place to a CString variant. If this conversion
    /// fails because the content contains embedded NUL characters, an error is returned.
    ///
    /// The Null FzString is represented as None.
    pub fn as_cstr(&mut self) -> Result<Option<&CStr>, EmbeddedNulError> {
        // first, convert in-place from String or Bytes (neither of which have a NUL terminator)
        match self {
            FzString::String(_) => self.string_to_cstring()?,
            FzString::Bytes(_) => self.bytes_to_cstring()?,
            _ => {}
        }

        Ok(match self {
            FzString::CString(cstring) => Some(cstring.as_c_str()),
            FzString::CStr(cstr) => Some(cstr),
            FzString::String(_) => unreachable!(), // handled above
            FzString::Bytes(_) => unreachable!(),  // handled above
            FzString::Null => None,
        })
    }

    /// Convert this FzString, assuming it is not Null, into a CStr.
    ///
    /// This is a simple wrapper that will panic on the Null variant.  This is useful when
    /// the C API prohibits NULL.
    pub fn as_cstr_nonnull(&mut self) -> Result<&CStr, EmbeddedNulError> {
        self.as_cstr()
            .map(|opt| opt.expect("unexpected NULL string"))
    }

    /// Consume this FzString and return an equivalent String.
    ///
    /// As with `as_str`, the FzString is converted in-place, and this conversion can fail.  In the
    /// failure case, the original data is lost.
    ///
    /// The Null varaiant is represented as None.
    pub fn into_string(mut self) -> Result<Option<String>, InvalidUTF8Error> {
        // first, convert in-place from bytes
        if let FzString::Bytes(_) = self {
            self.bytes_to_string()?;
        }

        Ok(match self {
            FzString::CString(cstring) => {
                Some(cstring.into_string().map_err(|_| InvalidUTF8Error)?)
            }
            FzString::CStr(cstr) => Some(
                cstr.to_str()
                    .map(|s| s.to_string())
                    .map_err(|_| InvalidUTF8Error)?,
            ),
            FzString::String(string) => Some(string),
            FzString::Bytes(_) => unreachable!(), // handled above
            FzString::Null => None,
        })
    }

    /// Consume this FzString, assuming it is not Null, and return an equivalent String.
    ///
    /// This is a simple wrapper that will panic on the Null variant.  This is useful when
    /// the C API prohibits NULL.
    pub fn into_string_nonnull(self) -> Result<String, InvalidUTF8Error> {
        self.into_string()
            .map(|opt| opt.expect("unexpected NULL string"))
    }

    /// Consume this FzString and return an equivalent PathBuf.
    ///
    /// As with `as_str`, the FzString is converted in-place, and this conversion can fail.  In the
    /// failure case, the original data is lost.
    ///
    /// The Null varaiant is represented as None.
    pub fn into_path_buf(self) -> Result<Option<PathBuf>, std::str::Utf8Error> {
        #[cfg(unix)]
        let path: Option<OsString> = {
            // on UNIX, we can use the bytes directly, without requiring that they
            // be valid UTF-8.
            use std::ffi::OsStr;
            use std::os::unix::ffi::OsStrExt;
            self.as_bytes()
                .map(|bytes| OsStr::from_bytes(bytes).to_os_string())
        };
        #[cfg(windows)]
        let path: Option<OsString> = {
            // on Windows, we assume the filename is valid Unicode, so it can be
            // represented as UTF-8.
            self.into_string()?.map(|s| OsString::from(s))
        };
        Ok(path.map(|p| p.into()))
    }

    /// Consume this FzString, assuming it is not Null, and return an equivalent PathBuf.
    ///
    /// This is a simple wrapper that will panic on the Null variant.  This is useful when
    /// the C API prohibits NULL.
    pub fn into_path_buf_nonnull(self) -> Result<PathBuf, std::str::Utf8Error> {
        self.into_path_buf()
            .map(|opt| opt.expect("unexpected NULL string"))
    }

    /// Get the slice of bytes representing the content of this value, not including any NUL
    /// terminator.
    ///
    /// Any variant can be represented as a byte slice, so this method does not mutate the
    /// FzString and cannot fail.
    ///
    /// The Null variant is represented as None.
    pub fn as_bytes(&self) -> Option<&[u8]> {
        match self {
            FzString::CString(cstring) => Some(cstring.as_bytes()),
            FzString::CStr(cstr) => Some(cstr.to_bytes()),
            FzString::String(string) => Some(string.as_bytes()),
            FzString::Bytes(bytes) => Some(bytes.as_ref()),
            FzString::Null => None,
        }
    }

    /// Get the slice of bytes representing the content of this value, not including any NUL
    /// terminator, panicing if this is the Null Variant.
    ///
    /// This is a simple wrapper that will panic on the Null variant.  This is useful when
    /// the C API prohibits NULL.
    pub fn as_bytes_nonnull(&self) -> &[u8] {
        self.as_bytes().expect("unexpected NULL string")
    }

    /// Call the contained function with a shared reference to the FzString.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::with_ref`.
    ///
    /// # Safety
    ///
    /// * fzstr must be NULL or point to a valid fz_string_t value
    /// * no other thread may mutate the value pointed to by fzstr until with_ref returns.
    #[inline]
    pub unsafe fn with_ref<T, F: Fn(&FzString) -> T>(fzstr: *const fz_string_t, f: F) -> T {
        unsafe { <Self as OpaqueStruct>::with_ref(fzstr, f) }
    }

    /// Call the contained function with an exclusive reference to the FzString.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::with_ref_mut`.
    ///
    /// # Safety
    ///
    /// * fzstr must be NULL or point to a valid `fz_string_t` value
    /// * no other thread may access the value pointed to by `fzstr` until `with_ref_mut` returns.
    #[inline]
    pub unsafe fn with_ref_mut<T, F: Fn(&mut FzString) -> T>(fzstr: *mut fz_string_t, f: F) -> T {
        unsafe { <Self as OpaqueStruct>::with_ref_mut(fzstr, f) }
    }

    /// Initialize the value pointed to fzstr with, "moving" it into the pointer.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::to_out_param`.
    ///
    /// If the pointer is NULL, the value is dropped.
    ///
    /// # Safety
    ///
    /// * if fzstr is not NULl, then it must be aligned for fz_string_t, and must have enough space
    ///   for fz_string_t.
    /// * ownership of the string is transfered to `*fzstr` or dropped.
    #[inline]
    pub unsafe fn to_out_param(self, fzstr: *mut fz_string_t) {
        unsafe { <Self as OpaqueStruct>::to_out_param(self, fzstr) }
    }

    /// Initialize the value pointed to fzstr with, "moving" it into the pointer.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::to_out_param_nonnull`.
    ///
    /// If the pointer is NULL, this method will panic.  Use this when the C API requires that the
    /// pointer be non-NULL.
    ///
    /// # Safety
    ///
    /// * fzstr must not be NULL, must be aligned for fz_string_t, and must have enough space for
    ///   fz_string_t.
    /// * ownership of the string is transfered to `*fzstr`.
    #[inline]
    pub unsafe fn to_out_param_nonnull(self, fzstr: *mut fz_string_t) {
        unsafe { <Self as OpaqueStruct>::to_out_param_nonnull(self, fzstr) }
    }

    /// Return a `fz_string_t` transferring ownership out of the function.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::return_val`.
    ///
    /// # Safety
    ///
    /// * to avoid a leak, ownership of the value must eventually be returned to Rust.
    #[inline]
    pub unsafe fn return_val(self) -> fz_string_t {
        unsafe { <Self as OpaqueStruct>::return_val(self) }
    }

    /// Take a `fz_string_t` by value and return an owned `FzString`.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::take`.
    ///
    /// This method is intended for C API functions that take a string by value and are
    /// documented as taking ownership of the value.  However, this means that C retains
    /// an expired "copy" of the value and could lead to use-after-free errors.
    ///
    /// Where compatible with the API design, prefer to use pointers in the C API and use
    /// [`FzString::take_ptr`] to ensure the old value is invalidated.
    ///
    /// # Safety
    ///
    /// * fzstr must be a valid `fz_string_t` value
    #[inline]
    pub unsafe fn take(fzstr: fz_string_t) -> Self {
        unsafe { <Self as OpaqueStruct>::take(fzstr) }
    }

    /// Take a pointer to a CType and return an owned value.
    ///
    /// This is a wrapper around `ffizz_passby::OpaqueStruct::take_ptr`.
    ///
    /// This is intended for C API functions that take a value by reference (pointer), but still
    /// "take ownership" of the value.  It leaves behind an invalid value, where any non-padding
    /// bytes of the Rust type are zeroed.  This makes use-after-free errors in the C code more
    /// likely to crash instead of silently working.  Which is about as good as it gets in C.
    ///
    /// Do _not_ pass a pointer to a Rust value to this function:
    ///
    /// ```ignore
    /// let rust_value = RustType::take_ptr(&mut c_value); // BAD!
    /// ```
    ///
    /// This creates undefined behavior as Rust will assume `c_value` is still initialized. Use
    /// `take` in this situation.
    ///
    /// # Safety
    ///
    /// * fzstr must be NULL or point to a valid fz_string_t value.
    /// * the memory pointed to by fzstr is uninitialized when this function returns.
    #[inline]
    pub unsafe fn take_ptr(fzstr: *mut fz_string_t) -> Self {
        unsafe { <Self as OpaqueStruct>::take_ptr(fzstr) }
    }

    /// Convert the FzString, in place, from a Bytes to String variant, returning None if
    /// the bytes do not contain valid UTF-8.
    fn bytes_to_string(&mut self) -> Result<(), InvalidUTF8Error> {
        if let FzString::Bytes(bytes) = self {
            // first, check for invalid UTF-8
            if std::str::from_utf8(bytes).is_err() {
                return Err(InvalidUTF8Error);
            }
            // take ownership of the bytes Vec
            let bytes = std::mem::take(bytes);
            // SAFETY: we just checked this..
            let string = unsafe { String::from_utf8_unchecked(bytes) };
            *self = FzString::String(string);
            Ok(())
        } else {
            unreachable!()
        }
    }

    /// Convert the FxString, in place, from a Bytes to CString variant, returning None if the
    /// string contains embedded NULs.
    ///
    /// Panics if self is not Bytes.
    fn bytes_to_cstring(&mut self) -> Result<(), EmbeddedNulError> {
        if let FzString::Bytes(bytes) = self {
            // first, check for NUL bytes within the sequence
            if has_nul_bytes(bytes) {
                return Err(EmbeddedNulError);
            }
            // take ownership of the bytes Vec
            let bytes = std::mem::take(bytes);
            // SAFETY: we just checked for NUL bytes
            let cstring = unsafe { CString::from_vec_unchecked(bytes) };
            *self = FzString::CString(cstring);
            Ok(())
        } else {
            unreachable!()
        }
    }

    /// Convert the FzString, in place, from a String to CString variant, returning None if the
    /// string contains embedded NULs.
    ///
    /// Panics if self is not String.
    fn string_to_cstring(&mut self) -> Result<(), EmbeddedNulError> {
        if let FzString::String(string) = self {
            // first, check for NUL bytes within the sequence
            if has_nul_bytes(string.as_bytes()) {
                return Err(EmbeddedNulError);
            }
            // take ownership of the string
            let string = std::mem::take(string);
            // SAFETY: we just checked for NUL bytes
            let cstring = unsafe { CString::from_vec_unchecked(string.into_bytes()) };
            *self = FzString::CString(cstring);
            Ok(())
        } else {
            unreachable!()
        }
    }
}

impl From<String> for FzString<'static> {
    fn from(string: String) -> FzString<'static> {
        FzString::String(string)
    }
}

impl From<&str> for FzString<'static> {
    fn from(string: &str) -> FzString<'static> {
        FzString::String(string.to_string())
    }
}

impl From<Vec<u8>> for FzString<'static> {
    fn from(bytes: Vec<u8>) -> FzString<'static> {
        FzString::Bytes(bytes)
    }
}

impl From<&[u8]> for FzString<'static> {
    fn from(bytes: &[u8]) -> FzString<'static> {
        FzString::Bytes(bytes.to_vec())
    }
}

impl From<Option<String>> for FzString<'static> {
    fn from(string: Option<String>) -> FzString<'static> {
        match string {
            Some(string) => FzString::String(string),
            None => FzString::Null,
        }
    }
}

impl From<Option<&str>> for FzString<'static> {
    fn from(string: Option<&str>) -> FzString<'static> {
        match string {
            Some(string) => FzString::String(string.to_string()),
            None => FzString::Null,
        }
    }
}

impl From<Option<Vec<u8>>> for FzString<'static> {
    fn from(bytes: Option<Vec<u8>>) -> FzString<'static> {
        match bytes {
            Some(bytes) => FzString::Bytes(bytes),
            None => FzString::Null,
        }
    }
}

impl From<Option<&[u8]>> for FzString<'static> {
    fn from(bytes: Option<&[u8]>) -> FzString<'static> {
        match bytes {
            Some(bytes) => FzString::Bytes(bytes.to_vec()),
            None => FzString::Null,
        }
    }
}

fn has_nul_bytes(bytes: &[u8]) -> bool {
    bytes.iter().any(|c| *c == b'\0')
}

#[cfg(test)]
mod test {
    use super::*;

    const INVALID_UTF8: &[u8] = b"abc\xf0\x28\x8c\x28";

    fn make_cstring() -> FzString<'static> {
        FzString::CString(CString::new("a string").unwrap())
    }

    fn make_cstr() -> FzString<'static> {
        let cstr = CStr::from_bytes_with_nul(b"a string\0").unwrap();
        FzString::CStr(cstr)
    }

    fn make_string() -> FzString<'static> {
        "a string".into()
    }

    fn make_string_with_nul() -> FzString<'static> {
        "a \0 nul!".into()
    }

    fn make_invalid_bytes() -> FzString<'static> {
        INVALID_UTF8.into()
    }

    fn make_nul_bytes() -> FzString<'static> {
        (&b"abc\0123"[..]).into()
    }

    fn make_bytes() -> FzString<'static> {
        (&b"bytes"[..]).into()
    }

    fn make_null() -> FzString<'static> {
        FzString::Null
    }

    fn cstr(s: &str) -> &CStr {
        CStr::from_bytes_with_nul(s.as_bytes()).unwrap()
    }

    // as_str

    #[test]
    fn as_str_cstring() {
        assert_eq!(make_cstring().as_str().unwrap(), Some("a string"));
    }

    #[test]
    fn as_str_cstr() {
        assert_eq!(make_cstr().as_str().unwrap(), Some("a string"));
    }

    #[test]
    fn as_str_string() {
        assert_eq!(make_string().as_str().unwrap(), Some("a string"));
    }

    #[test]
    fn as_str_string_with_nul() {
        assert_eq!(make_string_with_nul().as_str().unwrap(), Some("a \0 nul!"));
    }

    #[test]
    fn as_str_invalid_bytes() {
        assert_eq!(make_invalid_bytes().as_str().unwrap_err(), InvalidUTF8Error);
    }

    #[test]
    fn as_str_nul_bytes() {
        assert_eq!(make_nul_bytes().as_str().unwrap(), Some("abc\0123"));
    }

    #[test]
    fn as_str_valid_bytes() {
        assert_eq!(make_bytes().as_str().unwrap(), Some("bytes"));
    }

    #[test]
    fn as_str_null() {
        assert!(make_null().as_str().unwrap().is_none());
    }

    #[test]
    fn as_str_nonnull_string() {
        assert_eq!(make_string().as_str_nonnull().unwrap(), "a string");
    }

    #[test]
    #[should_panic]
    fn as_str_nonnull_null() {
        let _res = make_null().as_str_nonnull();
    }

    // as_cstr

    #[test]
    fn as_cstr_cstring() {
        assert_eq!(make_cstring().as_cstr().unwrap(), Some(cstr("a string\0")));
    }

    #[test]
    fn as_cstr_cstr() {
        assert_eq!(make_cstr().as_cstr().unwrap(), Some(cstr("a string\0")));
    }

    #[test]
    fn as_cstr_string() {
        assert_eq!(make_string().as_cstr().unwrap(), Some(cstr("a string\0")));
    }

    #[test]
    fn as_cstr_string_with_nul() {
        assert_eq!(
            make_string_with_nul().as_cstr().unwrap_err(),
            EmbeddedNulError
        );
    }

    #[test]
    fn as_cstr_invalid_bytes() {
        let expected = CString::new(INVALID_UTF8).unwrap();
        assert_eq!(
            make_invalid_bytes().as_cstr().unwrap(),
            Some(expected.as_c_str())
        );
    }

    #[test]
    fn as_cstr_nul_bytes() {
        assert_eq!(make_nul_bytes().as_cstr().unwrap_err(), EmbeddedNulError);
    }

    #[test]
    fn as_cstr_valid_bytes() {
        assert_eq!(make_bytes().as_cstr().unwrap(), Some(cstr("bytes\0")));
    }

    #[test]
    fn as_cstr_null() {
        assert_eq!(make_null().as_cstr().unwrap(), None);
    }

    #[test]
    fn as_cstr_nonnull_string() {
        assert_eq!(make_string().as_cstr_nonnull().unwrap(), cstr("a string\0"));
    }

    #[test]
    #[should_panic]
    fn as_cstr_nonnull_null() {
        let _res = make_null().as_cstr_nonnull();
    }

    // into_string

    #[test]
    fn into_string_cstring() {
        assert_eq!(
            make_cstring().into_string().unwrap(),
            Some(String::from("a string"))
        );
    }

    #[test]
    fn into_string_cstr() {
        assert_eq!(
            make_cstr().into_string().unwrap(),
            Some(String::from("a string"))
        );
    }

    #[test]
    fn into_string_string() {
        assert_eq!(
            make_string().into_string().unwrap(),
            Some(String::from("a string"))
        );
    }

    #[test]
    fn into_string_string_with_nul() {
        assert_eq!(
            make_string_with_nul().into_string().unwrap(),
            Some(String::from("a \0 nul!"))
        )
    }

    #[test]
    fn into_string_invalid_bytes() {
        assert_eq!(
            make_invalid_bytes().into_string().unwrap_err(),
            InvalidUTF8Error
        );
    }

    #[test]
    fn into_string_nul_bytes() {
        assert_eq!(
            make_nul_bytes().into_string().unwrap(),
            Some(String::from("abc\0123"))
        );
    }

    #[test]
    fn into_string_valid_bytes() {
        assert_eq!(
            make_bytes().into_string().unwrap(),
            Some(String::from("bytes"))
        );
    }

    #[test]
    fn into_string_null() {
        assert_eq!(make_null().into_string().unwrap(), None);
    }

    #[test]
    fn into_string_nonnull_string() {
        assert_eq!(
            make_string().into_string_nonnull().unwrap(),
            String::from("a string")
        );
    }

    #[test]
    #[should_panic]
    fn into_string_nonnull_null() {
        let _res = make_null().into_string_nonnull();
    }

    // into_path_buf

    #[test]
    fn into_path_buf_cstring() {
        assert_eq!(
            make_cstring().into_path_buf().unwrap(),
            Some(PathBuf::from("a string"))
        );
    }

    #[test]
    fn into_path_buf_cstr() {
        assert_eq!(
            make_cstr().into_path_buf().unwrap(),
            Some(PathBuf::from("a string"))
        );
    }

    #[test]
    fn into_path_buf_string() {
        assert_eq!(
            make_string().into_path_buf().unwrap(),
            Some(PathBuf::from("a string"))
        );
    }

    #[test]
    fn into_path_buf_string_with_nul() {
        assert_eq!(
            make_string_with_nul().into_path_buf().unwrap(),
            Some(PathBuf::from("a \0 nul!"))
        )
    }

    #[test]
    fn into_path_buf_invalid_bytes() {
        #[cfg(windows)] // windows filenames are unicode
        assert!(make_invalid_bytes().into_path_buf().is_err());
        #[cfg(unix)] // UNIX doesn't care
        assert!(make_invalid_bytes().into_path_buf().is_ok());
    }

    #[test]
    fn into_path_buf_nul_bytes() {
        assert_eq!(
            make_nul_bytes().into_path_buf().unwrap(),
            Some(PathBuf::from("abc\0123"))
        );
    }

    #[test]
    fn into_path_buf_valid_bytes() {
        assert_eq!(
            make_bytes().into_path_buf().unwrap(),
            Some(PathBuf::from("bytes"))
        );
    }

    #[test]
    fn into_path_buf_null() {
        assert_eq!(make_null().into_path_buf().unwrap(), None);
    }

    #[test]
    fn into_path_buf_nonnull_string() {
        assert_eq!(
            make_string().into_path_buf_nonnull().unwrap(),
            PathBuf::from("a string")
        );
    }

    #[test]
    #[should_panic]
    fn into_path_buf_nonnull_null() {
        let _res = make_null().into_path_buf_nonnull();
    }

    // as_bytes

    #[test]
    fn as_bytes_cstring() {
        assert_eq!(make_cstring().as_bytes().unwrap(), b"a string");
    }

    #[test]
    fn as_bytes_cstr() {
        assert_eq!(make_cstr().as_bytes().unwrap(), b"a string");
    }

    #[test]
    fn as_bytes_string() {
        assert_eq!(make_string().as_bytes().unwrap(), b"a string");
    }

    #[test]
    fn as_bytes_string_with_nul() {
        assert_eq!(make_string_with_nul().as_bytes().unwrap(), b"a \0 nul!");
    }

    #[test]
    fn as_bytes_invalid_bytes() {
        assert_eq!(make_invalid_bytes().as_bytes().unwrap(), INVALID_UTF8);
    }

    #[test]
    fn as_bytes_null_bytes() {
        assert_eq!(make_nul_bytes().as_bytes().unwrap(), b"abc\0123");
    }

    #[test]
    fn as_bytes_null() {
        assert_eq!(make_null().as_bytes(), None);
    }

    #[test]
    fn as_bytes_nonnul_string() {
        assert_eq!(make_string().as_bytes_nonnull(), b"a string");
    }

    #[test]
    #[should_panic]
    fn as_bytes_nonnull_null() {
        let _res = make_null().as_bytes_nonnull();
    }

    // From<..>

    #[test]
    fn from_string() {
        assert_eq!(
            FzString::from(String::from("hello")),
            FzString::String(String::from("hello"))
        );
    }

    #[test]
    fn from_str() {
        assert_eq!(
            FzString::from("hello"),
            FzString::String(String::from("hello"))
        );
    }

    #[test]
    fn from_vec() {
        assert_eq!(FzString::from(vec![1u8, 2u8]), FzString::Bytes(vec![1, 2]));
    }

    #[test]
    fn from_bytes() {
        assert_eq!(FzString::from(INVALID_UTF8), make_invalid_bytes());
    }

    #[test]
    fn from_option_string() {
        assert_eq!(FzString::from(None as Option<String>), FzString::Null);
        assert_eq!(
            FzString::from(Some(String::from("hello"))),
            FzString::String(String::from("hello")),
        );
    }

    #[test]
    fn from_option_str() {
        assert_eq!(FzString::from(None as Option<&str>), FzString::Null);
        assert_eq!(
            FzString::from(Some("hello")),
            FzString::String(String::from("hello")),
        );
    }

    #[test]
    fn from_option_vec() {
        assert_eq!(FzString::from(None as Option<Vec<u8>>), FzString::Null);
        assert_eq!(
            FzString::from(Some(vec![1u8, 2u8])),
            FzString::Bytes(vec![1, 2])
        );
    }

    #[test]
    fn from_option_bytes() {
        assert_eq!(FzString::from(None as Option<&[u8]>), FzString::Null);
        assert_eq!(
            FzString::from(Some(INVALID_UTF8)),
            FzString::Bytes(INVALID_UTF8.into())
        );
    }
}