use std::os::unix::ffi::OsStrExt;
use super::WordList as WordListCStr;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WordList<'p, 'l: 'p>(&'p WordListCStr<'l>);
impl<'p, 'l: 'p> From<&'p WordListCStr<'l>> for WordList<'p, 'l> {
fn from(word_list: &'p WordListCStr<'l>) -> Self {
WordList(word_list)
}
}
impl<'p, 'l: 'p> std::ops::Index<usize> for WordList<'p, 'l> {
type Output = std::path::Path;
fn index(&self, index: usize) -> &'p Self::Output {
std::ffi::OsStr::from_bytes(self.0[index].to_bytes()).as_ref()
}
}
impl<'p, 'l: 'p> WordList<'p, 'l> {
pub fn new(list: &'p WordListCStr<'l>) -> WordList<'p, 'l> {
list.into()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn get(&self, index: usize) -> Option<&<Self as std::ops::Index<usize>>::Output> {
if index < self.len() {
Some(&self[index])
} else {
None
}
}
pub unsafe fn get_unchecked(&self, index: usize) -> &<Self as std::ops::Index<usize>>::Output {
let element = self.0.get_unchecked(index);
std::ffi::OsStr::from_bytes(element.to_bytes()).as_ref()
}
}
pub struct Iter<'r, 'p: 'r, 'l: 'p> {
word_list: &'r WordList<'p, 'l>,
index: usize,
}
impl<'r, 'p: 'r, 'l: 'p> IntoIterator for &'r WordList<'p, 'l> {
type IntoIter = Iter<'r, 'p, 'l>;
type Item = <Self::IntoIter as Iterator>::Item;
fn into_iter(self) -> Self::IntoIter {
Iter {
word_list: self,
index: 0,
}
}
}
impl<'r, 'p: 'r, 'l: 'p> Iterator for Iter<'r, 'p, 'l> {
type Item = &'r <WordList<'p, 'l> as std::ops::Index<usize>>::Output;
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.word_list.len() {
None
} else {
let result = &self.word_list[self.index];
self.index += 1;
Some(result)
}
}
}