Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement slice::Vector for Option<T> and CVec<T> #16136

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 12 additions & 9 deletions src/libcore/option.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@

use cmp::{PartialEq, Eq, Ord};
use default::Default;
use slice::Vector;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use mem;
use slice;
Expand Down Expand Up @@ -216,15 +217,6 @@ impl<T> Option<T> {
match *self { Some(ref mut x) => Some(x), None => None }
}

/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
pub fn as_slice<'r>(&'r self) -> &'r [T] {
match *self {
Some(ref x) => slice::ref_slice(x),
None => &[]
}
}

/// Convert from `Option<T>` to `&mut [T]` (without copying)
#[inline]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
Expand Down Expand Up @@ -526,6 +518,17 @@ impl<T: Default> Option<T> {
// Trait implementations
/////////////////////////////////////////////////////////////////////////////

impl<T> Vector<T> for Option<T> {
/// Convert from `Option<T>` to `&[T]` (without copying)
#[inline]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Some(ref x) => slice::ref_slice(x),
None => &[]
}
}
}

impl<T> Default for Option<T> {
#[inline]
fn default() -> Option<T> { None }
Expand Down
17 changes: 10 additions & 7 deletions src/libstd/c_vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ use option::{Option, Some, None};
use ptr::RawPtr;
use ptr;
use raw;
use slice::Vector;

/// The type representing a foreign chunk of memory
pub struct CVec<T> {
Expand Down Expand Up @@ -101,13 +102,6 @@ impl<T> CVec<T> {
}
}

/// View the stored data as a slice.
pub fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}

/// View the stored data as a mutable slice.
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
unsafe {
Expand Down Expand Up @@ -151,6 +145,15 @@ impl<T> CVec<T> {
}
}

impl<T> Vector<T> for CVec<T> {
/// View the stored data as a slice.
fn as_slice<'a>(&'a self) -> &'a [T] {
unsafe {
mem::transmute(raw::Slice { data: self.base as *const T, len: self.len })
}
}
}

impl<T> Collection for CVec<T> {
fn len(&self) -> uint { self.len }
}
Expand Down