Created
September 23, 2020 14:49
-
-
Save FrancisMurillo/cbac4297b71ed3309e287acda0e8b7aa to your computer and use it in GitHub Desktop.
Rust Deref Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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