Created
March 27, 2018 22:27
-
-
Save rust-play/478c756e7e2738ea13549b27818c34ff to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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::cell::{RefMut, RefCell, BorrowMutError}; | |
use std::clone::Clone; | |
use std::ops::DerefMut; | |
struct I2C { | |
} | |
impl I2C { | |
pub fn send(&mut self, d: &[u8]) -> Result<(), std::io::Error> { | |
println!("I2C send: {:?}", d); | |
Ok(()) | |
} | |
} | |
trait Proxy<'a, T: 'a> { | |
fn get(&mut self) -> Result<RefMut<&'a mut T>, BorrowMutError>; | |
} | |
struct SimpleProxy<'a, T: 'a> { | |
item: RefCell<&'a mut T> | |
} | |
impl <'a, T>SimpleProxy<'a, T> { | |
pub fn new(i: &'a mut T) -> SimpleProxy<'a, T> { | |
SimpleProxy{item: RefCell::new(i)} | |
} | |
} | |
impl <'a, T>Clone for SimpleProxy<'a, T> { | |
fn clone(&self) -> SimpleProxy<'a, T> { | |
SimpleProxy::<T>{item: self.item.clone()} | |
} | |
} | |
impl <'a, T>Proxy<'a, T> for SimpleProxy<'a, T> { | |
fn get(&mut self) -> Result<RefMut<&'a mut T>, BorrowMutError> { | |
Ok(self.item.try_borrow_mut()?) | |
} | |
} | |
fn main() { | |
let mut i2c = I2C{}; | |
let mut i2c_proxy = SimpleProxy::new(&mut i2c); | |
{ | |
let mut i2c_ref = i2c_proxy.get().unwrap(); | |
let i2c_dev = i2c_ref.deref_mut(); | |
i2c_dev.send(&[0u8; 4]).unwrap() | |
} | |
{ | |
let mut i2c_ref = i2c_proxy.get().unwrap(); | |
let i2c_dev = i2c_ref.deref_mut(); | |
i2c_dev.send(&[1u8; 4]).unwrap() | |
} | |
let _i2c_ref = i2c_proxy.clone().get().unwrap(); | |
let _i2c_ref2 = i2c_proxy.clone().get().unwrap(); | |
println!("Hello, world!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment