Skip to content

Commit

Permalink
feat(util): finish load_mmaped_file
Browse files Browse the repository at this point in the history
`Mmap` will be auto-released out of scope.
  • Loading branch information
Huo Linhe committed Mar 7, 2016
1 parent 66ad1cd commit a470b94
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/engine/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ fn from_chars_to_cstring(p: *mut ::libc::c_char) -> CString {
}

fn from_chars_to_string(p: *mut ::libc::c_char) -> String {
from_chars_to_cstring(p).into_string().unwrap()
from_chars_to_cstring(p).into_string().unwrap()
}


Expand Down
49 changes: 43 additions & 6 deletions src/engine/util.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,61 @@
use std::path::Path;
use std::mem;
use libc::c_void;
use super::UnQlite;
use ffi::{unqlite_util_random_num, unqlite_util_random_string};
use ffi::{unqlite_util_load_mmaped_file, unqlite_util_random_num, unqlite_util_random_string,
unqlite_util_release_mmaped_file};

impl <'util> UnQlite {
impl<'util> UnQlite {
/// Generate random string using the UnQLite PRNG.
///
/// It will generate a english alphabet based string of length buf_size (last argument).
fn random_string(&self, buf_size: u32) -> Vec<u8> {
pub fn random_string(&self, buf_size: u32) -> Vec<u8> {
unsafe {
let mut vec: Vec<u8> = Vec::with_capacity(buf_size as usize);
error_or!(unqlite_util_random_string(self.db, vec.as_mut_ptr() as *mut i8, buf_size)).unwrap();
error_or!(unqlite_util_random_string(self.db, vec.as_mut_ptr() as *mut i8, buf_size))
.unwrap();
vec
}
}

/// Generate random number using the UnQLite PRNG.
///
/// It will return a 32-bit unsigned integer between 0 and 0xFFFFFFFF.
fn random_num(&self) -> u32 {
pub fn random_num(&self) -> u32 {
unsafe { unqlite_util_random_num(self.db) }
}

/// Memory-mapped file
pub fn load_mmaped_file<P: AsRef<Path>>(path: P) -> ::Result<Mmap> {
unsafe {
let path = path.as_ref();
let mut ptr: *mut c_void = mem::uninitialized();
let mut size: i64 = mem::uninitialized();
error_or!(unqlite_util_load_mmaped_file(path.as_os_str()
.to_cstring()
.unwrap()
.as_ptr(),
&mut ptr,
&mut size))
.map(|_| {
Mmap {
ptr: ptr,
size: size,
}
})
}
}
}

pub struct Mmap {
pub ptr: *mut c_void,
pub size: i64,
}

impl Drop for Mmap {
fn drop(&mut self) {
unsafe {
unqlite_util_random_num(self.db)
error_or!(unqlite_util_release_mmaped_file(self.ptr, self.size)).unwrap();
}
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![feature(convert)]

extern crate unqlite_sys as ffi;
extern crate libc;

Expand Down

0 comments on commit a470b94

Please sign in to comment.