aboutsummaryrefslogtreecommitdiff
path: root/database/src/indices
diff options
context:
space:
mode:
Diffstat (limited to 'database/src/indices')
-rw-r--r--database/src/indices/mod.rs19
-rw-r--r--database/src/indices/order.rs49
2 files changed, 68 insertions, 0 deletions
diff --git a/database/src/indices/mod.rs b/database/src/indices/mod.rs
new file mode 100644
index 0000000..48e91a9
--- /dev/null
+++ b/database/src/indices/mod.rs
@@ -0,0 +1,19 @@
+/*
+ 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::KV;
+use anyhow::Result;
+
+pub mod order;
+
+pub trait Index<T> {
+ fn add(&self, db: &dyn KV, id: u64, val: &T) -> Result<()>;
+ fn remove(&self, db: &dyn KV, id: u64, val: &T) -> Result<()>;
+ fn compare(&self, before: &T, after: &T) -> bool {
+ let _ = (before, after);
+ true
+ }
+}
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)
+ }
+}