diff options
| author | metamuffin <metamuffin@disroot.org> | 2025-12-19 21:52:59 +0100 |
|---|---|---|
| committer | metamuffin <metamuffin@disroot.org> | 2025-12-19 21:52:59 +0100 |
| commit | eac0de36221440571fe686074b04b71bf98cf727 (patch) | |
| tree | 76bad4c937e203bc13b6adcced9ed0b41432c2ae /database/src/indices/key.rs | |
| parent | da985cc06e4caa7501222dbf54f212536fd42b0c (diff) | |
| download | jellything-eac0de36221440571fe686074b04b71bf98cf727.tar jellything-eac0de36221440571fe686074b04b71bf98cf727.tar.bz2 jellything-eac0de36221440571fe686074b04b71bf98cf727.tar.zst | |
things
Diffstat (limited to 'database/src/indices/key.rs')
| -rw-r--r-- | database/src/indices/key.rs | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/database/src/indices/key.rs b/database/src/indices/key.rs new file mode 100644 index 0000000..ab56f76 --- /dev/null +++ b/database/src/indices/key.rs @@ -0,0 +1,42 @@ +/* + This file is part of jellything (https://codeberg.org/metamuffin/jellything) + which is licensed under the GNU Affero General Public License (version 3); see /COPYING. + Copyright (C) 2025 metamuffin <metamuffin.org> +*/ + +use crate::{ + backends::WriteTransaction, + indices::Index, + table::{RowNum, Table, TableNum}, +}; +use anyhow::Result; + +pub struct KeyIndex<T> { + id: TableNum, + key: fn(&T) -> &[u8], +} + +impl<T: 'static> KeyIndex<T> { + pub fn new(table: &mut Table<T>, id: TableNum, key: fn(&T) -> &[u8]) -> Self { + table.indices.push(Box::new(Self { id, key })); + Self { id, key } + } + pub fn key(&self, id: RowNum, val: &T) -> Vec<u8> { + let mut v = Vec::new(); + v.extend(self.id.to_be_bytes()); + v.extend((self.key)(val)); + v.extend(id.to_be_bytes()); + v + } +} +impl<T: 'static> Index<T> for KeyIndex<T> { + fn add(&self, db: &mut dyn WriteTransaction, id: RowNum, val: &T) -> Result<()> { + db.set(&self.key(id, val), &[]) + } + fn remove(&self, db: &mut dyn WriteTransaction, id: RowNum, val: &T) -> Result<()> { + db.del(&self.key(id, val)) + } + fn compare(&self, before: &T, after: &T) -> bool { + (self.key)(before) == (self.key)(after) + } +} |