use std::fmt;
use std::hash;
use std::ops;
pub trait IntoVector<T> {
fn into_vec(self) -> Vec<T>;
}
impl<T> IntoVector<T> for Vec<T> {
fn into_vec(self) -> Vec<T> { self }
}
impl<'a, T: Clone> IntoVector<T> for &'a [T] {
fn into_vec(self) -> Vec<T> { self.to_vec() }
}
impl<'a> IntoVector<u8> for &'a str {
fn into_vec(self) -> Vec<u8> { self.into_string().into_bytes() }
}
impl<'a> IntoVector<u8> for String {
fn into_vec(self) -> Vec<u8> { self.into_bytes() }
}
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct ByteString(Vec<u8>);
impl ByteString {
pub fn from_bytes<S: IntoVector<u8>>(bs: S) -> ByteString {
ByteString(bs.into_vec())
}
pub fn into_bytes(self) -> Vec<u8> {
self.0
}
pub fn as_bytes<'a>(&'a self) -> &'a [u8] {
&**self
}
pub fn into_utf8_string(self) -> Result<String, ByteString> {
String::from_utf8(self.into_bytes()).map_err(ByteString)
}
pub fn len(&self) -> uint {
self.as_bytes().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl fmt::Show for ByteString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self[])
}
}
impl AsSlice<u8> for ByteString {
#[inline]
fn as_slice<'a>(&'a self) -> &'a [u8] {
self.as_bytes()
}
}
impl Deref<[u8]> for ByteString {
fn deref<'a>(&'a self) -> &'a [u8] {
&*self.0
}
}
impl ops::Slice<uint, [u8]> for ByteString {
#[inline]
fn as_slice_<'a>(&'a self) -> &'a [u8] {
self.as_slice()
}
#[inline]
fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [u8] {
self.as_slice().slice_from_or_fail(start)
}
#[inline]
fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [u8] {
self.as_slice().slice_to_or_fail(end)
}
#[inline]
fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [u8] {
self.as_slice().slice_or_fail(start, end)
}
}
impl<H: hash::Writer> hash::Hash<H> for ByteString {
fn hash(&self, hasher: &mut H) {
self.as_slice().hash(hasher);
}
}
impl<S: Str> Equiv<S> for ByteString {
fn equiv(&self, other: &S) -> bool {
self.as_bytes() == other.as_slice().as_bytes()
}
}
impl FromIterator<u8> for ByteString {
fn from_iter<I: Iterator<u8>>(mut it: I) -> ByteString {
ByteString::from_bytes(it.collect::<Vec<_>>())
}
}