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
extern crate nvpair_sys as sys;
extern crate cstr_argument;
#[macro_use]
extern crate foreign_types;

use cstr_argument::CStrArgument;
use std::io;
use std::ptr;
use std::ffi;
use std::os::raw::c_int;
use foreign_types::{Opaque, ForeignTypeRef, ForeignType};

pub enum NvData {
    Bool,
    BoolV(bool),
    Byte(u8),
    Int8(i8),
    Uint8(i8),
    Int16(i16),
    Uint16(u16),
    Int32(i32),
    Uint32(u32),
    Int64(i64),
    Uint64(u64),
    String(ffi::CString),
    NvListRef(NvList),
    // TODO: arrays
    // hrtime
    // double
}

pub trait NvEncode {
    fn insert<S: CStrArgument>(&self, S, &mut NvListRef) -> io::Result<()>;
    //fn read(NvPair &nv) -> io::Result<Self>;
}

impl NvEncode for bool {
    fn insert<S: CStrArgument>(&self, name: S, nv: &mut NvListRef) -> io::Result<()>
    {
        let name = name.into_cstr();
        let v = unsafe {
            sys::nvlist_add_boolean_value(nv.as_mut_ptr(), name.as_ref().as_ptr(),
                if *self {
                    sys::boolean::B_TRUE
                } else {
                    sys::boolean::B_FALSE
                }
            )
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(())
        }
    }
}

impl NvEncode for u32 {
    fn insert<S: CStrArgument>(&self, name: S, nv: &mut NvListRef) -> io::Result<()>
    {
        let name = name.into_cstr();
        let v = unsafe {
            sys::nvlist_add_uint32(nv.as_mut_ptr(), name.as_ref().as_ptr(), *self)
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(())
        }
    }
}

impl NvEncode for ffi::CStr {
    fn insert<S: CStrArgument>(&self, name: S, nv: &mut NvListRef) -> io::Result<()>
    {
        let name = name.into_cstr();
        let v = unsafe {
            sys::nvlist_add_string(nv.as_mut_ptr(), name.as_ref().as_ptr(), self.as_ptr())
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(())
        }
    }
}

impl NvEncode for NvListRef {
    fn insert<S: CStrArgument>(&self, name: S, nv: &mut NvListRef) -> io::Result<()>
    {
        let name = name.into_cstr();
        let v = unsafe {
            sys::nvlist_add_nvlist(nv.as_mut_ptr(), name.as_ref().as_ptr(), self.as_ptr() as *mut _)
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
            } else {
            Ok(())
        }
    }
}

pub enum NvEncoding {
    Native,
    Xdr
}

impl NvEncoding {
    fn as_raw(&self) -> c_int {
        match self {
            &NvEncoding::Native => sys::NV_ENCODE_NATIVE,
            &NvEncoding::Xdr => sys::NV_ENCODE_XDR
        }
    }
}

foreign_type! {
    type CType = sys::nvlist;
    fn drop = sys::nvlist_free;
    /// An `NvList`
    pub struct NvList;
    /// A borrowed `NvList`
    pub struct NvListRef;
}

impl NvList {
    /// Create a new `NvList` with no options
    pub fn new() -> io::Result<Self> {
        let mut n = ptr::null_mut();
        let v = unsafe {
            // TODO: second arg is a bitfield of NV_UNIQUE_NAME|NV_UNIQUE_NAME_TYPE
            sys::nvlist_alloc(&mut n, 0, 0)
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(unsafe { Self::from_ptr(n) }) 
        }
    }

    /// Create a new `NvList` with the `NV_UNIQUE_NAME` constraint
    pub fn new_unqiue_names() -> io::Result<Self> {
        let mut n = ptr::null_mut();
        let v = unsafe {
            sys::nvlist_alloc(&mut n, sys::NV_UNIQUE_NAME, 0)
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(unsafe { Self::from_ptr(n) }) 
        }
    }

    pub fn try_clone(&self) -> io::Result<Self> {
        let mut n = ptr::null_mut();
        let v = unsafe { sys::nvlist_dup(self.0, &mut n, 0) };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(unsafe { Self::from_ptr(n) })
        }
    }
}

impl Clone for NvList {
    fn clone(&self) -> Self {
        self.try_clone().unwrap()
    }
}

impl NvListRef {
    pub unsafe fn from_mut_ptr<'a>(v: *mut sys::nvlist) -> &'a mut Self
    {
        std::mem::transmute::<*mut sys::nvlist, &mut Self>(v)
    }

    pub unsafe fn from_ptr<'a>(v: *const sys::nvlist) -> &'a Self
    {
        std::mem::transmute::<*const sys::nvlist, &Self>(v)
    }

    pub fn as_mut_ptr(&mut self) -> *mut sys::nvlist
    {
        unsafe { std::mem::transmute::<&mut NvListRef, *mut sys::nvlist>(self) }
    }

    pub fn as_ptr(&self) -> *const sys::nvlist
    {
        unsafe { std::mem::transmute::<&NvListRef, *const sys::nvlist>(self) }
    }

    pub fn encoded_size(&self, encoding: NvEncoding) -> io::Result<usize>
    {
        let mut l = 0usize;
        let v = unsafe {
            sys::nvlist_size(self.as_ptr() as *mut _, &mut l, encoding.as_raw())
        };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(l)
        }
    }

    pub fn is_empty(&self) -> bool {
        let v = unsafe { sys::nvlist_empty(self.as_ptr() as *mut _) };
        v != sys::boolean::B_FALSE
    }

    pub fn add_boolean<S: CStrArgument>(&mut self, name: S) -> io::Result<()>
    {
        let name = name.into_cstr();
        let v = unsafe { sys::nvlist_add_boolean(self.as_mut_ptr(), name.as_ref().as_ptr()) };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(())
        }
    }

    pub fn first(&self) -> Option<&NvPair> {
        let np = unsafe { sys::nvlist_next_nvpair(self.as_ptr() as *mut _, ptr::null_mut()) };  
        if np.is_null() {
            None
        } else {
            Some(unsafe { NvPair::from_ptr(np) })
        }
    }

    pub fn iter(&self) -> NvListIter {
        NvListIter {
            parent: self,
            pos: ptr::null_mut(),
        }
    }

    pub fn exists<S: CStrArgument>(&self, name: S) -> bool
    {
        let name = name.into_cstr();
        let v = unsafe { sys::nvlist_exists(self.as_ptr() as *mut _, name.as_ref().as_ptr()) };
        v != sys::boolean::B_FALSE
    }

    /* 
    // not allowed because `pair` is borrowed from `self`. Need to fiddle around so that we can
    // check:
    //  - `pair` is from `self`
    //  - `pair` is the only outstanding reference to this pair (need by-value semantics)
    pub fn remove(&mut self, pair: &NvPair) -> io::Result<()>
    {
        let v = unsafe { sys::nvlist_remove_nvpair(self.as_mut_ptr(), pair.as_ptr())};
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(())
        }
    }
    */

    pub fn lookup<S: CStrArgument>(&self, name: S) -> io::Result<&NvPair>
    {
        let name = name.into_cstr();
        let mut n = ptr::null_mut();
        let v = unsafe { sys::nvlist_lookup_nvpair(self.as_ptr() as *mut _, name.as_ref().as_ptr(), &mut n) };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(unsafe { NvPair::from_ptr(n) })
        }
    }

    pub fn try_to_owned(&self) -> io::Result<NvList> {
        let mut n = NvList(ptr::null_mut());
        let v = unsafe { sys::nvlist_dup(self.as_ptr() as *mut _, &mut n.0, 0) };
        if v != 0 {
            Err(io::Error::from_raw_os_error(v))
        } else {
            Ok(n)
        }
    }
}

pub struct NvListIter<'a> {
    parent: &'a NvListRef,
    pos: *mut sys::nvpair, 
}

impl<'a> Iterator for NvListIter<'a> {
    type Item = &'a NvPair;

    fn next(&mut self) -> Option<Self::Item> {
        let np = unsafe { sys::nvlist_next_nvpair(self.parent.as_ptr() as *mut _, self.pos) };  
        self.pos = np;
        if np.is_null() {
            None
        } else {
            Some(unsafe { NvPair::from_ptr(np) })
        }
    }
}

pub struct NvPair(Opaque);
impl ForeignTypeRef for NvPair {
    type CType = sys::nvpair;
}

impl NvPair {
    pub fn name(&self) -> &ffi::CStr
    {
        unsafe { ffi::CStr::from_ptr(sys::nvpair_name(self.as_ptr())) }
    }
}