signet-libmdbx 0.8.1

Idiomatic and safe MDBX wrapper
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! Shared low-level FFI operations for transactions.
//!
//! This module contains `#[inline(always)]` functions that wrap raw MDBX FFI
//! calls. These functions take raw `*mut ffi::MDBX_txn` pointers and are
//! designed to be called from [`TxAccess::with_txn_ptr`].
//!
//! # Safety
//!
//!  - All functions require the caller to ensure the provided transaction
//!    pointer is BOTH **Valid** and **Exclusive**.
//!
//! MDBX's transaction model requires that a transaction pointer is only used
//! by a single thread at a time. Therefore, callers must ensure that no
//! other code is concurrently accessing the same transaction pointer while
//! these functions are being called.
//!
//! Failure to uphold these safety guarantees may lead to undefined behavior,
//! data corruption, crashes, or other serious issues.
//!
//! [`TxAccess::with_txn_ptr`]: crate::tx::access::TxPtrAccess::with_txn_ptr

use crate::{
    Stat,
    error::{MdbxResult, mdbx_result},
    flags::{DatabaseFlags, WriteFlags},
};
use std::{
    ffi::{c_char, c_uint, c_void},
    mem::size_of,
    ptr, slice,
};

/// Performs a raw `mdbx_get` operation.
///
/// Returns the data value if found, `None` if not found.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
/// - `key` must be a valid slice.
#[inline(always)]
pub(crate) unsafe fn get_raw(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    key: &[u8],
) -> MdbxResult<Option<ffi::MDBX_val>> {
    let key_val = ffi::MDBX_val { iov_len: key.len(), iov_base: key.as_ptr() as *mut c_void };
    let mut data_val = ffi::MDBX_val { iov_len: 0, iov_base: ptr::null_mut() };

    // SAFETY: Caller guarantees txn and dbi are valid.
    match unsafe { ffi::mdbx_get(txn, dbi, &key_val, &mut data_val) } {
        ffi::MDBX_SUCCESS => Ok(Some(data_val)),
        ffi::MDBX_NOTFOUND => Ok(None),
        err_code => Err(crate::MdbxError::from_err_code(err_code)),
    }
}

/// Opens a database and retrieves its flags.
///
/// Returns `(dbi, flags)` on success.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `name_ptr` must be a valid C string pointer or null for the default DB.
#[inline(always)]
pub(crate) unsafe fn open_db_raw(
    txn: *mut ffi::MDBX_txn,
    name_ptr: *const c_char,
    flags: DatabaseFlags,
) -> MdbxResult<(ffi::MDBX_dbi, DatabaseFlags)> {
    let mut dbi: ffi::MDBX_dbi = 0;
    let mut actual_flags: c_uint = 0;
    let mut _status: c_uint = 0;

    // SAFETY: Caller guarantees txn is valid, name_ptr is valid or null.
    mdbx_result(unsafe { ffi::mdbx_dbi_open(txn, name_ptr, flags.bits(), &mut dbi) })?;
    // SAFETY: Caller guarantees txn is valid, dbi was just opened.
    mdbx_result(unsafe { ffi::mdbx_dbi_flags_ex(txn, dbi, &mut actual_flags, &mut _status) })?;

    #[cfg_attr(not(windows), allow(clippy::useless_conversion))]
    let db_flags = DatabaseFlags::from_bits_truncate(actual_flags.try_into().unwrap());

    Ok((dbi, db_flags))
}

/// Retrieves the flags for an open database.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[inline(always)]
pub(crate) unsafe fn db_flags_raw(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
) -> MdbxResult<DatabaseFlags> {
    let mut flags: c_uint = 0;
    let mut _status: c_uint = 0;

    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_dbi_flags_ex(txn, dbi, &mut flags, &mut _status) })?;

    #[cfg_attr(not(windows), allow(clippy::useless_conversion))]
    Ok(DatabaseFlags::from_bits_truncate(flags.try_into().unwrap()))
}

/// Retrieves database statistics.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[inline(always)]
pub(crate) unsafe fn db_stat_raw(txn: *mut ffi::MDBX_txn, dbi: ffi::MDBX_dbi) -> MdbxResult<Stat> {
    let mut stat = Stat::new();
    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_dbi_stat(txn, dbi, stat.mdb_stat(), size_of::<Stat>()) })?;
    Ok(stat)
}

/// Commits a transaction.
///
/// Returns `true` if the transaction was aborted (botched), `false` otherwise.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `latency` may be null or a valid pointer to receive latency info.
#[inline(always)]
pub(crate) unsafe fn commit_raw(
    txn: *mut ffi::MDBX_txn,
    latency: *mut ffi::MDBX_commit_latency,
) -> MdbxResult<bool> {
    // SAFETY: Caller guarantees txn is valid, latency is null or valid.
    mdbx_result(unsafe { ffi::mdbx_txn_commit_ex(txn, latency) })
}

/// Stores a key/value pair in the database.
///
/// # Safety
///
/// - `txn` must be a valid, non-null RW transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[inline(always)]
pub(crate) unsafe fn put_raw(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    key: &[u8],
    data: &[u8],
    flags: WriteFlags,
) -> MdbxResult<()> {
    let key_val = ffi::MDBX_val { iov_len: key.len(), iov_base: key.as_ptr() as *mut c_void };
    let mut data_val =
        ffi::MDBX_val { iov_len: data.len(), iov_base: data.as_ptr() as *mut c_void };

    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_put(txn, dbi, &key_val, &mut data_val, flags.bits()) })?;
    Ok(())
}

/// Reserves space for a value and returns a mutable slice to write into.
///
/// # Safety
///
/// - `txn` must be a valid, non-null RW transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
/// - The returned slice is only valid until the transaction is committed,
///   aborted, or another value is inserted at the same key.
#[inline(always)]
pub(crate) unsafe fn reserve_raw(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    key: &[u8],
    len: usize,
    flags: WriteFlags,
) -> MdbxResult<*mut u8> {
    let key_val = ffi::MDBX_val { iov_len: key.len(), iov_base: key.as_ptr() as *mut c_void };
    let mut data_val = ffi::MDBX_val { iov_len: len, iov_base: ptr::null_mut::<c_void>() };

    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe {
        ffi::mdbx_put(txn, dbi, &key_val, &mut data_val, flags.bits() | ffi::MDBX_RESERVE)
    })?;

    Ok(data_val.iov_base as *mut u8)
}

/// Creates a slice from a reserved pointer.
///
/// # Safety
///
/// - `ptr` must be a valid pointer returned from `reserve_raw`.
/// - `len` must match the length passed to `reserve_raw`.
#[inline(always)]
pub(crate) const unsafe fn slice_from_reserved(ptr: *mut u8, len: usize) -> &'static mut [u8] {
    // SAFETY: Caller guarantees ptr is valid and len matches.
    unsafe { slice::from_raw_parts_mut(ptr, len) }
}

/// Deletes items from a database.
///
/// Returns `true` if the key/value pair was present, `false` if not found.
///
/// # Safety
///
/// - `txn` must be a valid, non-null RW transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[inline(always)]
pub(crate) unsafe fn del_raw(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    key: &[u8],
    data: Option<&[u8]>,
) -> MdbxResult<bool> {
    let key_val = ffi::MDBX_val { iov_len: key.len(), iov_base: key.as_ptr() as *mut c_void };
    let data_val: Option<ffi::MDBX_val> = data
        .map(|data| ffi::MDBX_val { iov_len: data.len(), iov_base: data.as_ptr() as *mut c_void });

    let ptr = data_val.as_ref().map_or(ptr::null(), |d| d as *const ffi::MDBX_val);

    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_del(txn, dbi, &key_val, ptr) }).map(|_| true).or_else(
        |e| match e {
            crate::MdbxError::NotFound => Ok(false),
            other => Err(other),
        },
    )
}

/// Empties a database (removes all items).
///
/// # Safety
///
/// - `txn` must be a valid, non-null RW transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[inline(always)]
pub(crate) unsafe fn clear_db_raw(txn: *mut ffi::MDBX_txn, dbi: ffi::MDBX_dbi) -> MdbxResult<()> {
    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_drop(txn, dbi, false) })?;
    Ok(())
}

/// Drops a database from the environment.
///
/// # Safety
///
/// - `txn` must be a valid, non-null RW transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
/// - Caller must ensure all other Database and Cursor instances pointing
///   to this dbi are closed before calling.
#[inline(always)]
pub(crate) unsafe fn drop_db_raw(txn: *mut ffi::MDBX_txn, dbi: ffi::MDBX_dbi) -> MdbxResult<()> {
    // SAFETY: Caller guarantees txn and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_drop(txn, dbi, true) })?;
    Ok(())
}

/// Closes a database handle.
///
/// # Safety
///
/// - `env` must be a valid, non-null environment pointer.
/// - `dbi` must be a valid database handle for this environment.
/// - Caller must ensure the database is not in use.
#[inline(always)]
pub(crate) unsafe fn close_db_raw(env: *mut ffi::MDBX_env, dbi: ffi::MDBX_dbi) -> MdbxResult<()> {
    // SAFETY: Caller guarantees env and dbi are valid.
    mdbx_result(unsafe { ffi::mdbx_dbi_close(env, dbi) })?;
    Ok(())
}

/// Checks if a memory pointer refers to dirty (modified) data.
///
/// Returns `true` if the data is dirty and must be copied before borrowing.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `ptr` must be a pointer to data within the transaction's database pages.
/// - Access MUST be serialized. Concurrent access is NOT ALLOWED.
#[inline(always)]
pub(crate) unsafe fn is_dirty_raw(
    txn: *const ffi::MDBX_txn,
    ptr: *const c_void,
) -> MdbxResult<bool> {
    // SAFETY: Caller guarantees txn and ptr are valid.
    mdbx_result(unsafe { ffi::mdbx_is_dirty(txn, ptr) })
}

// =============================================================================
// Debug-only helpers for append assertions
// =============================================================================

/// Gets pagesize from transaction environment.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
#[cfg(debug_assertions)]
unsafe fn get_pagesize(txn: *mut ffi::MDBX_txn) -> usize {
    // SAFETY: Caller guarantees txn is valid.
    let env_ptr = unsafe { ffi::mdbx_txn_env(txn) };
    let mut stat: ffi::MDBX_stat = unsafe { std::mem::zeroed() };
    // SAFETY: env_ptr is valid from mdbx_txn_env.
    unsafe { ffi::mdbx_env_stat_ex(env_ptr, ptr::null(), &mut stat, size_of::<ffi::MDBX_stat>()) };
    stat.ms_psize as usize
}

/// Gets last key from database using a temporary cursor.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[cfg(debug_assertions)]
unsafe fn get_last_key(txn: *mut ffi::MDBX_txn, dbi: ffi::MDBX_dbi) -> Option<Vec<u8>> {
    let mut cursor: *mut ffi::MDBX_cursor = ptr::null_mut();
    // SAFETY: Caller guarantees txn and dbi are valid.
    if unsafe { ffi::mdbx_cursor_open(txn, dbi, &mut cursor) } != ffi::MDBX_SUCCESS {
        return None;
    }
    let mut key_val = ffi::MDBX_val { iov_len: 0, iov_base: ptr::null_mut() };
    let mut data_val = ffi::MDBX_val { iov_len: 0, iov_base: ptr::null_mut() };
    // SAFETY: cursor was just opened successfully.
    let result =
        if unsafe { ffi::mdbx_cursor_get(cursor, &mut key_val, &mut data_val, ffi::MDBX_LAST) }
            == ffi::MDBX_SUCCESS
        {
            // SAFETY: mdbx_cursor_get returned success, so key_val is valid.
            Some(unsafe {
                slice::from_raw_parts(key_val.iov_base as *const u8, key_val.iov_len).to_vec()
            })
        } else {
            None
        };
    // SAFETY: cursor is valid.
    unsafe { ffi::mdbx_cursor_close(cursor) };
    result
}

/// Gets last dup for a key using a temporary cursor.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[cfg(debug_assertions)]
unsafe fn get_last_dup(txn: *mut ffi::MDBX_txn, dbi: ffi::MDBX_dbi, key: &[u8]) -> Option<Vec<u8>> {
    let mut cursor: *mut ffi::MDBX_cursor = ptr::null_mut();
    // SAFETY: Caller guarantees txn and dbi are valid.
    if unsafe { ffi::mdbx_cursor_open(txn, dbi, &mut cursor) } != ffi::MDBX_SUCCESS {
        return None;
    }
    let mut key_val = ffi::MDBX_val { iov_len: key.len(), iov_base: key.as_ptr() as *mut c_void };
    let mut data_val = ffi::MDBX_val { iov_len: 0, iov_base: ptr::null_mut() };

    // SAFETY: cursor was just opened successfully.
    let result =
        if unsafe { ffi::mdbx_cursor_get(cursor, &mut key_val, &mut data_val, ffi::MDBX_SET) }
            == ffi::MDBX_SUCCESS
        {
            // SAFETY: cursor is positioned at key.
            if unsafe {
                ffi::mdbx_cursor_get(cursor, &mut key_val, &mut data_val, ffi::MDBX_LAST_DUP)
            } == ffi::MDBX_SUCCESS
            {
                // SAFETY: mdbx_cursor_get returned success, so data_val is valid.
                Some(unsafe {
                    slice::from_raw_parts(data_val.iov_base as *const u8, data_val.iov_len).to_vec()
                })
            } else {
                None
            }
        } else {
            None
        };
    // SAFETY: cursor is valid.
    unsafe { ffi::mdbx_cursor_close(cursor) };
    result
}

/// All-in-one append assertion: opens cursor, gets last key, asserts, closes cursor.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[cfg(debug_assertions)]
pub(crate) unsafe fn debug_assert_append(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    flags: DatabaseFlags,
    key: &[u8],
    data: &[u8],
) {
    // SAFETY: Caller guarantees txn is valid.
    let pagesize = unsafe { get_pagesize(txn) };
    // SAFETY: Caller guarantees txn and dbi are valid.
    let last_key = unsafe { get_last_key(txn, dbi) };
    crate::tx::assertions::debug_assert_append(pagesize, flags, key, data, last_key.as_deref());
}

/// Get the count of duplicates for the current key.
///
/// Returns the number of duplicate values for the key at the current cursor
/// position. For databases without `DUP_SORT`, this always returns 1.
///
/// # Safety
///
/// - `cursor` must be a valid, non-null cursor pointer.
/// - Must be called within a `with_txn_ptr` block.
#[inline(always)]
pub(crate) unsafe fn cursor_dup_count(cursor: *mut ffi::MDBX_cursor) -> MdbxResult<usize> {
    let mut count: usize = 0;
    // SAFETY: Caller guarantees cursor is valid.
    match unsafe { ffi::mdbx_cursor_count(cursor, &mut count) } {
        ffi::MDBX_SUCCESS => Ok(count),
        err_code => Err(crate::MdbxError::from_err_code(err_code)),
    }
}

/// All-in-one append_dup assertion: opens cursor, gets last dup, asserts, closes cursor.
///
/// # Safety
///
/// - `txn` must be a valid, non-null transaction pointer.
/// - `dbi` must be a valid database handle for this transaction.
#[cfg(debug_assertions)]
pub(crate) unsafe fn debug_assert_append_dup(
    txn: *mut ffi::MDBX_txn,
    dbi: ffi::MDBX_dbi,
    flags: DatabaseFlags,
    key: &[u8],
    data: &[u8],
) {
    // SAFETY: Caller guarantees txn is valid.
    let pagesize = unsafe { get_pagesize(txn) };
    // SAFETY: Caller guarantees txn and dbi are valid.
    let last_dup = unsafe { get_last_dup(txn, dbi, key) };
    crate::tx::assertions::debug_assert_append_dup(pagesize, flags, key, data, last_dup.as_deref());
}