Skip to content

Commit 2467c6e

Browse files
donkopotamusalexcrichton
authored andcommitted
Implement slice::Vector for Option<T> and CVec<T>
1 parent bc24819 commit 2467c6e

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

src/libcore/option.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,7 @@
143143
144144
use cmp::{PartialEq, Eq, Ord};
145145
use default::Default;
146+
use slice::Vector;
146147
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
147148
use mem;
148149
use slice;
@@ -216,15 +217,6 @@ impl<T> Option<T> {
216217
match *self { Some(ref mut x) => Some(x), None => None }
217218
}
218219

219-
/// Convert from `Option<T>` to `&[T]` (without copying)
220-
#[inline]
221-
pub fn as_slice<'r>(&'r self) -> &'r [T] {
222-
match *self {
223-
Some(ref x) => slice::ref_slice(x),
224-
None => &[]
225-
}
226-
}
227-
228220
/// Convert from `Option<T>` to `&mut [T]` (without copying)
229221
#[inline]
230222
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
@@ -526,6 +518,17 @@ impl<T: Default> Option<T> {
526518
// Trait implementations
527519
/////////////////////////////////////////////////////////////////////////////
528520

521+
impl<T> Vector<T> for Option<T> {
522+
/// Convert from `Option<T>` to `&[T]` (without copying)
523+
#[inline]
524+
fn as_slice<'a>(&'a self) -> &'a [T] {
525+
match *self {
526+
Some(ref x) => slice::ref_slice(x),
527+
None => &[]
528+
}
529+
}
530+
}
531+
529532
impl<T> Default for Option<T> {
530533
#[inline]
531534
fn default() -> Option<T> { None }

src/libstd/c_vec.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ use option::{Option, Some, None};
4343
use ptr::RawPtr;
4444
use ptr;
4545
use raw;
46+
use slice::Vector;
4647

4748
/// The type representing a foreign chunk of memory
4849
pub struct CVec<T> {
@@ -101,13 +102,6 @@ impl<T> CVec<T> {
101102
}
102103
}
103104

104-
/// View the stored data as a slice.
105-
pub fn as_slice<'a>(&'a self) -> &'a [T] {
106-
unsafe {
107-
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
108-
}
109-
}
110-
111105
/// View the stored data as a mutable slice.
112106
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
113107
unsafe {
@@ -151,6 +145,15 @@ impl<T> CVec<T> {
151145
}
152146
}
153147

148+
impl<T> Vector<T> for CVec<T> {
149+
/// View the stored data as a slice.
150+
fn as_slice<'a>(&'a self) -> &'a [T] {
151+
unsafe {
152+
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
153+
}
154+
}
155+
}
156+
154157
impl<T> Collection for CVec<T> {
155158
fn len(&self) -> uint { self.len }
156159
}

0 commit comments

Comments
 (0)