trivialdb-0.1.4/.cargo_vcs_info.json 0000644 00000000136 00000000001 0013016 0 ustar {
"git": {
"sha1": "d0b211f4ab97de5a93fca78350e305174e12c289"
},
"path_in_vcs": ""
} trivialdb-0.1.4/.github/workflows/rust.yml 0000644 0000000 0000000 00000000520 10461020230 0016720 0 ustar 0000000 0000000 name: Rust
on:
push:
pull_request:
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install tdb-dev
run: sudo apt install -y libtdb-dev
- name: Build
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose
trivialdb-0.1.4/.gitignore 0000644 0000000 0000000 00000000013 10461020230 0013570 0 ustar 0000000 0000000 /target
*~
trivialdb-0.1.4/COPYING 0000644 0000000 0000000 00000016744 10461020230 0012655 0 ustar 0000000 0000000 GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
trivialdb-0.1.4/Cargo.toml 0000644 00000002117 00000000001 0011015 0 ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
name = "trivialdb"
version = "0.1.4"
authors = ["Jelmer Vernooij "]
description = "Rust bindings for the TDB database library"
homepage = "https://github.com/jelmer/tdb-rs"
readme = "README.md"
license = "LGPL-3.0-or-later"
repository = "https://github.com/jelmer/tdb-rs.git"
[package.metadata.system-deps]
tdb = "1.0"
[dependencies.bitflags]
version = "1.2"
[dependencies.libc]
version = "0.2"
[dev-dependencies.tempfile]
version = "3"
[build-dependencies.bindgen]
version = ">=0.65"
[build-dependencies.pkg-config]
version = "0.3"
[build-dependencies.system-deps]
version = "6.1.1"
trivialdb-0.1.4/Cargo.toml.orig 0000644 0000000 0000000 00000000773 10461020230 0014504 0 ustar 0000000 0000000 [package]
name = "trivialdb"
version = "0.1.4"
edition = "2021"
authors = ["Jelmer Vernooij "]
repository = "https://github.com/jelmer/tdb-rs.git"
homepage = "https://github.com/jelmer/tdb-rs"
license = "LGPL-3.0-or-later"
description = "Rust bindings for the TDB database library"
[dependencies]
libc = "0.2"
bitflags = "1.2"
[build-dependencies]
pkg-config = "0.3"
bindgen = ">=0.65"
system-deps = "6.1.1"
[dev-dependencies]
tempfile = "3"
[package.metadata.system-deps]
tdb = "1.0"
trivialdb-0.1.4/README.md 0000644 0000000 0000000 00000000555 10461020230 0013072 0 ustar 0000000 0000000 # Rust bindings for TDB
This rust crate provides idiomatic Rust bindings for the Trivial Database (TDB)
library.
See the [TDB homepage](https://tdb.samba.org/) for more details.
## Example
```rust
use trivialdb::{Tdb,Flags};
let tdb = Tdb::memory(None, Flags::empty());
tdb.store(b"key", b"value", None).unwrap();
assert_eq!(b"value", tdb.fetch(b"key"));
```
trivialdb-0.1.4/build.rs 0000644 0000000 0000000 00000002567 10461020230 0013265 0 ustar 0000000 0000000 extern crate bindgen;
extern crate pkg_config;
fn main() {
system_deps::Config::new().probe().unwrap();
// Use pkg-config to get the necessary flags for the `tdb` library
let pc_tdb = pkg_config::Config::new()
.probe("tdb")
.unwrap_or_else(|e| panic!("Failed to find tdb library: {}", e));
if pc_tdb.include_paths.len() != 1 {
panic!("Expected to find exactly one tdb include path");
}
let tdb_header = pc_tdb.include_paths[0].join("tdb.h");
// Generate bindings using bindgen
let bindings = bindgen::Builder::default()
.header_contents("tdb.h", "typedef int mode_t;")
.header(tdb_header.to_str().unwrap())
.blocklist_type("TDB_DATA")
.blocklist_function("tdb_store")
.blocklist_function("tdb_fetch")
.blocklist_function("tdb_append")
.blocklist_function("tdb_delete")
.blocklist_function("tdb_exists")
.blocklist_function("tdb_nextkey")
.clang_args(
pc_tdb
.include_paths
.iter()
.map(|path| format!("-I{}", path.display())),
)
.generate()
.expect("Failed to generate bindings");
let out_path = std::path::PathBuf::from(std::env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("tdb_sys.rs"))
.expect("Failed to write bindings");
}
trivialdb-0.1.4/src/lib.rs 0000644 0000000 0000000 00000046331 10461020230 0013520 0 ustar 0000000 0000000 //! Rust bindings for TDB (Trivial Database)
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
mod generated {
#![allow(dead_code)]
include!(concat!(env!("OUT_DIR"), "/tdb_sys.rs"));
#[repr(C)]
pub struct TDB_DATA {
pub dptr: *mut std::os::raw::c_uchar,
pub dsize: usize,
}
}
use generated::TDB_DATA;
use bitflags::bitflags;
use std::ffi::CStr;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::{AsRawFd, RawFd};
pub struct Tdb(*mut generated::tdb_context);
#[derive(Debug)]
pub enum Error {
Corrupt,
IO,
Lock,
OOM,
Exists,
NoLock,
LockTimeout,
ReadOnly,
NoExist,
Invalid,
Nesting,
Unknown(u32),
}
bitflags! {
pub struct Flags: u32 {
/// CLEAR_IF_FIRST - Clear database if we are the only one with it open
const CLEAR_IF_FIRST = generated::TDB_CLEAR_IF_FIRST;
/// NOMMAP - Don't use mmap
const NOMMAP = generated::TDB_NOMMAP;
/// NOLOCK - Don't do any locking
const NOLOCK = generated::TDB_NOLOCK;
/// NOSYNC - Don't synchronise transactions to disk
const NOSYNC = generated::TDB_SEQNUM;
/// SEQNUM - Maintain a sequence number
const SEQNUM = generated::TDB_SEQNUM;
/// VOLATILE - activate the per-hashchain freelist, default 5.
const VOLATILE = generated::TDB_VOLATILE;
/// ALLOW_NESTING - Allow transactions to nest.
const ALLOW_NESTING = generated::TDB_ALLOW_NESTING;
/// DISALLOW_NESTING - Disallow transactions to nest.
const DISALLOW_NESTING = generated::TDB_DISALLOW_NESTING;
/// INCOMPATIBLE_HASH - Better hashing: can't be opened by tdb < 1.2.6.
const INCOMPATIBLE_HASH = generated::TDB_INCOMPATIBLE_HASH;
/// MUTEX_LOCKING - Optimized locking using robust mutexes if supported, can't be opened by tdb < 1.3.0.
/// Only valid in combination with TDB_CLEAR_IF_FIRST after checking tdb_runtime_check_for_robust_mutexes()
const MUTEX_LOCKING = generated::TDB_MUTEX_LOCKING;
}
}
#[repr(C)]
pub enum StoreFlags {
/// Don't overwrite an existing entry.
INSERT = generated::TDB_INSERT as isize,
/// Don't create a new entry.
REPLACE = generated::TDB_REPLACE as isize,
/// Don't create an existing entry.
MODIFY = generated::TDB_MODIFY as isize,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let msg = match self {
Error::Corrupt => "Corrupt",
Error::IO => "IO",
Error::Lock => "Lock",
Error::OOM => "OOM",
Error::Exists => "Exists",
Error::NoLock => "NoLock",
Error::LockTimeout => "LockTimeout",
Error::ReadOnly => "ReadOnly",
Error::NoExist => "NoExist",
Error::Invalid => "Invalid",
Error::Nesting => "Nesting",
Error::Unknown(e) => return write!(f, "Unknown({})", e),
};
write!(f, "{}", msg)
}
}
impl std::error::Error for Error {}
impl From for Error {
fn from(e: u32) -> Self {
match e {
generated::TDB_ERROR_TDB_ERR_CORRUPT => Error::Corrupt,
generated::TDB_ERROR_TDB_ERR_IO => Error::IO,
generated::TDB_ERROR_TDB_ERR_LOCK => Error::Lock,
generated::TDB_ERROR_TDB_ERR_OOM => Error::OOM,
generated::TDB_ERROR_TDB_ERR_EXISTS => Error::Exists,
generated::TDB_ERROR_TDB_ERR_NOLOCK => Error::NoLock,
generated::TDB_ERROR_TDB_ERR_LOCK_TIMEOUT => Error::LockTimeout,
generated::TDB_ERROR_TDB_ERR_RDONLY => Error::ReadOnly,
generated::TDB_ERROR_TDB_ERR_NOEXIST => Error::NoExist,
generated::TDB_ERROR_TDB_ERR_EINVAL => Error::Invalid,
generated::TDB_ERROR_TDB_ERR_NESTING => Error::Nesting,
_ => Error::Unknown(e),
}
}
}
impl From for Error {
fn from(e: i32) -> Self {
From::::from(e as u32)
}
}
impl From> for TDB_DATA {
fn from(data: Vec) -> Self {
let ptr = data.as_ptr() as *mut std::os::raw::c_uchar;
let len = data.len();
std::mem::forget(data);
TDB_DATA {
dptr: ptr,
dsize: len,
}
}
}
impl Drop for TDB_DATA {
fn drop(&mut self) {
unsafe {
libc::free(self.dptr as *mut libc::c_void);
}
}
}
impl Clone for TDB_DATA {
fn clone(&self) -> Self {
unsafe {
let ptr = libc::malloc(self.dsize) as *mut std::os::raw::c_uchar;
std::ptr::copy_nonoverlapping(self.dptr, ptr, self.dsize);
TDB_DATA {
dptr: ptr,
dsize: self.dsize,
}
}
}
}
impl From for Vec {
fn from(mut data: TDB_DATA) -> Self {
let ret = unsafe { Vec::from_raw_parts(data.dptr, data.dsize, data.dsize) };
data.dptr = std::ptr::null_mut();
ret
}
}
#[repr(C)]
pub struct CONST_TDB_DATA {
pub dptr: *const std::os::raw::c_uchar,
pub dsize: usize,
}
impl From<&[u8]> for CONST_TDB_DATA {
fn from(data: &[u8]) -> Self {
CONST_TDB_DATA {
dptr: data.as_ptr(),
dsize: data.len(),
}
}
}
extern "C" {
fn tdb_fetch(tdb: *mut generated::tdb_context, key: CONST_TDB_DATA) -> TDB_DATA;
fn tdb_store(
tdb: *mut generated::tdb_context,
key: CONST_TDB_DATA,
dbuf: CONST_TDB_DATA,
flag: ::std::os::raw::c_int,
) -> ::std::os::raw::c_int;
fn tdb_append(
tdb: *mut generated::tdb_context,
key: CONST_TDB_DATA,
new_dbuf: CONST_TDB_DATA,
) -> ::std::os::raw::c_int;
fn tdb_exists(tdb: *mut generated::tdb_context, key: CONST_TDB_DATA) -> bool;
fn tdb_delete(tdb: *mut generated::tdb_context, key: CONST_TDB_DATA) -> ::std::os::raw::c_int;
fn tdb_nextkey(tdb: *mut generated::tdb_context, key: CONST_TDB_DATA) -> TDB_DATA;
}
impl Tdb {
/// Open the database and creating it if necessary.
///
/// # Arguments
///
/// * `name` - The name of the db to open.
/// * `hash_size` - The hash size is advisory, leave None for a default.
/// * `tdb_flags` The flags to use to open the db:
/// * `open_flags` Flags for the open(2) function.
pub fn open(
name: &std::path::Path,
hash_size: Option,
tdb_flags: Flags,
open_flags: i32,
) -> Option {
let hash_size = hash_size.unwrap_or(0);
let ret = unsafe {
generated::tdb_open(
name.as_os_str().as_bytes().as_ptr() as *const i8,
hash_size as i32,
tdb_flags.bits() as i32,
open_flags,
0,
)
};
if ret.is_null() {
None
} else {
Some(Tdb(ret))
}
}
/// Create a database in memory
///
/// # Arguments
///
/// * `hash_size` - The hash size is advisory, leave None for a default.
/// * `tdb_flags` The flags to use to open the db:
pub fn memory(hash_size: Option, tdb_flags: Flags) -> Option {
let hash_size = hash_size.unwrap_or(0);
let ret = unsafe {
generated::tdb_open(
b":memory:\0".as_ptr() as *const i8,
hash_size as i32,
tdb_flags.bits() as i32,
0,
0,
)
};
if ret.is_null() {
None
} else {
Some(Tdb(ret))
}
}
/// Return the latest error that occurred
fn error(&self) -> Result<(), Error> {
let err = unsafe { generated::tdb_error(self.0) };
if err == 0 {
Ok(())
} else {
Err(err.into())
}
}
/// Set the maximum number of dead records per hash chain.
pub fn set_max_dead(&mut self, max_dead: u32) {
unsafe { generated::tdb_set_max_dead(self.0, max_dead as i32) };
}
/// Reopen the database
///
/// This can be used to reopen a database after a fork, to ensure that we have an independent
/// seek pointer and to re-establish any locks.
pub fn reopen(&mut self) -> Result<(), Error> {
let ret = unsafe { generated::tdb_reopen(self.0) };
if ret == -1 {
self.error()
} else {
Ok(())
}
}
/// Fetch a value from the database.:w
///
/// # Arguments
/// * `key` - The key to fetch.
///
/// # Returns
///
/// * `Ok(Some(value))` - The value associated with the key.
/// * `Ok(None)` - The key was not found.
/// * `Err(e)` - An error occurred.
pub fn fetch(&self, key: &[u8]) -> Result