Skip to main content

index_list/
listindex.rs

1//! Definition of the ListIndex type
2//! 
3use core::{convert::TryFrom, default::Default, fmt, num::NonZeroU32};
4
5/// Vector index for the elements in the list. They are typically not
6/// squential.
7#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
8pub struct ListIndex {
9    ndx: Option<NonZeroU32>
10}
11
12impl ListIndex {
13    #[inline]
14    pub fn new() -> ListIndex {
15        Default::default()
16    }
17    #[inline]
18    /// Returns `true` for a valid index.
19    ///
20    /// A valid index can be used in IndexList method calls.
21    pub fn is_some(&self) -> bool {
22        self.ndx.is_some()
23    }
24    #[inline]
25    /// Returns `true` for an invalid index.
26    ///
27    /// An invalid index will always be ignored and have `None` returned from
28    /// any IndexList method call that returns something.
29    pub fn is_none(&self) -> bool {
30        self.ndx.is_none()
31    }
32    #[inline]
33    pub(crate) fn get(&self) -> Option<usize> {
34        Some(self.ndx?.get() as usize - 1)
35    }
36    #[inline]
37    pub(crate) fn set(mut self, index: Option<usize>) -> Self {
38        if let Some(n) = index {
39            self.ndx = NonZeroU32::try_from(n as u32 + 1).ok()
40        }
41        self
42    }
43}
44
45impl From<u32> for ListIndex {
46    fn from(index: u32) -> ListIndex {
47        ListIndex::new().set(Some(index as usize))
48    }
49}
50
51impl From<u64> for ListIndex {
52    fn from(index: u64) -> ListIndex {
53        ListIndex::new().set(Some(index as usize))
54    }
55}
56
57impl From<usize> for ListIndex {
58    fn from(index: usize) -> ListIndex {
59        ListIndex::new().set(Some(index))
60    }
61}
62
63impl From<Option<usize>> for ListIndex {
64    fn from(index: Option<usize>) -> ListIndex {
65        ListIndex::new().set(index)
66    }
67}
68
69impl fmt::Display for ListIndex {
70    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71        if let Some(ndx) = self.ndx {
72            write!(f, "{}", ndx)
73        } else {
74            write!(f, "|")
75        }
76    }
77}