Skip to content

Commit eb2fdc8

Browse files
committed
Reinstate AsSlice impls for Option and Result
1 parent 3b0550c commit eb2fdc8

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/libcore/option.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
149149
use mem;
150150
use result::{Result, Ok, Err};
151151
use slice;
152+
use slice::AsSlice;
152153

153154
// Note that this is not a lang item per se, but it has a hidden dependency on
154155
// `Iterator`, which is one. The compiler assumes that the `next` method of
@@ -845,6 +846,21 @@ impl<T: Default> Option<T> {
845846
// Trait implementations
846847
/////////////////////////////////////////////////////////////////////////////
847848

849+
impl<T> AsSlice<T> for Option<T> {
850+
/// Convert from `Option<T>` to `&[T]` (without copying)
851+
#[inline]
852+
#[stable]
853+
fn as_slice<'a>(&'a self) -> &'a [T] {
854+
match *self {
855+
Some(ref x) => slice::ref_slice(x),
856+
None => {
857+
let result: &[_] = &[];
858+
result
859+
}
860+
}
861+
}
862+
}
863+
848864
impl<T> Default for Option<T> {
849865
#[inline]
850866
fn default() -> Option<T> { None }

src/libcore/result.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,7 @@ use clone::Clone;
280280
use cmp::PartialEq;
281281
use std::fmt::Show;
282282
use slice;
283+
use slice::AsSlice;
283284
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
284285
use option::{None, Option, Some};
285286

@@ -839,6 +840,26 @@ impl<T: Show, E> Result<T, E> {
839840
}
840841
}
841842

843+
/////////////////////////////////////////////////////////////////////////////
844+
// Trait implementations
845+
/////////////////////////////////////////////////////////////////////////////
846+
847+
impl<T, E> AsSlice<T> for Result<T, E> {
848+
/// Convert from `Result<T, E>` to `&[T]` (without copying)
849+
#[inline]
850+
#[stable]
851+
fn as_slice<'a>(&'a self) -> &'a [T] {
852+
match *self {
853+
Ok(ref x) => slice::ref_slice(x),
854+
Err(_) => {
855+
// work around lack of implicit coercion from fixed-size array to slice
856+
let emp: &[_] = &[];
857+
emp
858+
}
859+
}
860+
}
861+
}
862+
842863
/////////////////////////////////////////////////////////////////////////////
843864
// The Result Iterator
844865
/////////////////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)