Skip to content

Commit fd10d20

Browse files
committed
Implement Index for RingBuf
This also deprecates RingBuf::get. Use indexing instead.
1 parent 06727d4 commit fd10d20

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

src/libcollections/ringbuf.rs

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,8 @@ impl<T> RingBuf<T> {
139139
/// # Example
140140
///
141141
/// ```rust
142+
/// #![allow(deprecated)]
143+
///
142144
/// use std::collections::RingBuf;
143145
///
144146
/// let mut buf = RingBuf::new();
@@ -147,6 +149,7 @@ impl<T> RingBuf<T> {
147149
/// buf.push(5);
148150
/// assert_eq!(buf.get(1), &4);
149151
/// ```
152+
#[deprecated = "prefer using indexing, e.g., ringbuf[0]"]
150153
pub fn get<'a>(&'a self, i: uint) -> &'a T {
151154
let idx = self.raw_index(i);
152155
match *self.elts.get(idx) {
@@ -169,7 +172,7 @@ impl<T> RingBuf<T> {
169172
/// buf.push(4);
170173
/// buf.push(5);
171174
/// *buf.get_mut(1) = 7;
172-
/// assert_eq!(buf.get(1), &7);
175+
/// assert_eq!(buf[1], 7);
173176
/// ```
174177
pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
175178
let idx = self.raw_index(i);
@@ -195,8 +198,8 @@ impl<T> RingBuf<T> {
195198
/// buf.push(4);
196199
/// buf.push(5);
197200
/// buf.swap(0, 2);
198-
/// assert_eq!(buf.get(0), &5);
199-
/// assert_eq!(buf.get(2), &3);
201+
/// assert_eq!(buf[0], 5);
202+
/// assert_eq!(buf[2], 3);
200203
/// ```
201204
pub fn swap(&mut self, i: uint, j: uint) {
202205
assert!(i < self.len());
@@ -467,6 +470,21 @@ impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
467470
}
468471
}
469472

473+
impl<A> Index<uint, A> for RingBuf<A> {
474+
#[inline]
475+
fn index<'a>(&'a self, i: &uint) -> &'a A {
476+
self.get(*i)
477+
}
478+
}
479+
480+
// FIXME(#12825) Indexing will always try IndexMut first and that causes issues.
481+
/*impl<A> IndexMut<uint, A> for RingBuf<A> {
482+
#[inline]
483+
fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut A {
484+
self.get_mut(*index)
485+
}
486+
}*/
487+
470488
impl<A> FromIterator<A> for RingBuf<A> {
471489
fn from_iter<T: Iterator<A>>(iterator: T) -> RingBuf<A> {
472490
let (lower, _) = iterator.size_hint();
@@ -644,6 +662,25 @@ mod tests {
644662
}
645663
}
646664

665+
#[test]
666+
fn test_index() {
667+
let mut deq = RingBuf::new();
668+
for i in range(1u, 4) {
669+
deq.push_front(i);
670+
}
671+
assert_eq!(deq[1], 2);
672+
}
673+
674+
#[test]
675+
#[should_fail]
676+
fn test_index_out_of_bounds() {
677+
let mut deq = RingBuf::new();
678+
for i in range(1u, 4) {
679+
deq.push_front(i);
680+
}
681+
deq[3];
682+
}
683+
647684
#[bench]
648685
fn bench_new(b: &mut test::Bencher) {
649686
b.iter(|| {

0 commit comments

Comments
 (0)