Created
July 26, 2017 23:35
-
-
Save gnuvince/fe9e2b7850b3be146e3ae8871bd1f565 to your computer and use it in GitHub Desktop.
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
impl <'a> IntoIterator for &'a Bitmap { | |
type Item = u16; | |
type IntoIter = SharedBitmapIterator<'a>; | |
fn into_iter(self) -> Self::IntoIter { | |
return SharedBitmapIterator { offset: 0, bitmap: &self }; | |
} | |
} | |
impl IntoIterator for Bitmap { | |
type Item = u16; | |
type IntoIter = OwnedBitmapIterator; | |
fn into_iter(self) -> Self::IntoIter { | |
return OwnedBitmapIterator { offset: 0, bitmap: self }; | |
} | |
} | |
pub struct SharedBitmapIterator<'a> { | |
offset: usize, | |
bitmap: &'a Bitmap, | |
} | |
pub struct OwnedBitmapIterator { | |
offset: usize, | |
bitmap: Bitmap, | |
} | |
impl <'a> Iterator for SharedBitmapIterator<'a> { | |
type Item = u16; | |
fn next(&mut self) -> Option<Self::Item> { | |
loop { | |
let bucket = self.offset / BITS_PER_BUCKET; | |
let bit_pos = self.offset % BITS_PER_BUCKET; | |
if bucket >= self.bitmap.num_buckets() { | |
return None; | |
} | |
// Optimization: skip whole bucket when its value is zero. | |
if self.bitmap.buckets[bucket] == 0 { | |
self.offset += 64; | |
continue; | |
} | |
if self.bitmap.buckets[bucket] & (1 << bit_pos) == 0 { | |
self.offset += 1; | |
continue; | |
} | |
let x = self.offset; | |
self.offset += 1; | |
return Some(x as u16); | |
} | |
} | |
} | |
impl Iterator for OwnedBitmapIterator { | |
type Item = u16; | |
fn next(&mut self) -> Option<Self::Item> { | |
loop { | |
let bucket = self.offset / BITS_PER_BUCKET; | |
let bit_pos = self.offset % BITS_PER_BUCKET; | |
if bucket >= self.bitmap.num_buckets() { | |
return None; | |
} | |
// Optimization: skip whole bucket when its value is zero. | |
if self.bitmap.buckets[bucket] == 0 { | |
self.offset += 64; | |
continue; | |
} | |
if self.bitmap.buckets[bucket] & (1 << bit_pos) == 0 { | |
self.offset += 1; | |
continue; | |
} | |
let x = self.offset; | |
self.offset += 1; | |
return Some(x as u16); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment