trivialdb-0.1.4/.cargo_vcs_info.json0000644000000001360000000000100130160ustar { "git": { "sha1": "d0b211f4ab97de5a93fca78350e305174e12c289" }, "path_in_vcs": "" }trivialdb-0.1.4/.github/workflows/rust.yml000064400000000000000000000005201046102023000167200ustar 00000000000000name: 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/.gitignore000064400000000000000000000000131046102023000135700ustar 00000000000000/target *~ trivialdb-0.1.4/COPYING000064400000000000000000000167441046102023000126550ustar 00000000000000 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.toml0000644000000021170000000000100110150ustar # 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.orig000064400000000000000000000007731046102023000145040ustar 00000000000000[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.md000064400000000000000000000005551046102023000130720ustar 00000000000000# 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.rs000064400000000000000000000025671046102023000132650ustar 00000000000000extern 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.rs000064400000000000000000000463311046102023000135200ustar 00000000000000//! 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>, Error> { let ret = unsafe { tdb_fetch(self.0, key.into()) }; if ret.dptr.is_null() { match self.error() { Err(Error::NoExist) => Ok(None), Err(e) => Err(e), Ok(_) => panic!("error but no error?"), } } else { Ok(Some(ret.into())) } } /// Store a key/value pair in the database. /// /// # Arguments /// /// * `key` - The key to store. /// * `val` - The value to store. /// * `flags` - The flags to use when storing the value. pub fn store( &mut self, key: &[u8], val: &[u8], flags: Option, ) -> Result<(), Error> { let flags = flags.map_or(0, |f| f as i32); let ret = unsafe { tdb_store(self.0, key.into(), val.into(), flags) }; if ret == -1 { self.error() } else { Ok(()) } } /// Delete a key from the database. /// /// # Arguments /// /// * `key` - The key to delete pub fn delete(&mut self, key: &[u8]) -> Result<(), Error> { let ret = unsafe { tdb_delete(self.0, key.into()) }; if ret == -1 { self.error() } else { Ok(()) } } /// Append a value to an existing key. /// /// # Arguments /// * `key` - The key to append to. /// * `val` - The value to append. pub fn append(&mut self, key: &[u8], val: &[u8]) -> Result<(), Error> { let ret = unsafe { tdb_append(self.0, key.into(), val.into()) }; if ret == -1 { self.error() } else { Ok(()) } } /// Iterate over all keys in the database. pub fn keys(&self) -> impl Iterator> + '_ { TdbKeys(self, None) } /// Iterate over all key/value pairs in the database. pub fn iter(&self) -> impl Iterator, Vec)> + '_ { TdbIter(self, TdbKeys(self, None)) } /// Check if a particular key exists pub fn exists(&self, key: &[u8]) -> bool { unsafe { tdb_exists(self.0, key.into()) } } /// Lock the database pub fn lockall(&self) -> Result<(), Error> { let ret = unsafe { generated::tdb_lockall(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Unlock the database pub fn unlockall(&self) -> Result<(), Error> { let ret = unsafe { generated::tdb_unlockall(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } pub fn lockall_nonblock(&self) -> Result<(), Error> { let ret = unsafe { generated::tdb_lockall_nonblock(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } pub fn lockall_read(&self) -> Result<(), Error> { let ret = unsafe { generated::tdb_lockall_read(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } pub fn lockall_read_nonblock(&self) -> Result<(), Error> { let ret = unsafe { generated::tdb_lockall_read_nonblock(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Return the name of the database pub fn name(&self) -> &str { unsafe { CStr::from_ptr(generated::tdb_name(self.0)) } .to_str() .unwrap() } /// Return the hash size used by the database pub fn hash_size(&self) -> u32 { unsafe { generated::tdb_hash_size(self.0) as u32 } } /// Return the map size used by the database pub fn map_size(&self) -> u32 { unsafe { generated::tdb_map_size(self.0) as u32 } } /// Return the current sequence number pub fn get_seqnum(&self) -> u64 { unsafe { generated::tdb_get_seqnum(self.0) as u64 } } /// Return the current flags pub fn get_flags(&self) -> Flags { Flags::from_bits_truncate(unsafe { generated::tdb_get_flags(self.0) as u32 }) } /// Add a flag pub fn add_flags(&mut self, flags: Flags) { unsafe { generated::tdb_add_flags(self.0, flags.bits()) }; } /// Remove a flag pub fn remove_flags(&mut self, flags: Flags) { unsafe { generated::tdb_remove_flags(self.0, flags.bits()) }; } /// Enable sequence numbers pub fn enable_seqnum(&mut self) { unsafe { generated::tdb_enable_seqnum(self.0) }; } /// Increment the sequence number pub fn increment_seqnum_nonblock(&mut self) { unsafe { generated::tdb_increment_seqnum_nonblock(self.0) }; } /// Repack the database pub fn repack(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_repack(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Wipe the database pub fn wipe_all(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_wipe_all(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Return a string summarizing the database pub fn summary(&self) -> String { let buf = unsafe { generated::tdb_summary(self.0) }; unsafe { CStr::from_ptr(buf) }.to_str().unwrap().to_owned() } /// Return the freelist size pub fn freelist_size(&self) -> u32 { unsafe { generated::tdb_freelist_size(self.0) as u32 } } /// Start a new transaction pub fn transaction_start(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_transaction_start(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Check if a transaction is active pub fn transaction_active(&self) -> bool { unsafe { generated::tdb_transaction_active(self.0) } } /// Start a new transaction, non-blocking pub fn transaction_start_nonblock(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_transaction_start_nonblock(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Prepare to commit a transaction pub fn transaction_prepare_commit(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_transaction_prepare_commit(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Commit a transaction pub fn transaction_commit(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_transaction_commit(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } /// Cancel a transaction pub fn transaction_cancel(&mut self) -> Result<(), Error> { let ret = unsafe { generated::tdb_transaction_cancel(self.0) }; if ret == -1 { self.error() } else { Ok(()) } } } impl AsRawFd for Tdb { fn as_raw_fd(&self) -> RawFd { unsafe { generated::tdb_fd(self.0) } } } struct TdbKeys<'a>(&'a Tdb, Option>); impl<'a> Iterator for TdbKeys<'a> { type Item = Vec; fn next(&mut self) -> Option> { let key = if let Some(prev_key) = self.1.take() { unsafe { tdb_nextkey(self.0 .0, prev_key.as_slice().into()) } } else { unsafe { generated::tdb_firstkey(self.0 .0) } }; if key.dptr.is_null() { match self.0.error() { Err(Error::NoExist) | Ok(_) => None, Err(e) => panic!("error: {}", e), } } else { let ret: Vec = key.into(); self.1 = Some(ret.clone()); Some(ret) } } } struct TdbIter<'a>(&'a Tdb, TdbKeys<'a>); impl<'a> Iterator for TdbIter<'a> { type Item = (Vec, Vec); fn next(&mut self) -> Option<(Vec, Vec)> { let key = self.1.next()?; let val = self.0.fetch(key.as_slice()).unwrap().unwrap(); Some((key, val)) } } impl Drop for Tdb { fn drop(&mut self) { unsafe { generated::tdb_close(self.0) }; } } /// Generate the jenkins hash of a key pub fn jenkins_hash(key: Vec) -> u32 { let mut key = key.into(); unsafe { generated::tdb_jenkins_hash(&mut key) } } #[cfg(test)] mod test { fn testtdb() -> super::Tdb { let tmppath = tempfile::tempdir().unwrap(); let path = tmppath.path().join("test.tdb"); super::Tdb::open( path.as_path(), None, super::Flags::empty(), libc::O_RDWR | libc::O_CREAT, ) .unwrap() } #[test] fn test_simple() { let mut tdb = testtdb(); tdb.store(b"foo", b"bar", None).unwrap(); assert_eq!(tdb.fetch(b"foo").unwrap().unwrap(), b"bar"); tdb.delete(b"foo").unwrap(); assert_eq!(tdb.fetch(b"foo").unwrap(), None); } #[test] fn test_iter() { let mut tdb = testtdb(); tdb.store(b"foo", b"bar", None).unwrap(); tdb.store(b"blah", b"bloe", None).unwrap(); let mut iter = tdb.iter(); assert_eq!(iter.next().unwrap(), (b"foo".to_vec(), b"bar".to_vec())); assert_eq!(iter.next().unwrap(), (b"blah".to_vec(), b"bloe".to_vec())); assert_eq!(iter.next(), None); } #[test] fn test_keys() { let mut tdb = testtdb(); tdb.store(b"foo", b"bar", None).unwrap(); tdb.store(b"blah", b"bloe", None).unwrap(); let mut keys = tdb.keys(); assert_eq!(keys.next().unwrap(), b"foo"); assert_eq!(keys.next().unwrap(), b"blah"); assert_eq!(keys.next(), None); } #[test] fn test_transaction() { let mut tdb = testtdb(); tdb.transaction_start().unwrap(); tdb.store(b"foo", b"bar", None).unwrap(); tdb.transaction_cancel().unwrap(); assert_eq!(tdb.fetch(b"foo").unwrap(), None); tdb.transaction_start().unwrap(); tdb.store(b"foo", b"bar", None).unwrap(); tdb.transaction_prepare_commit().unwrap(); tdb.transaction_commit().unwrap(); assert_eq!(tdb.fetch(b"foo").unwrap().unwrap(), b"bar"); } #[test] fn test_fetch_nonexistent() { let tdb = testtdb(); assert_eq!(tdb.fetch(b"foo").unwrap(), None); } #[test] fn test_store_overwrite() { let mut tdb = testtdb(); tdb.store(b"foo", b"bar", None).unwrap(); tdb.store(b"foo", b"blah", None).unwrap(); assert_eq!(tdb.fetch(b"foo").unwrap().unwrap(), b"blah"); } }