redb_bincode/
tx.rs

1use std::marker::PhantomData;
2
3use redb::TableError;
4
5use super::{ReadOnlyTable, Table};
6use crate::sort;
7
8pub struct ReadTransaction(redb::ReadTransaction);
9
10impl From<redb::ReadTransaction> for ReadTransaction {
11    fn from(value: redb::ReadTransaction) -> Self {
12        Self(value)
13    }
14}
15
16impl ReadTransaction {
17    pub fn as_raw(&self) -> &redb::ReadTransaction {
18        &self.0
19    }
20    pub fn open_table<K, V>(
21        &self,
22        table_def: &TableDefinition<'_, K, V>,
23    ) -> Result<ReadOnlyTable<K, V, sort::Lexicographical>, TableError>
24    where
25        K: bincode::Encode + bincode::Decode<()>,
26        V: bincode::Encode + bincode::Decode<()>,
27    {
28        Ok(ReadOnlyTable {
29            inner: self
30                .0
31                .open_table(redb::TableDefinition::new(table_def.name))?,
32            _k: PhantomData,
33            _v: PhantomData,
34        })
35    }
36}
37
38pub struct WriteTransaction(redb::WriteTransaction);
39
40impl From<redb::WriteTransaction> for WriteTransaction {
41    fn from(value: redb::WriteTransaction) -> Self {
42        Self(value)
43    }
44}
45
46pub struct TableDefinition<'a, K, V> {
47    name: &'a str,
48    _key_type: PhantomData<K>,
49    _value_type: PhantomData<V>,
50}
51
52impl<'a, K, V> TableDefinition<'a, K, V> {
53    pub const fn new(name: &'a str) -> Self {
54        Self {
55            name,
56            _key_type: PhantomData,
57            _value_type: PhantomData,
58        }
59    }
60
61    pub fn as_raw(&self) -> redb::TableDefinition<'_, &'static [u8], &'static [u8]> {
62        redb::TableDefinition::new(self.name)
63    }
64}
65
66impl WriteTransaction {
67    pub fn as_raw(&self) -> &redb::WriteTransaction {
68        &self.0
69    }
70
71    pub fn open_table<K, V>(
72        &self,
73        table_def: &TableDefinition<'_, K, V>,
74    ) -> Result<Table<K, V, sort::Lexicographical>, TableError>
75    where
76        K: bincode::Encode + bincode::Decode<()>,
77        V: bincode::Encode + bincode::Decode<()>,
78    {
79        Ok(Table {
80            inner: self
81                .0
82                .open_table(redb::TableDefinition::new(table_def.name))?,
83            _k: PhantomData,
84            _v: PhantomData,
85        })
86    }
87
88    pub fn commit(self) -> Result<(), redb::CommitError> {
89        self.0.commit()
90    }
91}