1use std::io::Read;
2use std::path::Path;
3
4use flate2::read::ZlibDecoder;
5use fst::Map;
6use memmap2::Mmap;
7use roaring::RoaringBitmap;
8
9use super::format::{HEADER_SIZE, MAGIC, Meta, SECTION_HEADER_SIZE, SectionKind, VERSION};
10use crate::doc::Document;
11use crate::error::GeocoderError;
12use crate::types::{DocId, TokenId};
13
14pub struct Index {
22 mmap: Mmap,
23 ranges: Vec<(usize, usize)>,
24 pub meta: Meta,
25 token_fst: Map<Vec<u8>>,
26 ngram_fst: Map<Vec<u8>>,
27 geohash_fst: Map<Vec<u8>>,
28 filter_fst: Map<Vec<u8>>,
29}
30
31impl Index {
32 pub fn open(path: &Path) -> Result<Self, GeocoderError> {
33 let file = std::fs::File::open(path)?;
34 let mmap = unsafe { Mmap::map(&file)? };
36 let data: &[u8] = &mmap;
37 if data.len() < HEADER_SIZE || &data[..8] != MAGIC {
38 return Err(GeocoderError::InvalidIndex("bad magic bytes"));
39 }
40 if u32::from_le_bytes(data[8..12].try_into().unwrap()) != VERSION {
41 return Err(GeocoderError::InvalidIndex(
42 "unsupported format version, rebuild the index",
43 ));
44 }
45 let count = u32::from_le_bytes(data[12..16].try_into().unwrap()) as usize;
46 let mut ranges = vec![(0usize, 0usize); SectionKind::ALL.len()];
47 let mut found = vec![false; SectionKind::ALL.len()];
48 for i in 0..count {
49 let at = HEADER_SIZE + i * SECTION_HEADER_SIZE;
50 let header = data
51 .get(at..at + SECTION_HEADER_SIZE)
52 .ok_or(GeocoderError::InvalidIndex("truncated"))?;
53 let Ok(kind) = SectionKind::try_from(header[0]) else {
54 continue;
55 };
56 let offset = u64::from_le_bytes(header[1..9].try_into().unwrap());
57 let length = u64::from_le_bytes(header[9..17].try_into().unwrap());
58 let end = offset
59 .checked_add(length)
60 .filter(|&end| end <= data.len() as u64)
61 .ok_or(GeocoderError::InvalidIndex("truncated"))?;
62 ranges[kind as usize] = (offset as usize, end as usize);
63 found[kind as usize] = true;
64 }
65 if found.iter().any(|f| !f) {
66 return Err(GeocoderError::InvalidIndex("missing section"));
67 }
68 let section = |kind: SectionKind| {
69 let (start, end) = ranges[kind as usize];
70 &data[start..end]
71 };
72 let meta: Meta = serde_json::from_slice(section(SectionKind::Meta))?;
73 let fst = |kind: SectionKind| -> Result<Map<Vec<u8>>, GeocoderError> {
76 let map = Map::new(section(kind).to_vec())?;
77 map.as_fst().verify()?;
78 Ok(map)
79 };
80 let token_fst = fst(SectionKind::TokenFst)?;
81 let ngram_fst = fst(SectionKind::NgramFst)?;
82 let geohash_fst = fst(SectionKind::GeohashFst)?;
83 let filter_fst = fst(SectionKind::FilterFst)?;
84 Ok(Self {
85 mmap,
86 ranges,
87 meta,
88 token_fst,
89 ngram_fst,
90 geohash_fst,
91 filter_fst,
92 })
93 }
94
95 fn section(&self, kind: SectionKind) -> &[u8] {
96 let (start, end) = self.ranges[kind as usize];
97 &self.mmap[start..end]
98 }
99
100 fn offset(&self, kind: SectionKind, i: usize) -> Option<(usize, usize)> {
102 let table = self.section(kind);
103 let at = i.checked_mul(8)?;
104 let start = u64::from_le_bytes(table.get(at..at.checked_add(8)?)?.try_into().ok()?);
105 let end = u64::from_le_bytes(table.get(at + 8..at.checked_add(16)?)?.try_into().ok()?);
106 (start <= end).then_some((usize::try_from(start).ok()?, usize::try_from(end).ok()?))
107 }
108
109 fn slice(&self, kind: SectionKind, range: Option<(usize, usize)>, width: usize) -> &[u8] {
111 range
112 .and_then(|(start, end)| {
113 let (start, end) = (start.checked_mul(width)?, end.checked_mul(width)?);
114 self.section(kind).get(start..end)
115 })
116 .unwrap_or_default()
117 }
118
119 pub fn token_id(&self, token: &str) -> Option<TokenId> {
120 self.token_fst.get(token).map(|v| v as TokenId)
121 }
122
123 pub fn token_fst(&self) -> &Map<Vec<u8>> {
124 &self.token_fst
125 }
126
127 pub fn frequency(&self, token: TokenId) -> usize {
129 self.offset(SectionKind::PostingOffsets, token as usize)
130 .map(|(s, e)| e - s)
131 .unwrap_or(0)
132 }
133
134 pub fn postings(&self, token: TokenId) -> Postings<'_> {
136 let range = self.offset(SectionKind::PostingOffsets, token as usize);
137 Postings {
138 bytes: self.slice(SectionKind::PostingsByDoc, range, 8),
139 }
140 }
141
142 pub fn top(&self, token: TokenId, limit: usize) -> impl Iterator<Item = DocId> + '_ {
144 let range = self.offset(SectionKind::PostingOffsets, token as usize);
145 self.slice(SectionKind::PostingsByScore, range, 4)
146 .as_chunks::<4>()
147 .0
148 .iter()
149 .take(limit)
150 .map(|c| u32::from_le_bytes(*c))
151 }
152
153 pub fn pairs(&self, token: TokenId) -> RoaringBitmap {
155 let range = self.offset(SectionKind::PairOffsets, token as usize);
156 bitmap(self.slice(SectionKind::PairBlobs, range, 1))
157 }
158
159 pub fn edge_ngram(&self, prefix: &str) -> RoaringBitmap {
161 self.keyed(
162 &self.ngram_fst,
163 prefix,
164 SectionKind::NgramOffsets,
165 SectionKind::NgramBlobs,
166 )
167 }
168
169 pub fn geohash(&self, cell: &str) -> RoaringBitmap {
170 self.keyed(
171 &self.geohash_fst,
172 cell,
173 SectionKind::GeohashOffsets,
174 SectionKind::GeohashBlobs,
175 )
176 }
177
178 pub fn filter(&self, key: &str, value: &str) -> RoaringBitmap {
180 let k = format!("{key}|{value}");
181 self.keyed(
182 &self.filter_fst,
183 &k,
184 SectionKind::FilterOffsets,
185 SectionKind::FilterBlobs,
186 )
187 }
188
189 fn keyed(
190 &self,
191 fst: &Map<Vec<u8>>,
192 key: &str,
193 offsets: SectionKind,
194 blobs: SectionKind,
195 ) -> RoaringBitmap {
196 let range = fst.get(key).and_then(|i| self.offset(offsets, i as usize));
197 bitmap(self.slice(blobs, range, 1))
198 }
199
200 pub fn document(&self, doc: DocId) -> Option<Document> {
201 let range = self.offset(SectionKind::DocOffsets, doc as usize)?;
202 let blob = self.slice(SectionKind::DocBlobs, Some(range), 1);
203 let mut json = Vec::new();
205 ZlibDecoder::new(blob)
206 .take(MAX_DOCUMENT_BYTES + 1)
207 .read_to_end(&mut json)
208 .ok()?;
209 if json.len() as u64 > MAX_DOCUMENT_BYTES {
210 return None;
211 }
212 serde_json::from_slice(&json).ok()
213 }
214}
215
216const MAX_DOCUMENT_BYTES: u64 = 16 << 20;
219
220fn bitmap(bytes: &[u8]) -> RoaringBitmap {
222 RoaringBitmap::deserialize_from(bytes).unwrap_or_default()
223}
224
225#[derive(Clone, Copy)]
227pub struct Postings<'a> {
228 bytes: &'a [u8],
229}
230
231impl<'a> Postings<'a> {
232 pub fn len(&self) -> usize {
233 self.bytes.len() / 8
234 }
235
236 pub fn is_empty(&self) -> bool {
237 self.bytes.is_empty()
238 }
239
240 pub fn get(&self, i: usize) -> (DocId, f32) {
241 let at = i * 8;
242 let doc = u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap());
243 let boost = f32::from_le_bytes(self.bytes[at + 4..at + 8].try_into().unwrap());
244 (doc, boost)
245 }
246
247 pub fn iter(&self) -> impl Iterator<Item = (DocId, f32)> + 'a {
248 let bytes = self.bytes;
249 bytes.as_chunks::<8>().0.iter().map(|c| {
250 (
251 u32::from_le_bytes([c[0], c[1], c[2], c[3]]),
252 f32::from_le_bytes([c[4], c[5], c[6], c[7]]),
253 )
254 })
255 }
256
257 pub fn find(&self, doc: DocId) -> Option<f32> {
259 let (mut lo, mut hi) = (0, self.len());
260 while lo < hi {
261 let mid = (lo + hi) / 2;
262 let (d, boost) = self.get(mid);
263 match d.cmp(&doc) {
264 std::cmp::Ordering::Equal => return Some(boost),
265 std::cmp::Ordering::Less => lo = mid + 1,
266 std::cmp::Ordering::Greater => hi = mid,
267 }
268 }
269 None
270 }
271}