1use crate::{
2    Transaction,
3    database::DatabaseKind,
4    error::{Result, mdbx_result},
5    flags::c_enum,
6    transaction::{TransactionKind, txn_execute},
7};
8use libc::c_uint;
9use std::{ffi::CString, marker::PhantomData, ptr};
10
11#[derive(Debug)]
15pub struct Table<'txn> {
16    dbi: ffi::MDBX_dbi,
17    _marker: PhantomData<&'txn ()>,
18}
19
20impl<'txn> Table<'txn> {
21    pub(crate) fn new<'db, K: TransactionKind, E: DatabaseKind>(
22        txn: &'txn Transaction<'db, K, E>,
23        name: Option<&str>,
24        flags: c_uint,
25    ) -> Result<Self> {
26        let c_name = name.map(|n| CString::new(n).unwrap());
27        let name_ptr = if let Some(c_name) = &c_name {
28            c_name.as_ptr()
29        } else {
30            ptr::null()
31        };
32        let mut dbi: ffi::MDBX_dbi = 0;
33        mdbx_result(txn_execute(&txn.txn_mutex(), |txn| unsafe {
34            ffi::mdbx_dbi_open(txn, name_ptr, c_enum(flags), &mut dbi)
35        }))?;
36        Ok(Self::new_from_ptr(dbi))
37    }
38
39    pub(crate) fn new_from_ptr(dbi: ffi::MDBX_dbi) -> Self {
40        Self {
41            dbi,
42            _marker: PhantomData,
43        }
44    }
45
46    pub(crate) fn freelist_table() -> Self {
47        Table {
48            dbi: 0,
49            _marker: PhantomData,
50        }
51    }
52
53    pub fn dbi(&self) -> ffi::MDBX_dbi {
58        self.dbi
59    }
60}