#![allow(unused_imports)]
use std::borrow::Cow;
use std::error;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::iter;
use std::ops;
use std::path::{Path, PathBuf};
use std::ptr;
use std::str;
use std::vec;
use ext_slice::ByteSlice;
use utf8::{self, Utf8Error};
#[inline]
pub fn concat<T, I>(elements: I) -> Vec<u8>
where
T: AsRef<[u8]>,
I: IntoIterator<Item = T>,
{
let mut dest = vec![];
for element in elements {
dest.push_str(element);
}
dest
}
#[inline]
pub fn join<B, T, I>(separator: B, elements: I) -> Vec<u8>
where
B: AsRef<[u8]>,
T: AsRef<[u8]>,
I: IntoIterator<Item = T>,
{
let mut it = elements.into_iter();
let mut dest = vec![];
match it.next() {
None => return dest,
Some(first) => {
dest.push_str(first);
}
}
for element in it {
dest.push_str(&separator);
dest.push_str(element);
}
dest
}
impl ByteVec for Vec<u8> {
#[inline]
fn as_vec(&self) -> &Vec<u8> {
self
}
#[inline]
fn as_vec_mut(&mut self) -> &mut Vec<u8> {
self
}
#[inline]
fn into_vec(self) -> Vec<u8> {
self
}
}
pub trait Sealed {}
impl Sealed for Vec<u8> {}
pub trait ByteVec: Sealed {
#[doc(hidden)]
fn as_vec(&self) -> &Vec<u8>;
#[doc(hidden)]
fn as_vec_mut(&mut self) -> &mut Vec<u8>;
#[doc(hidden)]
fn into_vec(self) -> Vec<u8>
where
Self: Sized;
fn from_slice<B: AsRef<[u8]>>(bytes: B) -> Vec<u8> {
bytes.as_ref().to_vec()
}
#[inline]
fn from_os_string(os_str: OsString) -> Result<Vec<u8>, OsString> {
#[cfg(unix)]
#[inline]
fn imp(os_str: OsString) -> Result<Vec<u8>, OsString> {
use std::os::unix::ffi::OsStringExt;
Ok(Vec::from(os_str.into_vec()))
}
#[cfg(not(unix))]
#[inline]
fn imp(os_str: OsString) -> Result<Vec<u8>, OsString> {
os_str.into_string().map(Vec::from)
}
imp(os_str)
}
#[inline]
fn from_os_str_lossy<'a>(os_str: &'a OsStr) -> Cow<'a, [u8]> {
#[cfg(unix)]
#[inline]
fn imp<'a>(os_str: &'a OsStr) -> Cow<'a, [u8]> {
use std::os::unix::ffi::OsStrExt;
Cow::Borrowed(os_str.as_bytes())
}
#[cfg(not(unix))]
#[inline]
fn imp<'a>(os_str: &'a OsStr) -> Cow<'a, [u8]> {
match os_str.to_string_lossy() {
Cow::Borrowed(x) => Cow::Borrowed(x.as_bytes()),
Cow::Owned(x) => Cow::Owned(Vec::from(x)),
}
}
imp(os_str)
}
#[inline]
fn from_path_buf(path: PathBuf) -> Result<Vec<u8>, PathBuf> {
Vec::from_os_string(path.into_os_string()).map_err(PathBuf::from)
}
#[inline]
fn from_path_lossy<'a>(path: &'a Path) -> Cow<'a, [u8]> {
Vec::from_os_str_lossy(path.as_os_str())
}
#[inline]
fn push_byte(&mut self, byte: u8) {
self.as_vec_mut().push(byte);
}
#[inline]
fn push_char(&mut self, ch: char) {
if ch.len_utf8() == 1 {
self.push_byte(ch as u8);
return;
}
self.as_vec_mut()
.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes());
}
#[inline]
fn push_str<B: AsRef<[u8]>>(&mut self, bytes: B) {
self.as_vec_mut().extend_from_slice(bytes.as_ref());
}
#[inline]
fn into_string(self) -> Result<String, FromUtf8Error>
where
Self: Sized,
{
match utf8::validate(self.as_vec()) {
Err(err) => {
Err(FromUtf8Error { original: self.into_vec(), err })
}
Ok(()) => {
unsafe { Ok(self.into_string_unchecked()) }
}
}
}
#[inline]
fn into_string_lossy(self) -> String
where
Self: Sized,
{
let v = self.as_vec();
if let Ok(allutf8) = v.to_str() {
return allutf8.to_string();
}
let mut dst = String::with_capacity(v.len());
for ch in v.chars() {
dst.push(ch);
}
dst
}
unsafe fn into_string_unchecked(self) -> String
where
Self: Sized,
{
String::from_utf8_unchecked(self.into_vec())
}
#[inline]
fn into_os_string(self) -> Result<OsString, Vec<u8>>
where
Self: Sized,
{
#[cfg(unix)]
#[inline]
fn imp(v: Vec<u8>) -> Result<OsString, Vec<u8>> {
use std::os::unix::ffi::OsStringExt;
Ok(OsString::from_vec(v))
}
#[cfg(not(unix))]
#[inline]
fn imp(v: Vec<u8>) -> Result<OsString, Vec<u8>> {
match v.into_string() {
Ok(s) => Ok(OsString::from(s)),
Err(err) => Err(err.into_vec()),
}
}
imp(self.into_vec())
}
#[inline]
fn into_os_string_lossy(self) -> OsString
where
Self: Sized,
{
#[cfg(unix)]
#[inline]
fn imp(v: Vec<u8>) -> OsString {
use std::os::unix::ffi::OsStringExt;
OsString::from_vec(v)
}
#[cfg(not(unix))]
#[inline]
fn imp(v: Vec<u8>) -> OsString {
OsString::from(v.into_string_lossy())
}
imp(self.into_vec())
}
#[inline]
fn into_path_buf(self) -> Result<PathBuf, Vec<u8>>
where
Self: Sized,
{
self.into_os_string().map(PathBuf::from)
}
#[inline]
fn into_path_buf_lossy(self) -> PathBuf
where
Self: Sized,
{
PathBuf::from(self.into_os_string_lossy())
}
#[inline]
fn pop_byte(&mut self) -> Option<u8> {
self.as_vec_mut().pop()
}
#[inline]
fn pop_char(&mut self) -> Option<char> {
let (ch, size) = utf8::decode_last_lossy(self.as_vec());
if size == 0 {
return None;
}
let new_len = self.as_vec().len() - size;
self.as_vec_mut().truncate(new_len);
Some(ch)
}
#[inline]
fn remove_char(&mut self, at: usize) -> char {
let (ch, size) = utf8::decode_lossy(&self.as_vec()[at..]);
assert!(
size > 0,
"expected {} to be less than {}",
at,
self.as_vec().len(),
);
self.as_vec_mut().drain(at..at + size);
ch
}
#[inline]
fn insert_char(&mut self, at: usize, ch: char) {
self.insert_str(at, ch.encode_utf8(&mut [0; 4]).as_bytes());
}
#[inline]
fn insert_str<B: AsRef<[u8]>>(&mut self, at: usize, bytes: B) {
let bytes = bytes.as_ref();
let len = self.as_vec().len();
assert!(at <= len, "expected {} to be <= {}", at, len);
self.as_vec_mut().reserve(bytes.len());
unsafe {
ptr::copy(
self.as_vec().as_ptr().add(at),
self.as_vec_mut().as_mut_ptr().add(at + bytes.len()),
len - at,
);
ptr::copy_nonoverlapping(
bytes.as_ptr(),
self.as_vec_mut().as_mut_ptr().add(at),
bytes.len(),
);
self.as_vec_mut().set_len(len + bytes.len());
}
}
#[inline]
fn replace_range<R, B>(&mut self, range: R, replace_with: B)
where
R: ops::RangeBounds<usize>,
B: AsRef<[u8]>,
{
self.as_vec_mut().splice(range, replace_with.as_ref().iter().cloned());
}
#[inline]
fn drain_bytes<R>(&mut self, range: R) -> DrainBytes
where
R: ops::RangeBounds<usize>,
{
DrainBytes { it: self.as_vec_mut().drain(range) }
}
}
#[derive(Debug)]
pub struct DrainBytes<'a> {
it: vec::Drain<'a, u8>,
}
impl<'a> iter::FusedIterator for DrainBytes<'a> {}
impl<'a> Iterator for DrainBytes<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.it.next()
}
}
impl<'a> DoubleEndedIterator for DrainBytes<'a> {
#[inline]
fn next_back(&mut self) -> Option<u8> {
self.it.next_back()
}
}
impl<'a> ExactSizeIterator for DrainBytes<'a> {
#[inline]
fn len(&self) -> usize {
self.it.len()
}
}
#[derive(Debug, Eq, PartialEq)]
pub struct FromUtf8Error {
original: Vec<u8>,
err: Utf8Error,
}
impl FromUtf8Error {
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.original
}
#[inline]
pub fn into_vec(self) -> Vec<u8> {
self.original
}
#[inline]
pub fn utf8_error(&self) -> &Utf8Error {
&self.err
}
}
impl error::Error for FromUtf8Error {
#[inline]
fn description(&self) -> &str {
"invalid UTF-8 vector"
}
}
impl fmt::Display for FromUtf8Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.err)
}
}
#[cfg(test)]
mod tests {
use ext_slice::B;
use ext_vec::ByteVec;
#[test]
fn insert() {
let mut s = vec![];
s.insert_str(0, "foo");
assert_eq!(s, "foo".as_bytes());
let mut s = Vec::from("a");
s.insert_str(0, "foo");
assert_eq!(s, "fooa".as_bytes());
let mut s = Vec::from("a");
s.insert_str(1, "foo");
assert_eq!(s, "afoo".as_bytes());
let mut s = Vec::from("foobar");
s.insert_str(3, "quux");
assert_eq!(s, "fooquuxbar".as_bytes());
let mut s = Vec::from("foobar");
s.insert_str(3, "x");
assert_eq!(s, "fooxbar".as_bytes());
let mut s = Vec::from("foobar");
s.insert_str(0, "x");
assert_eq!(s, "xfoobar".as_bytes());
let mut s = Vec::from("foobar");
s.insert_str(6, "x");
assert_eq!(s, "foobarx".as_bytes());
let mut s = Vec::from("foobar");
s.insert_str(3, "quuxbazquux");
assert_eq!(s, "fooquuxbazquuxbar".as_bytes());
}
#[test]
#[should_panic]
fn insert_fail1() {
let mut s = vec![];
s.insert_str(1, "foo");
}
#[test]
#[should_panic]
fn insert_fail2() {
let mut s = Vec::from("a");
s.insert_str(2, "foo");
}
#[test]
#[should_panic]
fn insert_fail3() {
let mut s = Vec::from("foobar");
s.insert_str(7, "foo");
}
}