Skip to content

Commit 2f10d1e

Browse files
author
blake2-ppc
committed
extra: Implement DoubleEnded and RandomAccess iterators for bitv
1 parent 2ff8412 commit 2f10d1e

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

src/libextra/bitv.rs

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@
1212

1313

1414
use std::cmp;
15+
use std::iterator::{DoubleEndedIterator, RandomAccessIterator, Invert};
1516
use std::num;
1617
use std::ops;
1718
use std::uint;
1819
use std::vec;
1920

21+
2022
#[deriving(Clone)]
2123
struct SmallBitv {
2224
/// only the lowest nbits of this value are used. the rest is undefined.
@@ -404,7 +406,7 @@ impl Bitv {
404406

405407
#[inline]
406408
pub fn iter<'a>(&'a self) -> BitvIterator<'a> {
407-
BitvIterator {bitv: self, next_idx: 0}
409+
BitvIterator {bitv: self, next_idx: 0, end_idx: self.nbits}
408410
}
409411

410412
/// Returns true if all bits are 0
@@ -564,13 +566,14 @@ fn iterate_bits(base: uint, bits: uint, f: &fn(uint) -> bool) -> bool {
564566
/// An iterator for Bitv
565567
pub struct BitvIterator<'self> {
566568
priv bitv: &'self Bitv,
567-
priv next_idx: uint
569+
priv next_idx: uint,
570+
priv end_idx: uint,
568571
}
569572

570573
impl<'self> Iterator<bool> for BitvIterator<'self> {
571574
#[inline]
572575
fn next(&mut self) -> Option<bool> {
573-
if self.next_idx < self.bitv.nbits {
576+
if self.next_idx != self.end_idx {
574577
let idx = self.next_idx;
575578
self.next_idx += 1;
576579
Some(self.bitv.get(idx))
@@ -580,11 +583,39 @@ impl<'self> Iterator<bool> for BitvIterator<'self> {
580583
}
581584

582585
fn size_hint(&self) -> (uint, Option<uint>) {
583-
let rem = self.bitv.nbits - self.next_idx;
586+
let rem = self.end_idx - self.next_idx;
584587
(rem, Some(rem))
585588
}
586589
}
587590

591+
impl<'self> DoubleEndedIterator<bool> for BitvIterator<'self> {
592+
#[inline]
593+
fn next_back(&mut self) -> Option<bool> {
594+
if self.next_idx != self.end_idx {
595+
self.end_idx -= 1;
596+
Some(self.bitv.get(self.end_idx))
597+
} else {
598+
None
599+
}
600+
}
601+
}
602+
603+
impl<'self> RandomAccessIterator<bool> for BitvIterator<'self> {
604+
#[inline]
605+
fn indexable(&self) -> uint {
606+
self.end_idx - self.next_idx
607+
}
608+
609+
#[inline]
610+
fn idx(&self, index: uint) -> Option<bool> {
611+
if index >= self.indexable() {
612+
None
613+
} else {
614+
Some(self.bitv.get(index))
615+
}
616+
}
617+
}
618+
588619
/// An implementation of a set using a bit vector as an underlying
589620
/// representation for holding numerical elements.
590621
///

0 commit comments

Comments
 (0)