Skip to content

Instantly share code, notes, and snippets.

@SiegeLord
Last active August 29, 2015 14:00
Show Gist options
  • Save SiegeLord/b71373dc7f0a1d495372 to your computer and use it in GitHub Desktop.
Save SiegeLord/b71373dc7f0a1d495372 to your computer and use it in GitHub Desktop.
IndexAssign
use std::cell::Cell;
trait IndexAssign<IDX, RHS>
{
fn index_assign(self, idx: IDX, rhs: RHS);
}
struct ArrayLike
{
arr: Vec<Cell<u32>>
}
impl ArrayLike
{
fn assign_mul(&self, mul: u32, rhs: &ArrayLike)
{
for i in range(0, self.arr.len())
{
self.index_assign(i, rhs.arr.get(i).get() * mul);
}
}
}
impl<'l> IndexAssign<uint, u32> for &'l ArrayLike
{
fn index_assign(self, idx: uint, rhs: u32)
{
self.arr.get(idx).set(rhs)
}
}
impl<'l> IndexAssign<uint, bool> for &'l mut i32
{
fn index_assign(self, idx: uint, rhs: bool)
{
let m = 1 << idx;
if rhs
{
(*self) |= m;
}
else
{
(*self) &= !m;
}
}
}
fn main()
{
let arr = ArrayLike{ arr: vec![Cell::new(1)] };
arr.index_assign(0, 2);
arr.assign_mul(2, &arr);
let mut i = 0i32;
i.index_assign(3, true);
println!("{}", i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment