view src/env.rs @ 387:2ac6eedcc9dc

db_impl: Use a BufWriter inside LogWriter Unbuffered write-a-lot with 32768 entries written, first four iterations on a new DB: usr=0.32 sys=0.12 elap=0.46 usr=0.47 sys=0.12 elap=0.60 usr=0.59 sys=0.11 elap=0.72 usr=0.50 sys=0.15 elap=0.67 Buffered write-a-lot with 32768 entries written, first four iterations on a new DB: usr=0.22 sys=0.01 elap=0.24 (delta = -0.1/-0.11/-0.22) usr=0.43 sys=0.03 elap=0.48 (delta = -0.04/-0.09/-0.12) usr=0.54 sys=0.05 elap=0.62 (delta = -0.05/-0.06/-0.1) usr=0.42 sys=0.03 elap=0.47 (delta = (-0.08/-0.12/-0.2)
author Lewin Bormann <lbo@spheniscida.de>
date Mon, 09 Oct 2017 05:51:43 +0000
parents 9a2f35bb13d6
children 24e076b4ad21
line wrap: on
line source

//! An `env` is an abstraction layer that allows the database to run both on different platforms as
//! well as persisting data on disk or in memory.

use error::Result;

use std::io::prelude::*;
use std::fs::File;
use std::os::unix::fs::FileExt;
use std::path::Path;

pub trait RandomAccess {
    fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize>;
}

impl RandomAccess for File {
    fn read_at(&self, off: usize, dst: &mut [u8]) -> Result<usize> {
        Ok((self as &FileExt).read_at(dst, off as u64)?)
    }
}

pub struct FileLock {
    pub id: String,
}

pub trait Env {
    fn open_sequential_file(&self, &Path) -> Result<Box<Read>>;
    fn open_random_access_file(&self, &Path) -> Result<Box<RandomAccess>>;
    fn open_writable_file(&self, &Path) -> Result<Box<Write>>;
    fn open_appendable_file(&self, &Path) -> Result<Box<Write>>;

    fn exists(&self, &Path) -> Result<bool>;
    fn children(&self, &Path) -> Result<Vec<String>>;
    fn size_of(&self, &Path) -> Result<usize>;

    fn delete(&self, &Path) -> Result<()>;
    fn mkdir(&self, &Path) -> Result<()>;
    fn rmdir(&self, &Path) -> Result<()>;
    fn rename(&self, &Path, &Path) -> Result<()>;

    fn lock(&self, &Path) -> Result<FileLock>;
    fn unlock(&self, l: FileLock) -> Result<()>;

    fn new_logger(&self, &Path) -> Result<Logger>;

    fn micros(&self) -> u64;
    fn sleep_for(&self, micros: u32);
}

pub struct Logger {
    dst: Box<Write>,
}

impl Logger {
    pub fn new(w: Box<Write>) -> Logger {
        Logger { dst: w }
    }

    pub fn log(&mut self, message: &String) {
        let _ = self.dst.write(message.as_bytes());
        let _ = self.dst.write("\n".as_bytes());
    }
}

pub fn path_to_string(p: &Path) -> String {
    p.to_str().map(String::from).unwrap()
}

pub fn path_to_str(p: &Path) -> &str {
    p.to_str().unwrap()
}