// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::default::Default; use std::fmt; use std::iter::{IntoIterator, FromIterator}; use std::ops::Deref; use std::vec; use serialize::{Encodable, Decodable, Encoder, Decoder}; /// A non-growable owned slice. This is a separate type to allow the /// representation to change. #[derive(Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct OwnedSlice { data: Box<[T]> } impl fmt::Debug for OwnedSlice { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.data.fmt(fmt) } } impl OwnedSlice { pub fn empty() -> OwnedSlice { OwnedSlice { data: Box::new([]) } } #[inline(never)] pub fn from_vec(v: Vec) -> OwnedSlice { OwnedSlice { data: v.into_boxed_slice() } } #[inline(never)] pub fn into_vec(self) -> Vec { self.data.into_vec() } pub fn as_slice<'a>(&'a self) -> &'a [T] { &*self.data } pub fn move_iter(self) -> vec::IntoIter { self.into_vec().into_iter() } pub fn map U>(&self, f: F) -> OwnedSlice { self.iter().map(f).collect() } } impl Deref for OwnedSlice { type Target = [T]; fn deref(&self) -> &[T] { self.as_slice() } } impl Default for OwnedSlice { fn default() -> OwnedSlice { OwnedSlice::empty() } } impl Clone for OwnedSlice { fn clone(&self) -> OwnedSlice { OwnedSlice::from_vec(self.to_vec()) } } impl FromIterator for OwnedSlice { fn from_iter>(iter: I) -> OwnedSlice { OwnedSlice::from_vec(iter.into_iter().collect()) } } impl Encodable for OwnedSlice { fn encode(&self, s: &mut S) -> Result<(), S::Error> { Encodable::encode(&**self, s) } } impl Decodable for OwnedSlice { fn decode(d: &mut D) -> Result, D::Error> { Ok(OwnedSlice::from_vec(match Decodable::decode(d) { Ok(t) => t, Err(e) => return Err(e) })) } }