-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathnode.rs
194 lines (167 loc) · 5.96 KB
/
node.rs
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
use std::borrow::Cow;
use std::fmt;
use std::mem::size_of;
use bytemuck::{bytes_of, cast_slice, pod_read_unaligned};
use byteorder::{ByteOrder, NativeEndian};
use heed::{BoxedError, BytesDecode, BytesEncode};
use roaring::RoaringBitmap;
use crate::distance::Distance;
use crate::unaligned_vector::UnalignedVector;
use crate::{ItemId, NodeId};
#[derive(Clone, Debug)]
pub enum Node<'a, D: Distance> {
Leaf(Leaf<'a, D>),
Descendants(Descendants<'a>),
SplitPlaneNormal(SplitPlaneNormal<'a, D>),
}
pub const LEAF_TAG: u8 = 0;
pub const DESCENDANTS_TAG: u8 = 1;
pub const SPLIT_PLANE_NORMAL_TAG: u8 = 2;
impl<'a, D: Distance> Node<'a, D> {
pub fn leaf(self) -> Option<Leaf<'a, D>> {
if let Node::Leaf(leaf) = self {
Some(leaf)
} else {
None
}
}
}
/// A leaf node which corresponds to the vector inputed
/// by the user and the distance header.
pub struct Leaf<'a, D: Distance> {
/// The header of this leaf.
pub header: D::Header,
/// The vector of this leaf.
pub vector: Cow<'a, UnalignedVector<D::VectorCodec>>,
}
impl<D: Distance> fmt::Debug for Leaf<'_, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Leaf").field("header", &self.header).field("vector", &self.vector).finish()
}
}
impl<D: Distance> Clone for Leaf<'_, D> {
fn clone(&self) -> Self {
Self { header: self.header, vector: self.vector.clone() }
}
}
impl<D: Distance> Leaf<'_, D> {
/// Converts the leaf into an owned version of itself by cloning
/// the internal vector. Doing so will make it mutable.
pub fn into_owned(self) -> Leaf<'static, D> {
Leaf { header: self.header, vector: Cow::Owned(self.vector.into_owned()) }
}
}
#[derive(Clone)]
pub struct Descendants<'a> {
// A descendants node can only contains references to the leaf nodes.
// We can get and store their ids directly without the `Mode`.
pub descendants: Cow<'a, RoaringBitmap>,
}
impl fmt::Debug for Descendants<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let descendants = self.descendants.iter().collect::<Vec<_>>();
f.debug_struct("Descendants").field("descendants", &descendants).finish()
}
}
#[derive(Clone)]
pub struct ItemIds<'a> {
bytes: &'a [u8],
}
impl<'a> ItemIds<'a> {
pub fn from_slice(slice: &[u32]) -> ItemIds<'_> {
ItemIds::from_bytes(cast_slice(slice))
}
pub fn from_bytes(bytes: &[u8]) -> ItemIds<'_> {
ItemIds { bytes }
}
pub fn raw_bytes(&self) -> &[u8] {
self.bytes
}
pub fn len(&self) -> usize {
self.bytes.len() / size_of::<ItemId>()
}
pub fn iter(&self) -> impl Iterator<Item = ItemId> + 'a {
self.bytes.chunks_exact(size_of::<ItemId>()).map(NativeEndian::read_u32)
}
}
impl fmt::Debug for ItemIds<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
self.iter().for_each(|integer| {
list.entry(&integer);
});
list.finish()
}
}
pub struct SplitPlaneNormal<'a, D: Distance> {
pub left: NodeId,
pub right: NodeId,
pub normal: Cow<'a, UnalignedVector<D::VectorCodec>>,
}
impl<D: Distance> fmt::Debug for SplitPlaneNormal<'_, D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let name = format!("SplitPlaneNormal<{}>", D::name());
f.debug_struct(&name)
.field("left", &self.left)
.field("right", &self.right)
.field("normal", &self.normal)
.finish()
}
}
impl<D: Distance> Clone for SplitPlaneNormal<'_, D> {
fn clone(&self) -> Self {
Self { left: self.left, right: self.right, normal: self.normal.clone() }
}
}
/// The codec used internally to encode and decode nodes.
pub struct NodeCodec<D>(D);
impl<'a, D: Distance> BytesEncode<'a> for NodeCodec<D> {
type EItem = Node<'a, D>;
fn bytes_encode(item: &Self::EItem) -> Result<Cow<'a, [u8]>, BoxedError> {
let mut bytes = Vec::new();
match item {
Node::Leaf(Leaf { header, vector }) => {
bytes.push(LEAF_TAG);
bytes.extend_from_slice(bytes_of(header));
bytes.extend_from_slice(vector.as_bytes());
}
Node::SplitPlaneNormal(SplitPlaneNormal { normal, left, right }) => {
bytes.push(SPLIT_PLANE_NORMAL_TAG);
bytes.extend_from_slice(&left.to_bytes());
bytes.extend_from_slice(&right.to_bytes());
bytes.extend_from_slice(normal.as_bytes());
}
Node::Descendants(Descendants { descendants }) => {
bytes.push(DESCENDANTS_TAG);
descendants.serialize_into(&mut bytes)?;
}
}
Ok(Cow::Owned(bytes))
}
}
impl<'a, D: Distance> BytesDecode<'a> for NodeCodec<D> {
type DItem = Node<'a, D>;
fn bytes_decode(bytes: &'a [u8]) -> Result<Self::DItem, BoxedError> {
match bytes {
[LEAF_TAG, bytes @ ..] => {
let (header_bytes, remaining) = bytes.split_at(size_of::<D::Header>());
let header = pod_read_unaligned(header_bytes);
let vector = UnalignedVector::<D::VectorCodec>::from_bytes(remaining)?;
Ok(Node::Leaf(Leaf { header, vector }))
}
[SPLIT_PLANE_NORMAL_TAG, bytes @ ..] => {
let (left, bytes) = NodeId::from_bytes(bytes);
let (right, bytes) = NodeId::from_bytes(bytes);
Ok(Node::SplitPlaneNormal(SplitPlaneNormal {
normal: UnalignedVector::<D::VectorCodec>::from_bytes(bytes)?,
left,
right,
}))
}
[DESCENDANTS_TAG, bytes @ ..] => Ok(Node::Descendants(Descendants {
descendants: Cow::Owned(RoaringBitmap::deserialize_from(bytes)?),
})),
unknown => panic!("What the fuck is an {unknown:?}"),
}
}
}