use libesedb_sys::*;
use std::ffi::CString;
use std::io;
use std::path::Path;
use std::ptr::null_mut;
use crate::error::ese_result;
use crate::Table;
const LIBESEDB_OPEN_READ: LIBESEDB_ACCESS_FLAGS = LIBESEDB_ACCESS_FLAGS_LIBESEDB_ACCESS_FLAG_READ;
pub struct EseDb {
ptr: *mut libesedb_file_t,
}
impl EseDb {
pub fn open<P: AsRef<Path>>(filename: P) -> io::Result<Self> {
let filename = CString::new(&*filename.as_ref().to_string_lossy())?;
let mut ptr = null_mut();
ese_result!(libesedb_file_initialize, &mut ptr)?;
if let Err(e) = ese_result!(
libesedb_file_open,
ptr,
filename.as_ptr(),
LIBESEDB_OPEN_READ
) {
unsafe {
libesedb_file_free(&mut ptr, null_mut());
}
return Err(e);
}
Ok(Self { ptr })
}
pub fn as_mut_ptr(&mut self) -> *mut libesedb_table_t {
self.ptr
}
pub fn table(&self, entry: i32) -> io::Result<Table> {
Table::load(self.ptr, entry)
}
pub fn table_by_name(&self, name: &str) -> io::Result<Table> {
Table::from_name(self.ptr, name)
}
pub fn count_tables(&self) -> io::Result<i32> {
let mut n = 0;
ese_result!(libesedb_file_get_number_of_tables, self.ptr, &mut n)?;
Ok(n)
}
pub fn iter_tables(&self) -> io::Result<impl Iterator<Item = io::Result<Table>>> {
Ok((0..self.count_tables()?).map(|i| Table::load(self.ptr, i)))
}
}
impl Drop for EseDb {
fn drop(&mut self) {
unsafe {
libesedb_file_free(&mut self.ptr, null_mut());
}
}
}