use super::*;
pub struct StringList {
inner: NonNull<bindings::nixl_capi_string_list_s>,
}
impl StringList {
pub(crate) fn new(inner: NonNull<bindings::nixl_capi_string_list_s>) -> Self {
Self { inner }
}
pub fn len(&self) -> Result<usize, NixlError> {
let mut size = 0;
let status = unsafe { nixl_capi_string_list_size(self.inner.as_ptr(), &mut size) };
match status {
0 => Ok(size),
-1 => Err(NixlError::InvalidParam),
_ => Err(NixlError::BackendError),
}
}
pub fn is_empty(&self) -> Result<bool, NixlError> {
Ok(self.len()? == 0)
}
pub fn get(&self, index: usize) -> Result<&str, NixlError> {
let mut str_ptr = ptr::null();
let status = unsafe { nixl_capi_string_list_get(self.inner.as_ptr(), index, &mut str_ptr) };
match status {
0 => {
let c_str = unsafe { CStr::from_ptr(str_ptr) };
Ok(c_str.to_str().unwrap()) }
-1 => Err(NixlError::InvalidParam),
_ => Err(NixlError::BackendError),
}
}
pub fn iter(&self) -> StringListIterator<'_> {
StringListIterator {
list: self,
index: 0,
length: self.len().unwrap_or(0),
}
}
}
impl Drop for StringList {
fn drop(&mut self) {
unsafe {
nixl_capi_destroy_string_list(self.inner.as_ptr());
}
}
}
pub struct StringListIterator<'a> {
list: &'a StringList,
index: usize,
length: usize,
}
impl<'a> Iterator for StringListIterator<'a> {
type Item = Result<&'a str, NixlError>;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.length {
None
} else {
let result = self.list.get(self.index);
self.index += 1;
Some(result)
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.length - self.index;
(remaining, Some(remaining))
}
}