Skip to main content

faiss_next/
idx.rs

1use std::fmt;
2
3pub type IdxRepr = i64;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
6pub struct Idx(pub IdxRepr);
7
8impl Idx {
9    pub const NONE: Self = Idx(-1);
10
11    #[inline]
12    pub fn new(idx: u64) -> Self {
13        Idx(idx as IdxRepr)
14    }
15
16    #[inline]
17    pub fn is_none(self) -> bool {
18        self.0 < 0
19    }
20
21    #[inline]
22    pub fn is_some(self) -> bool {
23        self.0 >= 0
24    }
25
26    #[inline]
27    pub fn get(self) -> Option<u64> {
28        if self.0 < 0 {
29            None
30        } else {
31            Some(self.0 as u64)
32        }
33    }
34
35    #[inline]
36    pub fn get_unchecked(self) -> u64 {
37        self.0 as u64
38    }
39
40    #[inline]
41    pub fn as_repr(self) -> IdxRepr {
42        self.0
43    }
44}
45
46impl Default for Idx {
47    fn default() -> Self {
48        Self::NONE
49    }
50}
51
52impl From<u64> for Idx {
53    fn from(idx: u64) -> Self {
54        Self::new(idx)
55    }
56}
57
58impl From<Option<u64>> for Idx {
59    fn from(opt: Option<u64>) -> Self {
60        match opt {
61            Some(idx) => Self::new(idx),
62            None => Self::NONE,
63        }
64    }
65}
66
67impl From<Idx> for Option<u64> {
68    fn from(idx: Idx) -> Self {
69        idx.get()
70    }
71}
72
73impl fmt::Display for Idx {
74    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75        match self.get() {
76            Some(idx) => write!(f, "Idx({})", idx),
77            None => write!(f, "Idx(None)"),
78        }
79    }
80}