Created
November 11, 2019 19:49
-
-
Save rust-play/5a9b90db4bf361dec7a93fc9c2b11b74 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
#![feature(const_generics)] | |
use std::cell::{Cell, UnsafeCell}; | |
use core::mem::MaybeUninit; | |
fn main() { | |
let mut arr = [""]; | |
let view = MutView::<_, 1>::new(&mut arr); | |
let a = "undefined".to_string(); | |
*view.get_mut(0).unwrap() = a.as_str(); | |
println!("{:?}", arr); | |
let mut arr = [10,20,30,40,50]; | |
let view = MutView::<_, 3>::new(&mut arr); | |
let a = view.get_mut(0).unwrap(); | |
let b = view.get_mut(1).unwrap(); | |
let c = view.get_mut(2).unwrap(); | |
//panic! 4 variables was borrowed | |
//let c = view.get_mut(4).unwrap(); | |
//panic! borrowing same key twice | |
//let c = view.get_mut(2).unwrap(); | |
*a += *b + *c; | |
*b += 2; | |
*c += 3; | |
println!("{:?}", &arr[..]); | |
} | |
struct MutView<'a, V, const N: usize> { | |
keys: [Cell<MaybeUninit<usize>>; N], | |
len: Cell<usize>, | |
view: &'a [UnsafeCell<V>], | |
} | |
impl<'a, V, const N: usize> MutView<'a, V, {N}> { | |
fn new(slice: &'a mut [V]) -> Self { | |
let keys: [Cell<MaybeUninit<usize>>; N] = unsafe { | |
MaybeUninit::uninit().assume_init() | |
}; | |
MutView { | |
view: unsafe { std::mem::transmute(slice) }, | |
keys: keys, | |
len: Cell::new(0), | |
} | |
} | |
fn get_mut(&self, key: usize) -> Option<&mut V> { | |
let len = self.len.get(); | |
if self.keys[..len] | |
.iter() | |
.find(|&i| { | |
let i = unsafe { | |
i.get().assume_init() | |
}; | |
i == key }) | |
.is_some() | |
{ | |
panic!("borrowing mut more than once is not allowed") | |
} | |
if len >= self.keys.len() { | |
panic!("reached max borrows, you can increase the size of N if needed") | |
} | |
self.keys[len].set(MaybeUninit::new(key)); | |
self.len.set(len + 1); | |
let item = self.view.get(key)?; | |
unsafe { | |
Some(&mut *item.get()) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment