1
Fork 0

std: Make ~[T] no longer a growable vector

This removes all resizability support for ~[T] vectors in preparation of DST.
The only growable vector remaining is Vec<T>. In summary, the following methods
from ~[T] and various functions were removed. Each method/function has an
equivalent on the Vec type in std::vec unless otherwise stated.

* slice::OwnedCloneableVector
* slice::OwnedEqVector
* slice::append
* slice::append_one
* slice::build (no replacement)
* slice::bytes::push_bytes
* slice::from_elem
* slice::from_fn
* slice::with_capacity
* ~[T].capacity()
* ~[T].clear()
* ~[T].dedup()
* ~[T].extend()
* ~[T].grow()
* ~[T].grow_fn()
* ~[T].grow_set()
* ~[T].insert()
* ~[T].pop()
* ~[T].push()
* ~[T].push_all()
* ~[T].push_all_move()
* ~[T].remove()
* ~[T].reserve()
* ~[T].reserve_additional()
* ~[T].reserve_exect()
* ~[T].retain()
* ~[T].set_len()
* ~[T].shift()
* ~[T].shrink_to_fit()
* ~[T].swap_remove()
* ~[T].truncate()
* ~[T].unshift()
* ~str.clear()
* ~str.set_len()
* ~str.truncate()

Note that no other API changes were made. Existing apis that took or returned
~[T] continue to do so.

[breaking-change]
This commit is contained in:
Alex Crichton 2014-04-17 15:28:14 -07:00
parent ce2bab68d6
commit 7d3b0bf391
28 changed files with 344 additions and 1001 deletions

View file

@ -30,7 +30,6 @@ use rt::task::{Task, BlockedTask};
use rt::thread::Thread;
use sync::atomics;
use unstable::mutex::NativeMutex;
use slice::OwnedVector;
use mpsc = sync::mpsc_queue;

View file

@ -30,7 +30,6 @@ use rt::task::{Task, BlockedTask};
use rt::thread::Thread;
use spsc = sync::spsc_queue;
use sync::atomics;
use slice::OwnedVector;
static DISCONNECTED: int = int::MIN;
#[cfg(test)]

View file

@ -359,13 +359,8 @@ pub fn hash_with_keys<T: Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 {
#[cfg(test)]
mod tests {
extern crate test;
use io::Writer;
use iter::Iterator;
use prelude::*;
use num::ToStrRadix;
use option::{Some, None};
use str::Str;
use strbuf::StrBuf;
use slice::{Vector, ImmutableVector, OwnedVector};
use self::test::Bencher;
use super::super::Hash;
@ -454,7 +449,7 @@ mod tests {
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut buf = Vec::new();
let mut t = 0;
let mut state_inc = SipState::new_with_keys(k0, k1);
let mut state_full = SipState::new_with_keys(k0, k1);
@ -496,7 +491,7 @@ mod tests {
assert_eq!(vec, out);
state_full.reset();
state_full.write(buf);
state_full.write(buf.as_slice());
let f = result_str(state_full.result());
let i = result_str(state_inc.result());
let v = to_hex_str(&vecs[t]);

View file

@ -17,7 +17,7 @@ use iter::ExactSize;
use ops::Drop;
use option::{Some, None, Option};
use result::{Ok, Err};
use slice::{OwnedVector, ImmutableVector, MutableVector};
use slice::{ImmutableVector, MutableVector};
use slice;
use vec::Vec;
@ -391,7 +391,7 @@ mod test {
/// A dummy reader intended at testing short-reads propagation.
pub struct ShortReader {
lengths: ~[uint],
lengths: Vec<uint>,
}
impl Reader for ShortReader {
@ -554,7 +554,7 @@ mod test {
#[test]
fn test_short_reads() {
let inner = ShortReader{lengths: ~[0, 1, 2, 0, 1, 0]};
let inner = ShortReader{lengths: vec![0, 1, 2, 0, 1, 0]};
let mut reader = BufferedReader::new(inner);
let mut buf = [0, 0];
assert_eq!(reader.read(buf), Ok(0));

View file

@ -21,7 +21,7 @@ use option::{Option, Some, None};
use result::{Ok, Err};
use io;
use io::{IoError, IoResult, Reader};
use slice::{OwnedVector, ImmutableVector, Vector};
use slice::{ImmutableVector, Vector};
use ptr::RawPtr;
/// An iterator that reads a single byte on each iteration,
@ -503,21 +503,22 @@ mod test {
#[cfg(test)]
mod bench {
extern crate test;
use self::test::Bencher;
use container::Container;
use prelude::*;
use self::test::Bencher;
macro_rules! u64_from_be_bytes_bench_impl(
($size:expr, $stride:expr, $start_index:expr) =>
({
use slice;
use super::u64_from_be_bytes;
let data = slice::from_fn($stride*100+$start_index, |i| i as u8);
let data = Vec::from_fn($stride*100+$start_index, |i| i as u8);
let mut sum = 0u64;
b.iter(|| {
let mut i = $start_index;
while i < data.len() {
sum += u64_from_be_bytes(data, i, $size);
sum += u64_from_be_bytes(data.as_slice(), i, $size);
i += $stride;
}
});

View file

@ -17,7 +17,7 @@ use result::{Err, Ok};
use io;
use io::{Reader, Writer, Seek, Buffer, IoError, SeekStyle, IoResult};
use slice;
use slice::{Vector, ImmutableVector, MutableVector, OwnedCloneableVector};
use slice::{Vector, ImmutableVector, MutableVector};
use vec::Vec;
fn combine(seek: SeekStyle, cur: uint, end: uint, offset: i64) -> IoResult<u64> {

View file

@ -228,11 +228,11 @@ use os;
use option::{Option, Some, None};
use path::Path;
use result::{Ok, Err, Result};
use str::{StrSlice, OwnedStr};
use str::StrSlice;
use str;
use uint;
use unstable::finally::try_finally;
use slice::{Vector, OwnedVector, MutableVector, ImmutableVector, OwnedCloneableVector};
use slice::{Vector, MutableVector, ImmutableVector};
use vec::Vec;
// Reexports

View file

@ -16,6 +16,7 @@ use fmt;
use io::IoResult;
use io;
use libc;
use mem;
use rt::rtio::{RtioProcess, IoFactory, LocalIo};
/// Signal a process to exit, without forcibly killing it. Corresponds to
@ -416,12 +417,7 @@ impl Drop for Process {
drop(self.stdin.take());
drop(self.stdout.take());
drop(self.stderr.take());
loop {
match self.extra_io.pop() {
Some(_) => (),
None => break,
}
}
drop(mem::replace(&mut self.extra_io, ~[]));
self.wait();
}

View file

@ -28,7 +28,7 @@ use mem::drop;
use option::{Some, None};
use result::{Ok, Err};
use rt::rtio::{IoFactory, LocalIo, RtioSignal};
use slice::{ImmutableVector, OwnedVector};
use slice::ImmutableVector;
use vec::Vec;
/// Signals that can be sent and received

View file

@ -46,7 +46,7 @@ use kinds::Send;
use mem::replace;
use option::{None, Option, Some};
use rt::task::{Task, LocalStorage};
use slice::{ImmutableVector, MutableVector, OwnedVector};
use slice::{ImmutableVector, MutableVector};
use vec::Vec;
/**

View file

@ -277,13 +277,13 @@ impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
let mut buf: ~[u8] = ~[];
let mut buf = Vec::new();
strconv::int_to_str_bytes_common(*self, radix, strconv::SignNeg, |i| {
buf.push(i);
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
unsafe { str::raw::from_utf8_owned(buf) }
unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
}
}

View file

@ -1779,12 +1779,11 @@ mod bench {
extern crate test;
use self::test::Bencher;
use num;
use slice;
use prelude::*;
#[bench]
fn bench_pow_function(b: &mut Bencher) {
let v = slice::from_fn(1024, |n| n);
let v = Vec::from_fn(1024, |n| n);
b.iter(|| {v.iter().fold(0, |old, new| num::pow(old, *new));});
}
}

View file

@ -10,19 +10,21 @@
#![allow(missing_doc)]
use char;
use clone::Clone;
use container::Container;
use std::cmp::{Ord, Eq};
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use char;
use str::{StrSlice};
use str;
use slice::{CloneableVector, ImmutableVector, MutableVector};
use slice::OwnedVector;
use num;
use iter::Iterator;
use num::{NumCast, Zero, One, cast, Int};
use num::{Round, Float, FPNaN, FPInfinite, ToPrimitive};
use num;
use ops::{Add, Sub, Mul, Div, Rem, Neg};
use option::{None, Option, Some};
use slice::OwnedVector;
use slice::{CloneableVector, ImmutableVector, MutableVector};
use std::cmp::{Ord, Eq};
use str::{StrSlice};
use str;
use vec::Vec;
/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
@ -293,7 +295,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
}
let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
let mut buf: ~[u8] = ~[];
let mut buf = Vec::new();
let radix_gen: T = cast(radix as int).unwrap();
let (num, exp) = match exp_format {
@ -411,23 +413,23 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
// If reached left end of number, have to
// insert additional digit:
if i < 0
|| buf[i as uint] == '-' as u8
|| buf[i as uint] == '+' as u8 {
|| *buf.get(i as uint) == '-' as u8
|| *buf.get(i as uint) == '+' as u8 {
buf.insert((i + 1) as uint, value2ascii(1));
break;
}
// Skip the '.'
if buf[i as uint] == '.' as u8 { i -= 1; continue; }
if *buf.get(i as uint) == '.' as u8 { i -= 1; continue; }
// Either increment the digit,
// or set to 0 if max and carry the 1.
let current_digit = ascii2value(buf[i as uint]);
let current_digit = ascii2value(*buf.get(i as uint));
if current_digit < (radix - 1) {
buf[i as uint] = value2ascii(current_digit+1);
*buf.get_mut(i as uint) = value2ascii(current_digit+1);
break;
} else {
buf[i as uint] = value2ascii(0);
*buf.get_mut(i as uint) = value2ascii(0);
i -= 1;
}
}
@ -444,25 +446,25 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
let mut i = buf_max_i;
// discover trailing zeros of fractional part
while i > start_fractional_digits && buf[i] == '0' as u8 {
while i > start_fractional_digits && *buf.get(i) == '0' as u8 {
i -= 1;
}
// Only attempt to truncate digits if buf has fractional digits
if i >= start_fractional_digits {
// If buf ends with '.', cut that too.
if buf[i] == '.' as u8 { i -= 1 }
if *buf.get(i) == '.' as u8 { i -= 1 }
// only resize buf if we actually remove digits
if i < buf_max_i {
buf = buf.slice(0, i + 1).to_owned();
buf = Vec::from_slice(buf.slice(0, i + 1));
}
}
} // If exact and trailing '.', just cut that
else {
let max_i = buf.len() - 1;
if buf[max_i] == '.' as u8 {
buf = buf.slice(0, max_i).to_owned();
if *buf.get(max_i) == '.' as u8 {
buf = Vec::from_slice(buf.slice(0, max_i));
}
}
@ -481,7 +483,7 @@ pub fn float_to_str_bytes_common<T:NumCast+Zero+One+Eq+Ord+Float+Round+
}
}
(buf, false)
(buf.move_iter().collect(), false)
}
/**

View file

@ -191,13 +191,13 @@ impl ToStrRadix for $T {
/// Convert to a string in a given base.
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
let mut buf = ~[];
let mut buf = Vec::new();
strconv::int_to_str_bytes_common(*self, radix, strconv::SignNone, |i| {
buf.push(i);
});
// We know we generated valid utf-8, so we don't need to go through that
// check.
unsafe { str::raw::from_utf8_owned(buf) }
unsafe { str::raw::from_utf8_owned(buf.move_iter().collect()) }
}
}

View file

@ -28,7 +28,6 @@
#![allow(missing_doc)]
#[cfg(target_os = "macos")]
#[cfg(windows)]
use iter::range;
@ -49,6 +48,7 @@ use path::{Path, GenericPath};
use iter::Iterator;
use slice::{Vector, CloneableVector, ImmutableVector, MutableVector, OwnedVector};
use ptr::RawPtr;
use vec::Vec;
#[cfg(unix)]
use c_str::ToCStr;
@ -203,7 +203,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
result
}
#[cfg(unix)]
unsafe fn get_env_pairs() -> ~[~[u8]] {
unsafe fn get_env_pairs() -> Vec<~[u8]> {
use c_str::CString;
extern {
@ -214,7 +214,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
fail!("os::env() failure getting env string from OS: {}",
os::last_os_error());
}
let mut result = ~[];
let mut result = Vec::new();
ptr::array_each(environ, |e| {
let env_pair = CString::new(e, false).as_bytes_no_nul().to_owned();
result.push(env_pair);
@ -222,8 +222,8 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
result
}
fn env_convert(input: ~[~[u8]]) -> ~[(~[u8], ~[u8])] {
let mut pairs = ~[];
fn env_convert(input: Vec<~[u8]>) -> Vec<(~[u8], ~[u8])> {
let mut pairs = Vec::new();
for p in input.iter() {
let vs: ~[&[u8]] = p.splitn(1, |b| *b == '=' as u8).collect();
let key = vs[0].to_owned();
@ -234,7 +234,7 @@ pub fn env_as_bytes() -> ~[(~[u8],~[u8])] {
}
with_env_lock(|| {
let unparsed_environ = get_env_pairs();
env_convert(unparsed_environ)
env_convert(unparsed_environ).move_iter().collect()
})
}
}
@ -457,15 +457,14 @@ pub fn self_exe_name() -> Option<Path> {
fn load_self() -> Option<~[u8]> {
unsafe {
use libc::funcs::extra::_NSGetExecutablePath;
use slice;
let mut sz: u32 = 0;
_NSGetExecutablePath(ptr::mut_null(), &mut sz);
if sz == 0 { return None; }
let mut v: ~[u8] = slice::with_capacity(sz as uint);
let mut v: Vec<u8> = Vec::with_capacity(sz as uint);
let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz);
if err != 0 { return None; }
v.set_len(sz as uint - 1); // chop off trailing NUL
Some(v)
Some(v.move_iter().collect())
}
}
@ -795,11 +794,9 @@ pub fn get_exit_status() -> int {
unsafe fn load_argc_and_argv(argc: int, argv: **c_char) -> ~[~[u8]] {
use c_str::CString;
let mut args = ~[];
for i in range(0u, argc as uint) {
args.push(CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned())
}
args
Vec::from_fn(argc as uint, |i| {
CString::new(*argv.offset(i as int), false).as_bytes_no_nul().to_owned()
}).move_iter().collect()
}
/**

View file

@ -74,7 +74,7 @@ use option::{Option, None, Some};
use str;
use str::{MaybeOwned, Str, StrSlice, from_utf8_lossy};
use strbuf::StrBuf;
use slice::{OwnedCloneableVector, OwnedVector, Vector};
use slice::Vector;
use slice::{ImmutableEqVector, ImmutableVector};
use vec::Vec;

View file

@ -21,7 +21,7 @@ use option::{Option, None, Some};
use str;
use str::Str;
use slice::{CloneableVector, RevSplits, Splits, Vector, VectorVector,
ImmutableEqVector, OwnedVector, ImmutableVector, OwnedCloneableVector};
ImmutableEqVector, OwnedVector, ImmutableVector};
use vec::Vec;
use super::{BytesContainer, GenericPath, GenericPathUnsafe};

View file

@ -21,7 +21,7 @@ use io::Writer;
use iter::{AdditiveIterator, DoubleEndedIterator, Extendable, Rev, Iterator, Map};
use option::{Option, Some, None};
use slice::{Vector, OwnedVector, ImmutableVector};
use str::{CharSplits, OwnedStr, Str, StrVector, StrSlice};
use str::{CharSplits, Str, StrVector, StrSlice};
use strbuf::StrBuf;
use vec::Vec;

View file

@ -56,7 +56,7 @@ pub use tuple::{Tuple1, Tuple2, Tuple3, Tuple4};
pub use tuple::{Tuple5, Tuple6, Tuple7, Tuple8};
pub use tuple::{Tuple9, Tuple10, Tuple11, Tuple12};
pub use slice::{ImmutableEqVector, ImmutableTotalOrdVector, ImmutableCloneableVector};
pub use slice::{OwnedVector, OwnedCloneableVector, OwnedEqVector};
pub use slice::{OwnedVector};
pub use slice::{MutableVector, MutableTotalOrdVector};
pub use slice::{Vector, VectorVector, CloneableVector, ImmutableVector};
pub use strbuf::StrBuf;

View file

@ -170,10 +170,9 @@ pub fn mut_null<T>() -> *mut T { 0 as *mut T }
///
/// ```
/// use std::ptr;
/// use std::slice;
///
/// unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
/// let mut dst = slice::with_capacity(elts);
/// unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> Vec<T> {
/// let mut dst = Vec::with_capacity(elts);
/// dst.set_len(elts);
/// ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
/// dst

View file

@ -28,7 +28,7 @@ use reflect::{MovePtr, align};
use result::{Ok, Err};
use str::StrSlice;
use to_str::ToStr;
use slice::{Vector, OwnedVector};
use slice::Vector;
use intrinsics::{Disr, Opaque, TyDesc, TyVisitor, get_tydesc, visit_tydesc};
use raw;
use vec::Vec;

View file

@ -125,13 +125,14 @@ mod imp {
unsafe fn load_argc_and_argv(argc: int, argv: **u8) -> ~[~[u8]] {
use c_str::CString;
use ptr::RawPtr;
use {slice, libc};
use libc;
use slice::CloneableVector;
use vec::Vec;
slice::from_fn(argc as uint, |i| {
Vec::from_fn(argc as uint, |i| {
let cs = CString::new(*(argv as **libc::c_char).offset(i as int), false);
cs.as_bytes_no_nul().to_owned()
})
}).move_iter().collect()
}
#[cfg(test)]

File diff suppressed because it is too large Load diff

View file

@ -80,7 +80,7 @@ use char;
use char::Char;
use clone::Clone;
use cmp::{Eq, TotalEq, Ord, TotalOrd, Equiv, Ordering};
use container::{Container, Mutable};
use container::Container;
use fmt;
use io::Writer;
use iter::{Iterator, FromIterator, Extendable, range};
@ -92,7 +92,7 @@ use option::{None, Option, Some};
use ptr;
use from_str::FromStr;
use slice;
use slice::{OwnedVector, OwnedCloneableVector, ImmutableVector, MutableVector};
use slice::{OwnedVector, ImmutableVector, MutableVector};
use slice::{Vector};
use vec::Vec;
use default::Default;
@ -588,7 +588,7 @@ enum NormalizationForm {
pub struct Normalizations<'a> {
kind: NormalizationForm,
iter: Chars<'a>,
buffer: ~[(char, u8)],
buffer: Vec<(char, u8)>,
sorted: bool
}
@ -597,7 +597,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
fn next(&mut self) -> Option<char> {
use unicode::decompose::canonical_combining_class;
match self.buffer.head() {
match self.buffer.as_slice().head() {
Some(&(c, 0)) => {
self.sorted = false;
self.buffer.shift();
@ -622,7 +622,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
decomposer(ch, |d| {
let class = canonical_combining_class(d);
if class == 0 && !*sorted {
canonical_sort(*buffer);
canonical_sort(buffer.as_mut_slice());
*sorted = true;
}
buffer.push((d, class));
@ -632,7 +632,7 @@ impl<'a> Iterator<char> for Normalizations<'a> {
}
if !self.sorted {
canonical_sort(self.buffer);
canonical_sort(self.buffer.as_mut_slice());
self.sorted = true;
}
@ -1336,22 +1336,23 @@ impl<'a> fmt::Show for MaybeOwned<'a> {
pub mod raw {
use cast;
use container::Container;
use iter::Iterator;
use libc;
use ptr;
use ptr::RawPtr;
use str::{is_utf8, OwnedStr, StrSlice};
use slice;
use slice::{MutableVector, ImmutableVector, OwnedVector};
use ptr;
use raw::Slice;
use slice::{MutableVector, ImmutableVector, OwnedVector, Vector};
use str::{is_utf8, StrSlice};
use vec::Vec;
/// Create a Rust string from a *u8 buffer of the given length
pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str {
let mut v: ~[u8] = slice::with_capacity(len);
let mut v = Vec::with_capacity(len);
ptr::copy_memory(v.as_mut_ptr(), buf, len);
v.set_len(len);
assert!(is_utf8(v));
::cast::transmute(v)
assert!(is_utf8(v.as_slice()));
::cast::transmute(v.move_iter().collect::<~[u8]>())
}
#[lang="strdup_uniq"]
@ -1594,16 +1595,6 @@ impl Container for ~str {
fn len(&self) -> uint { self.as_slice().len() }
}
impl Mutable for ~str {
/// Remove all content, make the string empty
#[inline]
fn clear(&mut self) {
unsafe {
self.set_len(0)
}
}
}
/// Methods for string slices
pub trait StrSlice<'a> {
/// Returns true if one string contains another
@ -2396,7 +2387,7 @@ impl<'a> StrSlice<'a> for &'a str {
fn nfd_chars(&self) -> Normalizations<'a> {
Normalizations {
iter: self.chars(),
buffer: ~[],
buffer: Vec::new(),
sorted: false,
kind: NFD
}
@ -2406,7 +2397,7 @@ impl<'a> StrSlice<'a> for &'a str {
fn nfkd_chars(&self) -> Normalizations<'a> {
Normalizations {
iter: self.chars(),
buffer: ~[],
buffer: Vec::new(),
sorted: false,
kind: NFKD
}
@ -2544,22 +2535,22 @@ impl<'a> StrSlice<'a> for &'a str {
fn to_owned(&self) -> ~str {
let len = self.len();
unsafe {
let mut v = slice::with_capacity(len);
let mut v = Vec::with_capacity(len);
ptr::copy_memory(v.as_mut_ptr(), self.as_ptr(), len);
v.set_len(len);
::cast::transmute(v)
::cast::transmute(v.move_iter().collect::<~[u8]>())
}
}
fn to_utf16(&self) -> ~[u16] {
let mut u = ~[];
let mut u = Vec::new();;
for ch in self.chars() {
let mut buf = [0u16, ..2];
let n = ch.encode_utf16(buf /* as mut slice! */);
u.push_all(buf.slice_to(n));
}
u
u.move_iter().collect()
}
#[inline]
@ -2694,29 +2685,30 @@ impl<'a> StrSlice<'a> for &'a str {
if slen == 0 { return tlen; }
if tlen == 0 { return slen; }
let mut dcol = slice::from_fn(tlen + 1, |x| x);
let mut dcol = Vec::from_fn(tlen + 1, |x| x);
for (i, sc) in self.chars().enumerate() {
let mut current = i;
dcol[0] = current + 1;
*dcol.get_mut(0) = current + 1;
for (j, tc) in t.chars().enumerate() {
let next = dcol[j + 1];
let next = *dcol.get(j + 1);
if sc == tc {
dcol[j + 1] = current;
*dcol.get_mut(j + 1) = current;
} else {
dcol[j + 1] = ::cmp::min(current, next);
dcol[j + 1] = ::cmp::min(dcol[j + 1], dcol[j]) + 1;
*dcol.get_mut(j + 1) = ::cmp::min(current, next);
*dcol.get_mut(j + 1) = ::cmp::min(*dcol.get(j + 1),
*dcol.get(j)) + 1;
}
current = next;
}
}
return dcol[tlen];
return *dcol.get(tlen);
}
fn subslice_offset(&self, inner: &str) -> uint {
@ -2738,43 +2730,21 @@ impl<'a> StrSlice<'a> for &'a str {
/// Methods for owned strings
pub trait OwnedStr {
/// Shorten a string to the specified length (which must be <= the current length)
fn truncate(&mut self, len: uint);
/// Consumes the string, returning the underlying byte buffer.
///
/// The buffer does not have a null terminator.
fn into_bytes(self) -> ~[u8];
/// Sets the length of a string
///
/// This will explicitly set the size of the string, without actually
/// modifying its buffers, so it is up to the caller to ensure that
/// the string is actually the specified size.
unsafe fn set_len(&mut self, new_len: uint);
/// Pushes the given string onto this string, returning the concatenation of the two strings.
fn append(self, rhs: &str) -> ~str;
}
impl OwnedStr for ~str {
#[inline]
fn truncate(&mut self, len: uint) {
assert!(len <= self.len());
assert!(self.is_char_boundary(len));
unsafe { self.set_len(len); }
}
#[inline]
fn into_bytes(self) -> ~[u8] {
unsafe { cast::transmute(self) }
}
#[inline]
unsafe fn set_len(&mut self, new_len: uint) {
raw::as_owned_vec(self).set_len(new_len)
}
#[inline]
fn append(self, rhs: &str) -> ~str {
let mut new_str = StrBuf::from_owned_str(self);
@ -3409,8 +3379,7 @@ mod tests {
assert_eq!(a.subslice_offset(c), 0);
let string = "a\nb\nc";
let mut lines = ~[];
for line in string.lines() { lines.push(line) }
let lines: ~[&str] = string.lines().collect();
assert_eq!(string.subslice_offset(lines[0]), 0);
assert_eq!(string.subslice_offset(lines[1]), 2);
assert_eq!(string.subslice_offset(lines[2]), 4);
@ -4259,9 +4228,9 @@ mod bench {
#[bench]
fn from_utf8_lossy_100_invalid(b: &mut Bencher) {
let s = ::slice::from_elem(100, 0xF5u8);
let s = Vec::from_elem(100, 0xF5u8);
b.iter(|| {
let _ = from_utf8_lossy(s);
let _ = from_utf8_lossy(s.as_slice());
});
}

View file

@ -23,12 +23,13 @@
use cast;
use clone::Clone;
use iter::Iterator;
use kinds::Send;
use ops::Drop;
use ptr::RawPtr;
use sync::atomics::{fence, AtomicUint, Relaxed, Acquire, Release};
use slice;
use ty::Unsafe;
use vec::Vec;
/// An atomically reference counted pointer.
///
@ -73,7 +74,8 @@ impl<T: Send> UnsafeArc<T> {
~[] // need to free data here
} else {
let ptr = new_inner(data, num_handles);
slice::from_fn(num_handles, |_| UnsafeArc { data: ptr })
let v = Vec::from_fn(num_handles, |_| UnsafeArc { data: ptr });
v.move_iter().collect()
}
}
}

View file

@ -61,7 +61,7 @@ use ptr::RawPtr;
use sync::arc::UnsafeArc;
use sync::atomics::{AtomicInt, AtomicPtr, SeqCst};
use unstable::sync::Exclusive;
use slice::{OwnedVector, ImmutableVector};
use slice::ImmutableVector;
use vec::Vec;
// Once the queue is less than 1/K full, then it will be downsized. Note that

View file

@ -115,7 +115,7 @@ mod tests {
#[test]
fn exclusive_new_arc() {
unsafe {
let mut futures = ~[];
let mut futures = Vec::new();
let num_tasks = 10;
let count = 10;

View file

@ -614,13 +614,9 @@ impl<T> Vec<T> {
/// ```
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
// See the comment in as_slice() for what's going on here.
let slice = if mem::size_of::<T>() == 0 {
Slice { data: 1 as *T, len: self.len }
} else {
Slice { data: self.ptr as *T, len: self.len }
};
unsafe { transmute(slice) }
unsafe {
transmute(Slice { data: self.as_mut_ptr() as *T, len: self.len })
}
}
/// Creates a consuming iterator, that is, one that moves each
@ -1143,7 +1139,15 @@ impl<T> Vec<T> {
/// would also make any pointers to it invalid.
#[inline]
pub fn as_ptr(&self) -> *T {
self.as_slice().as_ptr()
// If we have a 0-sized vector, then the base pointer should not be NULL
// because an iterator over the slice will attempt to yield the base
// pointer as the first element in the vector, but this will end up
// being Some(NULL) which is optimized to None.
if mem::size_of::<T>() == 0 {
1 as *T
} else {
self.ptr as *T
}
}
/// Returns a mutable unsafe pointer to the vector's buffer.
@ -1155,7 +1159,12 @@ impl<T> Vec<T> {
/// would also make any pointers to it invalid.
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self.as_mut_slice().as_mut_ptr()
// see above for the 0-size check
if mem::size_of::<T>() == 0 {
1 as *mut T
} else {
self.ptr
}
}
/// Retains only the elements specified by the predicate.
@ -1356,16 +1365,7 @@ impl<T> Vector<T> for Vec<T> {
/// ```
#[inline]
fn as_slice<'a>(&'a self) -> &'a [T] {
// If we have a 0-sized vector, then the base pointer should not be NULL
// because an iterator over the slice will attempt to yield the base
// pointer as the first element in the vector, but this will end up
// being Some(NULL) which is optimized to None.
let slice = if mem::size_of::<T>() == 0 {
Slice { data: 1 as *T, len: self.len }
} else {
Slice { data: self.ptr as *T, len: self.len }
};
unsafe { transmute(slice) }
unsafe { transmute(Slice { data: self.as_ptr(), len: self.len }) }
}
}