diff options
Diffstat (limited to 'database/src/indices/order.rs')
| -rw-r--r-- | database/src/indices/order.rs | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/database/src/indices/order.rs b/database/src/indices/order.rs new file mode 100644 index 0000000..852342d --- /dev/null +++ b/database/src/indices/order.rs @@ -0,0 +1,49 @@ +/* + 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::{Table, backends::KV, indices::Index}; +use anyhow::Result; +use std::sync::Arc; + +pub struct OrderIndex<T> { + id: u32, + value: fn(&T) -> [u8; 8], + db: Arc<dyn KV>, +} +impl<T: 'static> OrderIndex<T> { + pub fn new(table: &mut Table<T>, id: u32, value: fn(&T) -> [u8; 8]) -> Self { + table.indices.push(Box::new(Self { + id, + value, + db: table.db.clone(), + })); + Self { + id, + value, + db: table.db.clone(), + } + } + fn key(&self, id: u64, val: &T) -> Vec<u8> { + let mut key = Vec::new(); + key.extend(self.id.to_be_bytes()); + key.extend((self.value)(val)); + key.extend(id.to_be_bytes()); + key + } +} +impl<T: 'static> Index<T> for OrderIndex<T> { + fn add(&self, db: &dyn KV, id: u64, val: &T) -> Result<()> { + db.set(&self.key(id, val), &[])?; + Ok(()) + } + fn remove(&self, db: &dyn KV, id: u64, val: &T) -> Result<()> { + db.del(&self.key(id, val))?; + Ok(()) + } + fn compare(&self, before: &T, after: &T) -> bool { + (self.value)(before) == (self.value)(after) + } +} |