Skip to content

Instantly share code, notes, and snippets.

@FrancisMurillo
Created September 23, 2020 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrancisMurillo/cbac4297b71ed3309e287acda0e8b7aa to your computer and use it in GitHub Desktop.
Save FrancisMurillo/cbac4297b71ed3309e287acda0e8b7aa to your computer and use it in GitHub Desktop.
Rust Deref Example
use std::fs;
use std::ops::{Deref, DerefMut};
#[derive(Debug)]
struct DB;
#[derive(Debug)]
struct Index(Vec<u8>);
#[derive(Debug)]
struct IndexRef(Index);
#[derive(Debug)]
struct IndexRefMut(Index);
impl DB {
pub fn open() -> Self {
Self
}
fn read_index() -> Index {
Index(fs::read("index.db").unwrap())
}
pub fn load_index(&self) -> IndexRef {
IndexRef(Self::read_index())
}
pub fn lock_index(&mut self) -> IndexRefMut {
IndexRefMut(Self::read_index())
}
}
impl Deref for IndexRef {
type Target = Index;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Deref for IndexRefMut {
type Target = Index;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for IndexRefMut {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Index {
pub fn read(&self) -> &[u8] {
&self.0
}
pub fn add(&mut self, data: &[u8]) {
self.0.append(&mut data.to_vec());
}
}
impl Drop for IndexRefMut {
fn drop(&mut self) {
fs::write("index.db", &(self.0).0).ok();
}
}
fn main() {
fs::write("index.db", "").ok();
let mut db = DB::open();
{
let read_index = db.load_index();
println!("Should be empty data: {:?}", read_index.read());
}
{
let mut write_index = db.lock_index();
write_index.add("TOTORO".as_bytes());
drop(write_index);
}
{
let updated_index = db.load_index();
println!("Should have data: {:?}", updated_index.read());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment