libnv 0.5.0

Safe and rustic wrapper around libnv-sys.
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
//! FreeBSD implementation of Name/value pairs library.
//!
//! All insert operation clone values using `dup(2)` system call. So you
//! don't have to worry about the lifetime of the value. Unless you leak NvList
//! yourself using `unsafe`
//! you don't have to worry about anything. Once list goes out of scope it will
//! call to C library
//! to free all resources associated with it. `nvlist_take_*` and
//! `nvlist_move_*` operations are
//! not supported for this very reason.
//!
//! It's missing a few features:
//!
//! - Sending to socket
//! - Receiving from socket
//! - Insert/Remove file descriptors
//! - Insert/Remove binary
//! - Take operations
//! - Iterator interface
use libc::ENOMEM;

// Importing all because it's cold, I dont want to turn on heater and it's hard
// to type.
use libnv_sys::*;
use std::{convert::{From, Into},
          ffi::CStr,
          os::{raw::{c_char, c_void},
               unix::io::AsRawFd},
          slice};

use crate::{IntoCStr, NvError, NvResult};

/// Enumeration of available data types that the API supports.
pub enum NvType {
    /// Empty type
    None            = 0,
    /// There is no associated data with the name
    Null            = 1,
    /// The value is a `bool` value
    Bool            = 2,
    /// The value is a `u64` value
    Number          = 3,
    /// The value is a C string
    String          = 4,
    /// The value is another `nvlist`
    NvList          = 5,
    /// The value is a file descriptor
    Descriptor      = 6,
    /// The value is a binary buffer
    Binary          = 7,
    /// The value is an array of `bool` values
    BoolArray       = 8,
    /// The value is an array of `u64` values
    NumberArray     = 9,
    /// The value is an array of C strings
    StringArray     = 10,
    /// The value is an array of other `nvlist`'s
    NvListArray     = 11,
    /// The value is an array of file descriptors
    DescriptorArray = 12,
}

/// Options available for creation of an `nvlist`
#[repr(i32)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum NvFlag {
    /// No user specified options.
    None       = 0,
    /// Perform case-insensitive lookups of provided names.
    IgnoreCase = 1,
    /// Names in the nvlist do not have to be unique.
    NoUnique   = 2,
    /// Allow duplicate case-insensitive keys.
    Both       = 3,
}

impl From<i32> for NvFlag {
    /// This should be TryFrom. This function WILL panic if you pass incorrect
    /// value to it. This should be impossible.
    fn from(source: i32) -> Self {
        match source {
            0 => NvFlag::None,
            1 => NvFlag::IgnoreCase,
            2 => NvFlag::NoUnique,
            3 => NvFlag::Both,
            _ => panic!("Incorrect value passed to NvFlag"),
        }
    }
}

macro_rules! impl_list_op {
    ($type_:ty, $method:ident, false) => {
        impl NvTypeOp for $type_ {
            /// Add a `$type_` value to the `NvList`
            fn add_to_list<'a, N: IntoCStr<'a>>(&self, list: &mut NvList, name: N) -> NvResult<()> {
                return list.$method(name, *self);
            }
        }
    };
    ($type_:ty, $method:ident, true) => {
        impl NvTypeOp for $type_ {
            /// Add a `$type_` value to the `NvList`
            fn add_to_list<'a, N: IntoCStr<'a>>(&self, list: &mut NvList, name: N) -> NvResult<()> {
                return list.$method(name, &*self);
            }
        }
    };
}

/// This allows usage of insert method with basic types. Implement this for your
/// own types if you don't want to convert to primitive types every time.
pub trait NvTypeOp {
    /// Add self to given list.
    fn add_to_list<'a, N: IntoCStr<'a>>(&self, list: &mut NvList, name: N) -> NvResult<()>;
}

impl_list_op! {bool, insert_bool, false}
impl_list_op! {[bool], insert_bools, true}
impl_list_op! {u8, insert_number, false}
impl_list_op! {u16, insert_number, false}
impl_list_op! {u32, insert_number, false}
impl_list_op! {u64, insert_number, false}
impl_list_op! {[u64], insert_numbers, true}
impl_list_op! {str, insert_string, true}
impl_list_op! {NvList, insert_nvlist, true}

/// If `Some` insert content to the list. If `None` insert null.
impl<T> NvTypeOp for Option<T>
where
    T: NvTypeOp,
{
    fn add_to_list<'a, N: IntoCStr<'a>>(&self, list: &mut NvList, name: N) -> NvResult<()> {
        match &self {
            Some(val) => val.add_to_list(list, name),
            None => list.insert_null(name),
        }
    }
}

/// A list of name/value pairs.
#[derive(Debug)]
pub struct NvList {
    ptr: *mut nvlist_t,
}

/// A packed [`NvList`]
///
/// This buffer holds an NvList that has been packed into a form suitable for serialization.  It
/// can even be sent to a host with a different endianness.
#[derive(Debug)]
pub struct PackedNvList {
    ptr:  *mut c_void,
    size: usize,
}

/// Like [`PackedNvList`], but it doesn't own the memory
#[derive(Debug)]
pub struct BorrowedPackedNvList<'a> {
    buf: &'a [u8],
}

impl<'a> BorrowedPackedNvList<'a> {
    /// Create a borrowed packed NvList from a Rust buffer
    pub fn from_raw(buf: &'a [u8]) -> Self { BorrowedPackedNvList { buf } }

    /// Get a pointer to the packed buffer, for use with FFI functions.
    pub fn as_ptr(&self) -> *const c_void { self.buf.as_ptr() as *const c_void }

    /// Get a mutable pointer to the packed buffer, for use with FFI functions.
    pub fn as_mut_ptr(&mut self) -> *mut c_void { self.buf.as_ptr() as *mut c_void }

    /// Get the size of the packed buffer
    #[allow(clippy::len_without_is_empty)] // This struct should never be empty
    pub fn len(&self) -> usize { self.buf.len() }

    /// Attempt to unpack the given buffer into an [`NvList`].
    ///
    /// The `flags` should be the same that were originally passed to [`NvList::new`], if it was
    /// created by this library.  Otherwise, they should refer to whatever top level nvlist is
    /// expected.
    pub fn unpack(&self, flags: NvFlag) -> NvResult<NvList> {
        let raw =
            unsafe { nvlist_unpack(self.buf.as_ptr() as *const c_void, self.len(), flags as i32) };
        if raw.is_null() {
            let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            Err(NvError::from_errno(errno))
        } else {
            Ok(NvList { ptr: raw })
        }
    }
}

impl PackedNvList {
    /// Get a pointer to the packed buffer, for use with FFI functions.
    pub fn as_ptr(&self) -> *const c_void { self.ptr }

    /// Get a mutable pointer to the packed buffer, for use with FFI functions.
    pub fn as_mut_ptr(&mut self) -> *mut c_void { self.ptr }

    /// Get the size of the packed buffer
    #[allow(clippy::len_without_is_empty)] // This struct should never be empty
    pub fn len(&self) -> usize { self.size }

    /// Attempt to unpack the given buffer into an [`NvList`].
    ///
    /// The `flags` should be the same that were originally passed to [`NvList::new`], if it was
    /// created by this library.  Otherwise, they should refer to whatever top level nvlist is
    /// expected.
    pub fn unpack(&self, flags: NvFlag) -> NvResult<NvList> {
        let raw = unsafe { nvlist_unpack(self.ptr, self.size, flags as i32) };
        if raw.is_null() {
            let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            Err(NvError::from_errno(errno))
        } else {
            Ok(NvList { ptr: raw })
        }
    }
}

impl Drop for PackedNvList {
    fn drop(&mut self) {
        unsafe {
            libc::free(self.ptr);
        }
    }
}

#[doc(hidden)]
/// Return new list with no flags.
impl Default for NvList {
    fn default() -> NvList { NvList::new(NvFlag::None).expect("Failed to create new list") }
}
impl NvList {
    /// Make a copy of a pointer. Danger zone.
    pub fn as_ptr(&self) -> *mut nvlist_t { self.ptr }

    fn check_if_error(&self) -> NvResult<()> {
        match self.error() {
            0 => Ok(()),
            errno => Err(NvError::NativeError(errno)),
        }
    }

    /// Create a new name/value pair list (`nvlist`). Call this can only fail
    /// when system is out of memory.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let nvlist = NvList::new(NvFlag::None).unwrap();
    /// ```
    pub fn new(flags: NvFlag) -> NvResult<NvList> {
        let raw_list = unsafe { nvlist_create(flags as i32) };
        if raw_list.is_null() {
            Err(NvError::NativeError(ENOMEM))
        } else {
            Ok(NvList { ptr: raw_list })
        }
    }

    /// Take ownership of a raw NvList from C.
    ///
    /// # Safety
    ///
    /// This provided pointer must be valid, and after this function returns
    /// nothing else may access the raw pointer except through the returned
    /// object.
    // Note: this cannot be `impl From<*mut nvlist_t> for Self` because that
    // trait is only for safe conversions.
    pub unsafe fn from_ptr(ptr: *mut nvlist_t) -> Self { Self { ptr } }

    /// Determines if the `nvlist` is empty.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    /// let nvlist = NvList::new(NvFlag::IgnoreCase).unwrap();
    /// assert!(nvlist.is_empty());
    /// ```
    pub fn is_empty(&self) -> bool { unsafe { nvlist_empty(self.ptr) } }

    /// The flags the `nvlist` was created with.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    /// let nvlist = NvList::new(NvFlag::NoUnique).unwrap();
    ///
    /// assert_eq!(nvlist.flags(), NvFlag::NoUnique);
    /// ```
    pub fn flags(&self) -> NvFlag { NvFlag::from(unsafe { nvlist_flags(self.ptr) }) }

    /// Gets error value that the list may have accumulated.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    /// let list = NvList::new(NvFlag::NoUnique).unwrap();
    ///
    /// assert_eq!(0, list.error());
    /// ```
    pub fn error(&self) -> i32 { unsafe { nvlist_error(self.ptr) } }

    /// Sets the `NvList` to be in an error state.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// // EINVAL
    /// list.set_error(0x16).unwrap();
    ///
    /// assert_eq!(0x16, list.error());
    /// ```
    pub fn set_error(&mut self, error: i32) -> NvResult<()> {
        if self.error() != 0 {
            Err(NvError::AlreadySet)
        } else {
            unsafe { nvlist_set_error(self.ptr, error) }
            Ok(())
        }
    }

    /// Sugared way to add a single value to the NvList.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag, NvTypeOp};
    ///
    /// let mut list = NvList::default();
    ///
    /// let the_answer: u32 = 1776;
    /// let not_the_answer: Option<u64> = None;
    ///
    /// list.insert("Important year", the_answer);
    /// list.insert("not important year", not_the_answer);
    /// let copy = list.clone();
    /// list.insert("foo", copy);
    ///
    /// assert_eq!(list.get_number("Important year").unwrap().unwrap(), 1776);
    /// ```
    pub fn insert<'a, N: IntoCStr<'a>, T: NvTypeOp>(&mut self, name: N, value: T) -> NvResult<()> {
        value.add_to_list(self, name)
    }

    /// Add a null value to the `NvList`.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag, NvTypeOp};
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    /// list.insert_null("Hello, World!");
    /// ```
    pub fn insert_null<'a, N: IntoCStr<'a>>(&mut self, name: N) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_null(self.ptr, c_name.as_ptr());
        }
        self.check_if_error()
    }

    /// Add a number to the `NvList`. Number will be converted into u64.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// list.insert_number("Important year", 1776u64);
    /// ```
    pub fn insert_number<'a, N: IntoCStr<'a>, I: Into<u64>>(
        &mut self,
        name: N,
        value: I,
    ) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_number(self.ptr, c_name.as_ptr(), value.into());
        }
        self.check_if_error()
    }

    /// Add a `bool` to the list.
    pub fn insert_bool<'a, N: IntoCStr<'a>>(&mut self, name: N, value: bool) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_bool(self.ptr, c_name.as_ptr(), value);
        }
        self.check_if_error()
    }

    /// Add string to the list.
    pub fn insert_string<'a, 'b, N: IntoCStr<'a>, V: IntoCStr<'b>>(
        &mut self,
        name: N,
        value: V,
    ) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        let c_value = value.into_c_str()?;
        unsafe {
            nvlist_add_string(self.ptr, c_name.as_ptr(), c_value.as_ptr());
        }
        self.check_if_error()
    }

    /// Add `NvList` to the list.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::default();
    ///
    /// let other_list = NvList::default();
    ///
    /// list.insert_nvlist("other list", &other_list).unwrap();
    /// ```
    pub fn insert_nvlist<'a, N: IntoCStr<'a>>(&mut self, name: N, value: &NvList) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        if !value.as_ptr().is_null() {
            unsafe {
                nvlist_add_nvlist(self.ptr, c_name.as_ptr(), value.as_ptr());
            }
        }
        self.check_if_error()
    }

    /// Add binary data to the list.
    ///
    /// # Safety
    ///
    /// `value` must point to valid memory of size at least `size`.
    #[deprecated(since = "0.4.0", note = "use insert_binary instead")]
    pub unsafe fn add_binary<'a, N: IntoCStr<'a>>(
        &mut self,
        name: N,
        value: *const i8,
        size: usize,
    ) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_binary(self.ptr, c_name.as_ptr(), value as *const c_void, size);
        }
        self.check_if_error()
    }

    /// Add a byte array to the list.
    pub fn insert_binary<'a, N: IntoCStr<'a>>(&mut self, name: N, value: &[u8]) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_binary(
                self.ptr,
                c_name.as_ptr(),
                value.as_ptr() as *const c_void,
                value.len(),
            );
        }
        self.check_if_error()
    }

    /// Add an array of `bool` values.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// let slice = [true, false, true, false];
    ///
    /// list.insert_bools("Important year", &slice);
    /// ```
    pub fn insert_bools<'a, N: IntoCStr<'a>>(&mut self, name: N, value: &[bool]) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_bool_array(self.ptr, c_name.as_ptr(), value.as_ptr(), value.len());
        }
        self.check_if_error()
    }

    /// Add an array if `u64`. TODO: Make it work with any number...
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::None).unwrap();
    ///
    /// let slice = [1776, 2017];
    ///
    /// list.insert_numbers("Important year", &slice);
    /// ```
    pub fn insert_numbers<'a, N: IntoCStr<'a>>(&mut self, name: N, value: &[u64]) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_add_number_array(self.ptr, c_name.as_ptr(), value.as_ptr(), value.len());
        }
        self.check_if_error()
    }

    /// Add an array of strings
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::None).unwrap();
    ///
    /// let orig = ["Hello", "World!"];
    ///
    /// list.insert_strings("key", orig).unwrap();
    ///
    /// let vec = list.get_strings("key").unwrap().unwrap();
    ///
    /// assert_eq!(*vec, ["Hello", "World!"]);
    /// ```
    pub fn insert_strings<'a, 'b, N: IntoCStr<'a>, V: IntoCStr<'b>, I: IntoIterator<Item = V>>(
        &mut self,
        name: N,
        value: I,
    ) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        let strings = value.into_iter().map(IntoCStr::into_c_str).collect::<NvResult<Vec<_>>>()?;
        unsafe {
            let pointers: Vec<*const c_char> = strings.iter().map(|e| e.as_ptr()).collect();

            nvlist_add_string_array(
                self.ptr,
                c_name.as_ptr(),
                pointers.as_slice().as_ptr(),
                strings.len(),
            );
        }
        self.check_if_error()
    }

    /// Add an array of `NvList`s
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// let slice = [NvList::new(NvFlag::Both).unwrap(),
    /// NvList::new(NvFlag::Both).unwrap(),
    ///              NvList::new(NvFlag::None).unwrap()];
    ///
    /// list.insert_nvlists("nvlists", &slice);
    ///
    /// let mut nvlists = list.get_nvlists("nvlists").unwrap().unwrap();
    ///
    /// assert_eq!(NvFlag::None, nvlists.pop().unwrap().flags());
    /// ```
    pub fn insert_nvlists<'a, N: IntoCStr<'a>>(
        &mut self,
        name: N,
        value: &[NvList],
    ) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        let vec = value.to_vec();
        unsafe {
            let lists: Vec<*const nvlist_t> =
                vec.iter().map(|item| item.as_ptr() as *const nvlist_t).collect();
            nvlist_add_nvlist_array(
                self.ptr,
                c_name.as_ptr(),
                lists.as_slice().as_ptr(),
                lists.len(),
            );
        }
        self.check_if_error()
    }

    /// Returns `true` if a name/value pair exists in the `NvList` and `false`
    /// otherwise.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// let result = list.insert_number("Important year", 1776u64);
    /// assert!(result.is_ok());
    ///
    /// assert!(list.contains_key("Important year").unwrap());
    /// ```
    pub fn contains_key<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<bool> {
        let c_name = name.into_c_str()?;
        unsafe { Ok(nvlist_exists(self.ptr, c_name.as_ptr())) }
    }

    /// Returns `true` if a name/value pair of the specified type exists and
    /// `false` otherwise.
    /// ```
    /// use libnv::libnv::{NvList, NvFlag, NvType};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// let result = list.insert_number("Important year", 1776u64);
    /// assert!(result.is_ok());
    ///
    /// assert!(!list.contains_key_with_type("Important year", NvType::Bool).unwrap());
    /// ```
    pub fn contains_key_with_type<'a, N: IntoCStr<'a>>(
        &self,
        name: N,
        ty: NvType,
    ) -> NvResult<bool> {
        let c_name = name.into_c_str()?;
        unsafe { Ok(nvlist_exists_type(self.ptr, c_name.as_ptr(), ty as i32)) }
    }

    /// Get the first matching byte slice value for the given name
    ///
    /// ```
    /// use libnv::libnv::NvList;
    ///
    /// let x = [1, 2, 3, 4];
    /// let mut list = NvList::default();
    /// list.insert_binary("x", &x).unwrap();
    ///
    /// let v = list.get_binary("x").unwrap().unwrap();
    /// assert_eq!(&x, v);
    /// ```
    pub fn get_binary<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<&[u8]>> {
        let c_name = name.into_c_str()?;
        unsafe {
            let mut size: usize = 0;
            let ret = nvlist_get_binary(self.ptr, c_name.as_ptr(), &mut size as *mut usize);
            if ret.is_null() {
                Ok(None)
            } else {
                Ok(Some(slice::from_raw_parts(ret as *const u8, size)))
            }
        }
    }

    /// Get the first matching `bool` value paired with
    /// the given name.
    ///
    /// ```
    /// use libnv::libnv::NvList;
    ///
    /// let mut list = NvList::default();
    ///
    /// list.insert_bool("Did history start on 1776?", true).unwrap();
    ///
    /// assert!(list.get_bool("Did history start on 1776?").unwrap().unwrap());
    /// ```
    pub fn get_bool<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<bool>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_bool(self.ptr, c_name.as_ptr()) {
                Ok(Some(nvlist_get_bool(self.ptr, c_name.as_ptr())))
            } else {
                Ok(None)
            }
        }
    }

    /// Get the first matching `u64` value paired with
    /// the given name.
    pub fn get_number<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<u64>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_number(self.ptr, c_name.as_ptr()) {
                Ok(Some(nvlist_get_number(self.ptr, c_name.as_ptr())))
            } else {
                Ok(None)
            }
        }
    }

    /// Get the first matching `u64` value paired with
    /// the given name
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// // Note: we're allowing duplicate values per name
    /// let mut list = NvList::default();
    ///
    /// list.insert_string("Hello", "World!").unwrap();
    ///
    /// assert_eq!(list.get_string("Hello").unwrap().unwrap(), "World!");
    /// ```
    pub fn get_string<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<String>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_string(self.ptr, c_name.as_ptr()) {
                let ret = nvlist_get_string(self.ptr, c_name.as_ptr());
                if ret.is_null() {
                    Ok(None)
                } else {
                    Ok(Some(CStr::from_ptr(ret).to_string_lossy().into_owned()))
                }
            } else {
                Ok(None)
            }
        }
    }

    /// Get the first matching `NvList` value paired with
    /// the given name and clone it
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::Both).unwrap();
    ///
    /// list.insert_bool("other list", true).unwrap();
    ///
    /// let mut other_list = NvList::new(NvFlag::None).unwrap();
    /// other_list.insert_number("Important year", 42u32).unwrap();
    ///
    /// list.insert_nvlist("other list", &other_list).unwrap();
    ///
    /// // Since we use `get_nvlist` we will get the
    /// // NvList not the boolean value
    /// let other_nvlist = list.get_nvlist("other list").unwrap().unwrap();
    ///
    /// assert_eq!(other_nvlist.get_number("Important year").unwrap().unwrap(),
    /// 42);
    /// ```
    pub fn get_nvlist<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<NvList>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_nvlist(self.ptr, c_name.as_ptr()) {
                let res = nvlist_get_nvlist(self.ptr, c_name.as_ptr());
                Ok(Some(NvList { ptr: nvlist_clone(res) }))
            } else {
                Ok(None)
            }
        }
    }

    /// Get a `&[bool]` from the `NvList`
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// // Note: we're allowing duplicate values per name
    /// let mut list = NvList::new(NvFlag::None).unwrap();
    ///
    /// list.insert_bools("true/false", &[true, false, true]).unwrap();
    ///
    /// assert_eq!(list.get_bools("true/false").unwrap().unwrap(), &[true,
    /// false, true]);
    /// ```
    pub fn get_bools<'a, 'b, N: IntoCStr<'b>>(&'a self, name: N) -> NvResult<Option<&'a [bool]>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_bool_array(self.ptr, c_name.as_ptr()) {
                let mut len: usize = 0;
                let arr = nvlist_get_bool_array(self.ptr, c_name.as_ptr(), &mut len as *mut usize);
                Ok(Some(slice::from_raw_parts(arr, len)))
            } else {
                Ok(None)
            }
        }
    }

    /// Get a `&[u64]` slice from the `NvList`
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// // Note: we're allowing duplicate values per name
    /// let mut list = NvList::default();
    ///
    /// list.insert_numbers("The Year", &[1, 7, 7, 6]).unwrap();
    ///
    /// assert_eq!(list.get_numbers("The Year").unwrap().unwrap(), &[1, 7, 7,
    /// 6]);
    /// ```
    pub fn get_numbers<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<&[u64]>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_number_array(self.ptr, c_name.as_ptr()) {
                let mut len: usize = 0;
                let arr =
                    nvlist_get_number_array(self.ptr, c_name.as_ptr(), &mut len as *mut usize);
                Ok(Some(slice::from_raw_parts(arr, len)))
            } else {
                Ok(None)
            }
        }
    }

    /// Get a `Vec<String>` of the first string slice added to the `NvList`
    /// for the given name
    pub fn get_strings<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<Vec<String>>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_string_array(self.ptr, c_name.as_ptr()) {
                let mut len: usize = 0;
                let arr =
                    nvlist_get_string_array(self.ptr, c_name.as_ptr(), &mut len as *mut usize);
                let slice = slice::from_raw_parts(arr, len);
                let strings = slice
                    .iter()
                    .copied()
                    .map(|ptr| String::from(CStr::from_ptr(ptr).to_string_lossy()))
                    .collect();
                Ok(Some(strings))
            } else {
                Ok(None)
            }
        }
    }

    /// Get an array of `NvList`.
    ///
    /// ```
    /// use libnv::libnv::{NvList, NvFlag};
    ///
    /// let mut list = NvList::new(NvFlag::None).unwrap();
    ///
    /// list.insert_nvlists("lists", &[NvList::default(),
    ///                                       NvList::default()]).unwrap();
    ///
    /// let vec = list.get_nvlists("lists").unwrap().unwrap();
    ///
    /// assert_eq!(vec.len(), 2);
    /// assert_eq!(vec[0].flags(), NvFlag::None);
    /// ```
    pub fn get_nvlists<'a, N: IntoCStr<'a>>(&self, name: N) -> NvResult<Option<Vec<NvList>>> {
        let c_name = name.into_c_str()?;
        unsafe {
            if nvlist_exists_nvlist_array(self.ptr, c_name.as_ptr()) {
                let mut len: usize = 0;
                let arr =
                    nvlist_get_nvlist_array(self.ptr, c_name.as_ptr(), &mut len as *mut usize);
                let slice = slice::from_raw_parts(arr, len);
                Ok(Some(slice.iter().map(|item| NvList { ptr: nvlist_clone(*item) }).collect()))
            } else {
                Ok(None)
            }
        }
    }

    /// Write `NvList` to a file descriptor.
    ///
    /// ```
    /// use std::fs::File;
    /// use libnv::libnv::NvList;
    ///
    /// let mut list = NvList::default();
    ///
    /// list.insert_number("Important year", 1776u64);
    ///
    /// list.dump(File::create("/tmp/libnv_nv.dump").unwrap());
    /// ```
    pub fn dump<T: AsRawFd>(&self, out: T) -> NvResult<()> {
        unsafe { nvlist_dump(self.ptr, out.as_raw_fd()) }
        self.check_if_error()
    }

    /// The size of the current list
    pub fn len(&self) -> usize { unsafe { nvlist_size(self.ptr) } }

    /// Removes a key from the `NvList`.
    pub fn remove<'a, N: IntoCStr<'a>>(&mut self, name: N) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_free(self.ptr, c_name.as_ptr());
        }
        self.check_if_error()
    }

    /// Remove the element of the given name and type
    /// from the `NvList`
    pub fn remove_with_type<'a, N: IntoCStr<'a>>(&mut self, name: N, ty: NvType) -> NvResult<()> {
        let c_name = name.into_c_str()?;
        unsafe {
            nvlist_free_type(self.ptr, c_name.as_ptr(), ty as i32);
        }
        self.check_if_error()
    }

    /// Attempt to pack this NvList into a serialized form.
    ///
    /// See the man page for restrictions on which types of NvList may be packed.
    pub fn pack(&self) -> NvResult<PackedNvList> {
        let mut packed = PackedNvList { ptr: std::ptr::null_mut(), size: 0 };
        let ptr = unsafe { nvlist_pack(self.ptr, &mut packed.size) };
        if ptr.is_null() {
            let errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
            Err(NvError::from_errno(errno))
        } else {
            packed.ptr = ptr;
            Ok(packed)
        }
    }
}

impl Clone for NvList {
    /// Clone list using libnv method. This will perform deep copy.
    fn clone(&self) -> NvList { NvList { ptr: unsafe { nvlist_clone(self.ptr) } } }
}

impl Drop for NvList {
    /// Using libnv method.
    fn drop(&mut self) {
        unsafe {
            nvlist_destroy(self.ptr);
        }
    }
}

impl From<NvList> for *mut nvlist_t {
    /// Consume the wrapper and return a raw pointer to the inner structure.
    /// Useful for FFI functions that expect to take ownership of the nvlist.
    fn from(outer: NvList) -> *mut nvlist_t {
        let r = outer.ptr;
        std::mem::forget(outer);
        r
    }
}

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

    mod nvlist_pack {
        use super::*;

        #[test]
        fn ok() {
            let nv = NvList::new(NvFlag::None).unwrap();
            let _packed = nv.pack().unwrap();
        }

        /// nvlist_pack does not work on nvlists with file descriptors
        #[test]
        fn file_descriptors() {
            let nv = NvList::new(NvFlag::None).unwrap();
            let name = c"foo";
            unsafe {
                nvlist_add_descriptor(nv.as_ptr(), name.as_ptr(), 1);
            }
            assert!(matches!(nv.pack().unwrap_err(), NvError::OperationNotSupported));
        }
    }

    mod nvlist_unpack {
        use super::*;

        #[test]
        fn bad_flags() {
            let mut nv = NvList::new(NvFlag::None).unwrap();
            nv.insert_number("Answer", 42u64).unwrap();
            let packed = nv.pack().unwrap();
            assert!(matches!(packed.unpack(NvFlag::IgnoreCase).unwrap_err(), NvError::Io(_)));
        }

        #[test]
        fn borrowed() {
            // Create a valid packed nvlist and clone it, just so we know it will have a different
            // address than anything allocated by libnv.so
            let buf = {
                let mut nv = NvList::new(NvFlag::None).unwrap();
                nv.insert_number("Answer", 42u64).unwrap();
                let packed = nv.pack().unwrap();
                let buf =
                    unsafe { std::slice::from_raw_parts(packed.ptr as *const u8, packed.len()) };
                buf.to_vec()
            };

            let borrowed = BorrowedPackedNvList::from_raw(&buf);

            let nv2 = borrowed.unpack(NvFlag::None).unwrap();
            assert_eq!(nv2.get_number("Answer").unwrap(), Some(42u64));
        }

        #[test]
        fn corruption() {
            let mut buf = [42u8; 100];
            // PackedNvList is "corrupt"!
            let packed = std::mem::ManuallyDrop::new(PackedNvList {
                ptr:  buf.as_mut_ptr() as *mut c_void,
                size: 100,
            });
            assert!(matches!(packed.unpack(NvFlag::None).unwrap_err(), NvError::Io(_)));
            // Drop packed without running its destructor
        }

        #[test]
        fn ok() {
            let mut nv = NvList::new(NvFlag::None).unwrap();
            nv.insert_number("Answer", 42u64).unwrap();
            let packed = nv.pack().unwrap();
            let nv2 = packed.unpack(NvFlag::None).unwrap();
            assert_eq!(nv2.get_number("Answer").unwrap(), Some(42u64));
        }
    }
}