From 805352fa1ba4b1cf25c96dbf6c85db6a644941b2 Mon Sep 17 00:00:00 2001 From: Derek Harland Date: Thu, 31 Jul 2014 15:57:29 +1200 Subject: [PATCH] Implement slice::Vector for Option and CVec --- src/libcore/option.rs | 21 ++++++++++++--------- src/libstd/c_vec.rs | 17 ++++++++++------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 84b402a68dd12..f8293aeb03d19 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -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; @@ -216,15 +217,6 @@ impl Option { match *self { Some(ref mut x) => Some(x), None => None } } - /// Convert from `Option` 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` to `&mut [T]` (without copying) #[inline] pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] { @@ -526,6 +518,17 @@ impl Option { // Trait implementations ///////////////////////////////////////////////////////////////////////////// +impl Vector for Option { + /// Convert from `Option` to `&[T]` (without copying) + #[inline] + fn as_slice<'a>(&'a self) -> &'a [T] { + match *self { + Some(ref x) => slice::ref_slice(x), + None => &[] + } + } +} + impl Default for Option { #[inline] fn default() -> Option { None } diff --git a/src/libstd/c_vec.rs b/src/libstd/c_vec.rs index a7d697c8665ef..80fe05fcea5cd 100644 --- a/src/libstd/c_vec.rs +++ b/src/libstd/c_vec.rs @@ -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 { @@ -101,13 +102,6 @@ impl CVec { } } - /// 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 { @@ -151,6 +145,15 @@ impl CVec { } } +impl Vector for CVec { + /// 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 Collection for CVec { fn len(&self) -> uint { self.len } }