| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | use std::collections::HashMap; |
| 9 | |
| 10 | use hashbrown::HashTable; |
| 11 | use rustc_hash::FxHashSet; |
| 12 | use std::sync::{Arc, RwLock}; |
| 13 | |
| 14 | use super::{NoteMeta, plain_text, preview}; |
| 15 | use crate::matcher; |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | pub(super) const PLAIN_KEPT: usize = 64 << 10; |
| 21 | |
| 22 | pub(super) struct Entry { |
| 23 | |
| 24 | |
| 25 | |
| 26 | text: Box<str>, |
| 27 | |
| 28 | at: [u32; 3], |
| 29 | in_notebook: bool, |
| 30 | |
| 31 | pub plain_cut: bool, |
| 32 | pub created_at: i64, |
| 33 | pub updated_at: i64, |
| 34 | pub trashed_at: Option<i64>, |
| 35 | |
| 36 | |
| 37 | preview: (u32, u32), |
| 38 | |
| 39 | words: Box<[u32]>, |
| 40 | title_words: u32, |
| 41 | } |
| 42 | |
| 43 | impl Entry { |
| 44 | fn new(meta: NoteMeta, plain: &str, plain_cut: bool, preview: &str, title: &[u32], text: &[u32]) -> Self { |
| 45 | |
| 46 | let preview = match plain.find(preview) { |
| 47 | Some(at) => (at as u32, (at + preview.len()) as u32), |
| 48 | None => { |
| 49 | let end = plain.char_indices().nth(super::PREVIEW_CHARS).map_or(plain.len(), |(i, _)| i); |
| 50 | (0, end as u32) |
| 51 | } |
| 52 | }; |
| 53 | let words = title.iter().chain(text).copied().collect(); |
| 54 | let mut entry = Self::packed(&meta, plain); |
| 55 | entry.plain_cut = plain_cut; |
| 56 | entry.preview = preview; |
| 57 | entry.words = words; |
| 58 | entry.title_words = title.len() as u32; |
| 59 | entry |
| 60 | } |
| 61 | |
| 62 | |
| 63 | fn packed(meta: &NoteMeta, plain: &str) -> Self { |
| 64 | let notebook = meta.notebook_id.as_deref().unwrap_or(""); |
| 65 | let mut text = String::with_capacity(meta.id.len() + meta.title.len() + notebook.len() + plain.len()); |
| 66 | let mut at = [0; 3]; |
| 67 | for (i, part) in [&meta.id, &meta.title, notebook, plain].into_iter().enumerate() { |
| 68 | if i > 0 { |
| 69 | at[i - 1] = text.len() as u32; |
| 70 | } |
| 71 | text.push_str(part); |
| 72 | } |
| 73 | Self { |
| 74 | text: text.into_boxed_str(), |
| 75 | at, |
| 76 | in_notebook: meta.notebook_id.is_some(), |
| 77 | plain_cut: false, |
| 78 | created_at: meta.created_at, |
| 79 | updated_at: meta.updated_at, |
| 80 | trashed_at: meta.trashed_at, |
| 81 | preview: (0, 0), |
| 82 | words: Box::new([]), |
| 83 | title_words: 0, |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | pub fn id(&self) -> &str { |
| 88 | &self.text[..self.at[0] as usize] |
| 89 | } |
| 90 | |
| 91 | pub fn title(&self) -> &str { |
| 92 | &self.text[self.at[0] as usize..self.at[1] as usize] |
| 93 | } |
| 94 | |
| 95 | pub fn notebook_id(&self) -> Option<&str> { |
| 96 | self.in_notebook.then(|| &self.text[self.at[1] as usize..self.at[2] as usize]) |
| 97 | } |
| 98 | |
| 99 | pub fn plain(&self) -> &str { |
| 100 | &self.text[self.at[2] as usize..] |
| 101 | } |
| 102 | |
| 103 | pub fn meta(&self) -> NoteMeta { |
| 104 | NoteMeta { |
| 105 | id: self.id().to_owned(), |
| 106 | title: self.title().to_owned(), |
| 107 | created_at: self.created_at, |
| 108 | updated_at: self.updated_at, |
| 109 | notebook_id: self.notebook_id().map(str::to_owned), |
| 110 | trashed_at: self.trashed_at, |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | pub fn preview(&self) -> &str { |
| 115 | &self.plain()[self.preview.0 as usize..self.preview.1 as usize] |
| 116 | } |
| 117 | |
| 118 | pub fn title_words(&self) -> &[u32] { |
| 119 | &self.words[..self.title_words as usize] |
| 120 | } |
| 121 | |
| 122 | pub fn text_words(&self) -> &[u32] { |
| 123 | &self.words[self.title_words as usize..] |
| 124 | } |
| 125 | |
| 126 | fn with_meta(&self, meta: &NoteMeta) -> Self { |
| 127 | Self { |
| 128 | plain_cut: self.plain_cut, |
| 129 | preview: self.preview, |
| 130 | words: self.words.clone(), |
| 131 | title_words: self.title_words, |
| 132 | ..Self::packed(meta, self.plain()) |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | #[derive(Default)] |
| 141 | pub(super) struct Vocab { |
| 142 | |
| 143 | ids: HashTable<u32>, |
| 144 | |
| 145 | |
| 146 | chars: Vec<char>, |
| 147 | ends: Vec<usize>, |
| 148 | |
| 149 | |
| 150 | |
| 151 | pub costs: std::sync::Mutex<Vec<(Box<[char]>, matcher::Options, Arc<Vec<u8>>)>>, |
| 152 | } |
| 153 | |
| 154 | |
| 155 | pub(super) enum Change { |
| 156 | |
| 157 | Note(String), |
| 158 | |
| 159 | NotebookGone(String), |
| 160 | } |
| 161 | |
| 162 | #[derive(Default)] |
| 163 | pub(super) struct Counts { |
| 164 | |
| 165 | pub live: usize, |
| 166 | |
| 167 | pub unfiled: usize, |
| 168 | pub trashed: usize, |
| 169 | |
| 170 | pub notebooks: HashMap<String, usize>, |
| 171 | } |
| 172 | |
| 173 | impl Counts { |
| 174 | fn add(&mut self, e: &Entry, n: isize) { |
| 175 | let bump = |c: &mut usize| *c = c.saturating_add_signed(n); |
| 176 | if e.trashed_at.is_some() { |
| 177 | bump(&mut self.trashed); |
| 178 | return; |
| 179 | } |
| 180 | bump(&mut self.live); |
| 181 | match e.notebook_id() { |
| 182 | None => bump(&mut self.unfiled), |
| 183 | Some(nb) => { |
| 184 | if !self.notebooks.contains_key(nb) { |
| 185 | self.notebooks.insert(nb.to_owned(), 0); |
| 186 | } |
| 187 | let c = self.notebooks.get_mut(nb).unwrap(); |
| 188 | bump(c); |
| 189 | if *c == 0 { |
| 190 | self.notebooks.remove(nb); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | impl Vocab { |
| 198 | pub fn len(&self) -> usize { |
| 199 | self.ends.len() |
| 200 | } |
| 201 | |
| 202 | pub fn word(&self, id: usize) -> &[char] { |
| 203 | word_in(&self.chars, &self.ends, id) |
| 204 | } |
| 205 | |
| 206 | fn id(&self, word: &[char]) -> Option<u32> { |
| 207 | self.ids.find(hash(word), |&id| self.word(id as usize) == word).copied() |
| 208 | } |
| 209 | |
| 210 | fn add(&mut self, word: &[char]) { |
| 211 | if self.id(word).is_none() { |
| 212 | let id = self.ends.len() as u32; |
| 213 | self.chars.extend_from_slice(word); |
| 214 | self.ends.push(self.chars.len()); |
| 215 | let (chars, ends) = (&self.chars, &self.ends); |
| 216 | self.ids.insert_unique(hash(word), id, |&id| hash(word_in(chars, ends, id as usize))); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | |
| 221 | fn shrink(&mut self) { |
| 222 | self.chars.shrink_to_fit(); |
| 223 | self.ends.shrink_to_fit(); |
| 224 | let (chars, ends) = (&self.chars, &self.ends); |
| 225 | self.ids.shrink_to_fit(|&id| hash(word_in(chars, ends, id as usize))); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | |
| 230 | fn word_in<'a>(chars: &'a [char], ends: &[usize], id: usize) -> &'a [char] { |
| 231 | &chars[if id == 0 { 0 } else { ends[id - 1] }..ends[id]] |
| 232 | } |
| 233 | |
| 234 | fn hash<T: std::hash::Hash + ?Sized>(t: &T) -> u64 { |
| 235 | use std::hash::BuildHasher; |
| 236 | rustc_hash::FxBuildHasher.hash_one(t) |
| 237 | } |
| 238 | |
| 239 | |
| 240 | pub(super) struct Prepared(Vec<Ready>); |
| 241 | |
| 242 | |
| 243 | pub(super) fn prepare_one(meta: NoteMeta, body: String) -> Prepared { |
| 244 | let mut prepared = prepare_with(vec![(meta, body)], |rows, f| rows.into_iter().map(f).collect()); |
| 245 | prepared.0.shrink_to_fit(); |
| 246 | prepared |
| 247 | } |
| 248 | |
| 249 | |
| 250 | |
| 251 | pub(super) fn prepare(rows: Vec<(NoteMeta, String)>) -> Prepared { |
| 252 | prepare_with(rows, |rows, f| par_map(rows, f)) |
| 253 | } |
| 254 | |
| 255 | type Row = (NoteMeta, String); |
| 256 | type Ready = (NoteMeta, String, bool, String, Vec<Box<[char]>>, Vec<Box<[char]>>); |
| 257 | |
| 258 | fn prepare_with(rows: Vec<Row>, map: impl FnOnce(Vec<Row>, &(dyn Fn(Row) -> Ready + Sync)) -> Vec<Ready>) -> Prepared { |
| 259 | let words = |text: &str| { |
| 260 | |
| 261 | let distinct: FxHashSet<&str> = matcher::words(text).collect(); |
| 262 | let mut words: Vec<Box<[char]>> = distinct.into_iter().map(matcher::fold_word).collect(); |
| 263 | words.sort_unstable(); |
| 264 | words.dedup(); |
| 265 | words |
| 266 | }; |
| 267 | Prepared(map(rows, &|(meta, body)| { |
| 268 | let mut plain = plain_text(&body); |
| 269 | let (title, text) = (words(&meta.title), words(&plain)); |
| 270 | let plain_cut = plain.len() > PLAIN_KEPT; |
| 271 | if plain_cut { |
| 272 | let mut end = PLAIN_KEPT; |
| 273 | while !plain.is_char_boundary(end) { |
| 274 | end -= 1; |
| 275 | } |
| 276 | plain.truncate(end); |
| 277 | } |
| 278 | (meta, plain, plain_cut, preview(&body), title, text) |
| 279 | })) |
| 280 | } |
| 281 | |
| 282 | #[derive(Default)] |
| 283 | pub(super) struct Directory { |
| 284 | |
| 285 | index: HashTable<u32>, |
| 286 | |
| 287 | |
| 288 | slots: Vec<Option<Arc<Entry>>>, |
| 289 | free: Vec<usize>, |
| 290 | pub counts: Counts, |
| 291 | pub vocab: Arc<RwLock<Vocab>>, |
| 292 | } |
| 293 | |
| 294 | impl Directory { |
| 295 | |
| 296 | |
| 297 | pub fn put_many(&mut self, rows: Vec<(NoteMeta, String)>) { |
| 298 | self.put_prepared(prepare(rows)); |
| 299 | } |
| 300 | |
| 301 | |
| 302 | |
| 303 | pub fn set_meta(&mut self, meta: NoteMeta) { |
| 304 | let entry = match self.remove(&meta.id) { |
| 305 | Some(old) => old.with_meta(&meta), |
| 306 | None => Entry::new(meta, "", false, "", &[], &[]), |
| 307 | }; |
| 308 | self.insert(entry); |
| 309 | } |
| 310 | |
| 311 | pub fn updated_at(&self, id: &str) -> Option<i64> { |
| 312 | self.get(id).map(|e| e.updated_at) |
| 313 | } |
| 314 | |
| 315 | |
| 316 | pub fn put_prepared(&mut self, Prepared(prepared): Prepared) { |
| 317 | |
| 318 | let unknown: Vec<FxHashSet<&[char]>> = { |
| 319 | let vocab = self.vocab.read().unwrap(); |
| 320 | par_chunks(&prepared, |chunk| { |
| 321 | chunk |
| 322 | .iter() |
| 323 | .flat_map(|(_, _, _, _, title, text)| title.iter().chain(text)) |
| 324 | .filter(|w| vocab.id(w).is_none()) |
| 325 | .map(|w| &**w) |
| 326 | .collect() |
| 327 | }) |
| 328 | }; |
| 329 | let mut vocab = self.vocab.write().unwrap(); |
| 330 | for word in unknown.into_iter().flatten() { |
| 331 | vocab.add(word); |
| 332 | } |
| 333 | drop(vocab); |
| 334 | let vocab = self.vocab.read().unwrap(); |
| 335 | let ids_of = |words: Vec<Box<[char]>>| -> Vec<u32> { |
| 336 | let mut ids: Vec<u32> = words.iter().map(|w| vocab.id(w).unwrap()).collect(); |
| 337 | ids.sort_unstable(); |
| 338 | ids |
| 339 | }; |
| 340 | let entries = par_map(prepared, |(meta, plain, plain_cut, preview, title, text)| { |
| 341 | Entry::new(meta, &plain, plain_cut, &preview, &ids_of(title), &ids_of(text)) |
| 342 | }); |
| 343 | drop(vocab); |
| 344 | for entry in entries { |
| 345 | self.remove(entry.id()); |
| 346 | self.insert(entry); |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | fn insert(&mut self, entry: Entry) { |
| 351 | self.counts.add(&entry, 1); |
| 352 | let h = hash(entry.id()); |
| 353 | let entry = Some(Arc::new(entry)); |
| 354 | let slot = match self.free.pop() { |
| 355 | Some(slot) => { |
| 356 | self.slots[slot] = entry; |
| 357 | slot |
| 358 | } |
| 359 | None => { |
| 360 | self.slots.push(entry); |
| 361 | self.slots.len() - 1 |
| 362 | } |
| 363 | }; |
| 364 | let slots = &self.slots; |
| 365 | self.index.insert_unique(h, slot as u32, |&s| hash(slots[s as usize].as_ref().unwrap().id())); |
| 366 | } |
| 367 | |
| 368 | |
| 369 | pub fn shrink(&mut self) { |
| 370 | self.slots.shrink_to_fit(); |
| 371 | self.vocab.write().unwrap().shrink(); |
| 372 | } |
| 373 | |
| 374 | fn slot(&self, id: &str) -> Option<usize> { |
| 375 | let slots = &self.slots; |
| 376 | self.index.find(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).map(|&s| s as usize) |
| 377 | } |
| 378 | |
| 379 | pub fn remove(&mut self, id: &str) -> Option<Arc<Entry>> { |
| 380 | let slots = &self.slots; |
| 381 | let slot = self.index.find_entry(hash(id), |&s| slots[s as usize].as_ref().is_some_and(|e| e.id() == id)).ok()?.remove().0 as usize; |
| 382 | let old = self.slots[slot].take()?; |
| 383 | self.free.push(slot); |
| 384 | self.counts.add(&old, -1); |
| 385 | Some(old) |
| 386 | } |
| 387 | |
| 388 | pub fn get(&self, id: &str) -> Option<&Arc<Entry>> { |
| 389 | self.slots[self.slot(id)?].as_ref() |
| 390 | } |
| 391 | |
| 392 | |
| 393 | pub fn slots(&self) -> &[Option<Arc<Entry>>] { |
| 394 | &self.slots |
| 395 | } |
| 396 | |
| 397 | pub fn entries(&self) -> impl Iterator<Item = &Arc<Entry>> { |
| 398 | self.slots.iter().flatten() |
| 399 | } |
| 400 | |
| 401 | pub fn unfile(&mut self, notebook_id: &str) { |
| 402 | let ids: Vec<String> = self |
| 403 | .entries() |
| 404 | .filter(|e| e.notebook_id() == Some(notebook_id)) |
| 405 | .map(|e| e.id().to_owned()) |
| 406 | .collect(); |
| 407 | for id in ids { |
| 408 | let old = self.remove(&id).unwrap(); |
| 409 | let mut meta = old.meta(); |
| 410 | meta.notebook_id = None; |
| 411 | self.insert(old.with_meta(&meta)); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | |
| 416 | pub fn live(&self) -> Vec<Arc<Entry>> { |
| 417 | self.entries().filter(|e| e.trashed_at.is_none()).cloned().collect() |
| 418 | } |
| 419 | } |
| 420 | |
| 421 | |
| 422 | |
| 423 | fn par_map<T: Send, U: Send>(items: Vec<T>, f: impl Fn(T) -> U + Sync) -> Vec<U> { |
| 424 | let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len().max(1)); |
| 425 | let n = items.len(); |
| 426 | let items: Vec<std::sync::Mutex<Option<T>>> = items.into_iter().map(|t| std::sync::Mutex::new(Some(t))).collect(); |
| 427 | let next = std::sync::atomic::AtomicUsize::new(0); |
| 428 | let (items, next, f) = (&items, &next, &f); |
| 429 | let mut done: Vec<(usize, U)> = std::thread::scope(|scope| { |
| 430 | let handles: Vec<_> = (0..threads) |
| 431 | .map(|_| { |
| 432 | scope.spawn(move || { |
| 433 | let mut out = Vec::new(); |
| 434 | loop { |
| 435 | |
| 436 | let start = next.fetch_add(64, std::sync::atomic::Ordering::Relaxed); |
| 437 | if start >= n { |
| 438 | return out; |
| 439 | } |
| 440 | for (i, item) in items.iter().enumerate().skip(start).take(64) { |
| 441 | out.push((i, f(item.lock().unwrap().take().unwrap()))); |
| 442 | } |
| 443 | } |
| 444 | }) |
| 445 | }) |
| 446 | .collect(); |
| 447 | handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() |
| 448 | }); |
| 449 | done.sort_unstable_by_key(|(i, _)| *i); |
| 450 | done.into_iter().map(|(_, u)| u).collect() |
| 451 | } |
| 452 | |
| 453 | |
| 454 | fn par_chunks<'a, T: Sync, U: Send>(items: &'a [T], f: impl Fn(&'a [T]) -> U + Sync) -> Vec<U> { |
| 455 | let threads = std::thread::available_parallelism().map_or(1, |n| n.get()); |
| 456 | let f = &f; |
| 457 | std::thread::scope(|scope| { |
| 458 | let handles: Vec<_> = items.chunks(items.len().div_ceil(threads).max(1)).map(|chunk| scope.spawn(move || f(chunk))).collect(); |
| 459 | handles.into_iter().map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect() |
| 460 | }) |
| 461 | } |