auto merge of #18070 : alexcrichton/rust/spring-cleaning, r=aturon

This is a large spring-cleaning commit now that the 0.12.0 release has passed removing an amount of deprecated functionality. This removes a number of deprecated crates (all still available as cargo packages in the rust-lang organization) as well as a slew of deprecated functions. All `#[crate_id]` support has also been removed.

I tried to avoid anything that was recently deprecated, but I may have missed something! The major pain points of this commit is the fact that rustc/syntax have `#[allow(deprecated)]`, but I've removed that annotation so moving forward they should be cleaned up as we go.
This commit is contained in:
bors 2014-10-20 16:07:43 +00:00
commit 7d0cc44f87
355 changed files with 1364 additions and 12821 deletions

View File

@ -49,11 +49,11 @@
# automatically generated for all stage/host/target combinations.
################################################################################
TARGET_CRATES := libc std green native flate arena glob term semver \
uuid serialize sync getopts collections num test time rand \
url log regex graphviz core rbml rlibc alloc rustrt \
TARGET_CRATES := libc std green native flate arena term \
serialize sync getopts collections test time rand \
log regex graphviz core rbml rlibc alloc rustrt \
unicode
HOST_CRATES := syntax rustc rustdoc fourcc hexfloat regex_macros fmt_macros \
HOST_CRATES := syntax rustc rustdoc regex_macros fmt_macros \
rustc_llvm rustc_back
CRATES := $(TARGET_CRATES) $(HOST_CRATES)
TOOLS := compiletest rustdoc rustc
@ -83,18 +83,13 @@ DEPS_glob := std
DEPS_serialize := std log
DEPS_rbml := std log serialize
DEPS_term := std log
DEPS_semver := std
DEPS_uuid := std serialize
DEPS_sync := core alloc rustrt collections
DEPS_getopts := std
DEPS_collections := core alloc unicode
DEPS_fourcc := rustc syntax std
DEPS_hexfloat := rustc syntax std
DEPS_num := std
DEPS_test := std getopts serialize rbml term time regex native:rust_test_helpers
DEPS_time := std serialize
DEPS_rand := core
DEPS_url := std
DEPS_log := std regex
DEPS_regex := std
DEPS_regex_macros = rustc syntax std regex

View File

@ -475,12 +475,6 @@ impl<T> DList<T> {
Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
}
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
self.iter_mut()
}
/// Provides a forward iterator with mutable references.
#[inline]
pub fn iter_mut<'a>(&'a mut self) -> MutItems<'a, T> {
@ -496,12 +490,6 @@ impl<T> DList<T> {
}
}
/// Deprecated: use `into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> MoveItems<T> {
self.into_iter()
}
/// Consumes the list into an iterator yielding elements by value.
#[inline]
pub fn into_iter(self) -> MoveItems<T> {
@ -870,7 +858,8 @@ mod tests {
let mut m = list_from(v.as_slice());
m.append(list_from(u.as_slice()));
check_links(&m);
let sum = v.append(u.as_slice());
let mut sum = v;
sum.push_all(u.as_slice());
assert_eq!(sum.len(), m.len());
for elt in sum.into_iter() {
assert_eq!(m.pop_front(), Some(elt))

View File

@ -502,40 +502,6 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn push_front(&mut self, elt: T);
/// Inserts an element last in the sequence.
///
/// # Example
///
/// ```ignore
/// use std::collections::{DList, Deque};
///
/// let mut d = DList::new();
/// d.push_back(1i);
/// d.push_back(2i);
/// assert_eq!(d.front(), Some(&1i));
/// ```
#[deprecated = "use the `push` method"]
fn push_back(&mut self, elt: T) { self.push(elt) }
/// Removes the last element and returns it, or `None` if the sequence is
/// empty.
///
/// # Example
///
/// ```ignore
/// use std::collections::{RingBuf, Deque};
///
/// let mut d = RingBuf::new();
/// d.push_back(1i);
/// d.push_back(2i);
///
/// assert_eq!(d.pop_back(), Some(2i));
/// assert_eq!(d.pop_back(), Some(1i));
/// assert_eq!(d.pop_back(), None);
/// ```
#[deprecated = "use the `pop` method"]
fn pop_back(&mut self) -> Option<T> { self.pop() }
/// Removes the first element and returns it, or `None` if the sequence is
/// empty.
///

View File

@ -269,9 +269,6 @@ impl<T: Ord> PriorityQueue<T> {
if self.is_empty() { None } else { Some(&self.data[0]) }
}
#[deprecated="renamed to `top`"]
pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
/// Returns the number of elements the queue can hold without reallocating.
///
/// # Example
@ -341,9 +338,6 @@ impl<T: Ord> PriorityQueue<T> {
}
}
#[deprecated="renamed to `pop`"]
pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
/// Pushes an item onto the queue.
///
/// # Example
@ -417,14 +411,6 @@ impl<T: Ord> PriorityQueue<T> {
}
}
#[allow(dead_code)]
#[deprecated="renamed to `into_vec`"]
fn to_vec(self) -> Vec<T> { self.into_vec() }
#[allow(dead_code)]
#[deprecated="renamed to `into_sorted_vec`"]
fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
/// Consumes the `PriorityQueue` and returns the underlying vector
/// in arbitrary order.
///

View File

@ -19,6 +19,7 @@ use core::cmp;
use core::default::Default;
use core::fmt;
use core::iter;
use core::slice;
use std::hash::{Writer, Hash};
use {Deque, Mutable, MutableSeq};
@ -132,32 +133,6 @@ impl<T> RingBuf<T> {
elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)}
}
/// Retrieve an element in the `RingBuf` by index.
///
/// Fails if there is no element with the given index.
///
/// # Example
///
/// ```rust
/// #![allow(deprecated)]
///
/// use std::collections::RingBuf;
///
/// let mut buf = RingBuf::new();
/// buf.push(3i);
/// buf.push(4);
/// buf.push(5);
/// assert_eq!(buf.get(1), &4);
/// ```
#[deprecated = "prefer using indexing, e.g., ringbuf[0]"]
pub fn get<'a>(&'a self, i: uint) -> &'a T {
let idx = self.raw_index(i);
match self.elts[idx] {
None => fail!(),
Some(ref v) => v
}
}
/// Retrieves an element in the `RingBuf` by index.
///
/// Fails if there is no element with the given index.
@ -250,12 +225,6 @@ impl<T> RingBuf<T> {
Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()}
}
/// Deprecated: use `iter_mut`
#[deprecated = "use iter_mut"]
pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
self.iter_mut()
}
/// Returns a front-to-back iterator which returns mutable references.
///
/// # Example
@ -285,16 +254,20 @@ impl<T> RingBuf<T> {
// 0 to end_index
let (temp, remaining1) = self.elts.split_at_mut(start_index);
let (remaining2, _) = temp.split_at_mut(end_index);
MutItems { remaining1: remaining1,
remaining2: remaining2,
nelts: self.nelts }
MutItems {
remaining1: remaining1.iter_mut(),
remaining2: remaining2.iter_mut(),
nelts: self.nelts,
}
} else {
// Items to iterate goes from start_index to end_index:
let (empty, elts) = self.elts.split_at_mut(0);
let remaining1 = elts[mut start_index..end_index];
MutItems { remaining1: remaining1,
remaining2: empty,
nelts: self.nelts }
MutItems {
remaining1: remaining1.iter_mut(),
remaining2: empty.iter_mut(),
nelts: self.nelts,
}
}
}
}
@ -356,26 +329,26 @@ impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
/// `RingBuf` mutable iterator.
pub struct MutItems<'a, T:'a> {
remaining1: &'a mut [Option<T>],
remaining2: &'a mut [Option<T>],
remaining1: slice::MutItems<'a, Option<T>>,
remaining2: slice::MutItems<'a, Option<T>>,
nelts: uint,
}
impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
#[inline]
#[allow(deprecated)] // mut_shift_ref
fn next(&mut self) -> Option<&'a mut T> {
if self.nelts == 0 {
return None;
}
let r = if self.remaining1.len() > 0 {
&mut self.remaining1
} else {
assert!(self.remaining2.len() > 0);
&mut self.remaining2
};
self.nelts -= 1;
Some(r.mut_shift_ref().unwrap().get_mut_ref())
match self.remaining1.next() {
Some(ptr) => return Some(ptr.as_mut().unwrap()),
None => {}
}
match self.remaining2.next() {
Some(ptr) => return Some(ptr.as_mut().unwrap()),
None => unreachable!(),
}
}
#[inline]
@ -386,19 +359,19 @@ impl<'a, T> Iterator<&'a mut T> for MutItems<'a, T> {
impl<'a, T> DoubleEndedIterator<&'a mut T> for MutItems<'a, T> {
#[inline]
#[allow(deprecated)] // mut_shift_ref
fn next_back(&mut self) -> Option<&'a mut T> {
if self.nelts == 0 {
return None;
}
let r = if self.remaining2.len() > 0 {
&mut self.remaining2
} else {
assert!(self.remaining1.len() > 0);
&mut self.remaining1
};
self.nelts -= 1;
Some(r.mut_pop_ref().unwrap().get_mut_ref())
match self.remaining2.next_back() {
Some(ptr) => return Some(ptr.as_mut().unwrap()),
None => {}
}
match self.remaining1.next_back() {
Some(ptr) => return Some(ptr.as_mut().unwrap()),
None => unreachable!(),
}
}
}
@ -484,9 +457,12 @@ impl<S: Writer, A: Hash<S>> Hash<S> for RingBuf<A> {
impl<A> Index<uint, A> for RingBuf<A> {
#[inline]
#[allow(deprecated)]
fn index<'a>(&'a self, i: &uint) -> &'a A {
self.get(*i)
let idx = self.raw_index(*i);
match self.elts[idx] {
None => fail!(),
Some(ref v) => v,
}
}
}
@ -576,14 +552,14 @@ mod tests {
assert_eq!(d.len(), 3u);
d.push_front(1);
assert_eq!(d.len(), 4u);
debug!("{}", d.get(0));
debug!("{}", d.get(1));
debug!("{}", d.get(2));
debug!("{}", d.get(3));
assert_eq!(*d.get(0), 1);
assert_eq!(*d.get(1), 2);
assert_eq!(*d.get(2), 3);
assert_eq!(*d.get(3), 4);
debug!("{}", d[0]);
debug!("{}", d[1]);
debug!("{}", d[2]);
debug!("{}", d[3]);
assert_eq!(d[0], 1);
assert_eq!(d[1], 2);
assert_eq!(d[2], 3);
assert_eq!(d[3], 4);
}
#[cfg(test)]

View File

@ -270,23 +270,6 @@ impl<T: Clone> Iterator<Vec<T>> for Permutations<T> {
pub trait CloneableVector<T> {
/// Copies `self` into a new `Vec`.
fn to_vec(&self) -> Vec<T>;
/// Deprecated. Use `to_vec`.
#[deprecated = "Replaced by `to_vec`"]
fn to_owned(&self) -> Vec<T> {
self.to_vec()
}
/// Converts `self` into an owned vector, not making a copy if possible.
/// Deprecated. Use 'to_vec'
#[deprecated = "Replaced by `to_vec`"]
fn into_vec(self) -> Vec<T>;
/// Deprecated. Use `to_vec`
#[deprecated = "Replaced by `to_vec`"]
fn into_owned(self) -> Vec<T> {
self.to_vec()
}
}
impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
@ -297,9 +280,6 @@ impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
vector.push_all(*self);
vector
}
#[inline(always)]
fn into_vec(self) -> Vec<T> { self.to_vec() }
}
#[experimental]
@ -920,25 +900,6 @@ mod tests {
a.as_mut_slice().tail_mut();
}
#[test]
#[allow(deprecated)]
fn test_tailn() {
let mut a = vec![11i, 12, 13];
let b: &mut [int] = &mut [11, 12, 13];
assert!(a.tailn(0) == b);
a = vec![11i, 12, 13];
let b: &mut [int] = &mut [13];
assert!(a.tailn(2) == b);
}
#[test]
#[should_fail]
#[allow(deprecated)]
fn test_tailn_empty() {
let a: Vec<int> = vec![];
a.tailn(2);
}
#[test]
fn test_init() {
let mut a = vec![11i];
@ -973,25 +934,6 @@ mod tests {
a.as_mut_slice().init_mut();
}
#[test]
#[allow(deprecated)]
fn test_initn() {
let mut a = vec![11i, 12, 13];
let b: &[int] = &[11, 12, 13];
assert_eq!(a.as_slice().initn(0), b);
a = vec![11i, 12, 13];
let b: &[int] = &[11];
assert_eq!(a.as_slice().initn(2), b);
}
#[test]
#[should_fail]
#[allow(deprecated)]
fn test_initn_empty() {
let a: Vec<int> = vec![];
a.as_slice().initn(2);
}
#[test]
fn test_last() {
let mut a = vec![];
@ -1156,20 +1098,6 @@ mod tests {
assert_eq!(v[2], 4u);
}
#[test]
#[allow(deprecated)]
fn test_grow_set() {
let mut v = vec![1i, 2, 3];
v.grow_set(4u, &4, 5);
let v = v.as_slice();
assert_eq!(v.len(), 5u);
assert_eq!(v[0], 1);
assert_eq!(v[1], 2);
assert_eq!(v[2], 3);
assert_eq!(v[3], 4);
assert_eq!(v[4], 5);
}
#[test]
fn test_truncate() {
let mut v = vec![box 6i,box 5,box 4];
@ -1385,49 +1313,48 @@ mod tests {
}
#[test]
#[allow(deprecated)]
fn test_bsearch_elem() {
assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
fn test_binary_search_elem() {
assert_eq!([1i,2,3,4,5].binary_search_elem(&5).found(), Some(4));
assert_eq!([1i,2,3,4,5].binary_search_elem(&4).found(), Some(3));
assert_eq!([1i,2,3,4,5].binary_search_elem(&3).found(), Some(2));
assert_eq!([1i,2,3,4,5].binary_search_elem(&2).found(), Some(1));
assert_eq!([1i,2,3,4,5].binary_search_elem(&1).found(), Some(0));
assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
assert_eq!([2i,4,6,8,10].binary_search_elem(&1).found(), None);
assert_eq!([2i,4,6,8,10].binary_search_elem(&5).found(), None);
assert_eq!([2i,4,6,8,10].binary_search_elem(&4).found(), Some(1));
assert_eq!([2i,4,6,8,10].binary_search_elem(&10).found(), Some(4));
assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
assert_eq!([2i,4,6,8].binary_search_elem(&1).found(), None);
assert_eq!([2i,4,6,8].binary_search_elem(&5).found(), None);
assert_eq!([2i,4,6,8].binary_search_elem(&4).found(), Some(1));
assert_eq!([2i,4,6,8].binary_search_elem(&8).found(), Some(3));
assert_eq!([2i,4,6].bsearch_elem(&1), None);
assert_eq!([2i,4,6].bsearch_elem(&5), None);
assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
assert_eq!([2i,4,6].binary_search_elem(&1).found(), None);
assert_eq!([2i,4,6].binary_search_elem(&5).found(), None);
assert_eq!([2i,4,6].binary_search_elem(&4).found(), Some(1));
assert_eq!([2i,4,6].binary_search_elem(&6).found(), Some(2));
assert_eq!([2i,4].bsearch_elem(&1), None);
assert_eq!([2i,4].bsearch_elem(&5), None);
assert_eq!([2i,4].bsearch_elem(&2), Some(0));
assert_eq!([2i,4].bsearch_elem(&4), Some(1));
assert_eq!([2i,4].binary_search_elem(&1).found(), None);
assert_eq!([2i,4].binary_search_elem(&5).found(), None);
assert_eq!([2i,4].binary_search_elem(&2).found(), Some(0));
assert_eq!([2i,4].binary_search_elem(&4).found(), Some(1));
assert_eq!([2i].bsearch_elem(&1), None);
assert_eq!([2i].bsearch_elem(&5), None);
assert_eq!([2i].bsearch_elem(&2), Some(0));
assert_eq!([2i].binary_search_elem(&1).found(), None);
assert_eq!([2i].binary_search_elem(&5).found(), None);
assert_eq!([2i].binary_search_elem(&2).found(), Some(0));
assert_eq!([].bsearch_elem(&1i), None);
assert_eq!([].bsearch_elem(&5i), None);
assert_eq!([].binary_search_elem(&1i).found(), None);
assert_eq!([].binary_search_elem(&5i).found(), None);
assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
assert!([1i,1,1,1,1].binary_search_elem(&1).found() != None);
assert!([1i,1,1,1,2].binary_search_elem(&1).found() != None);
assert!([1i,1,1,2,2].binary_search_elem(&1).found() != None);
assert!([1i,1,2,2,2].binary_search_elem(&1).found() != None);
assert_eq!([1i,2,2,2,2].binary_search_elem(&1).found(), Some(0));
assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
assert_eq!([1i,2,3,4,5].binary_search_elem(&6).found(), None);
assert_eq!([1i,2,3,4,5].binary_search_elem(&0).found(), None);
}
#[test]
@ -1544,26 +1471,6 @@ mod tests {
assert_eq!(v.connect_vec(&0), vec![1, 0, 2, 0, 3]);
}
#[test]
#[allow(deprecated)]
fn test_shift() {
let mut x = vec![1i, 2, 3];
assert_eq!(x.shift(), Some(1));
assert_eq!(&x, &vec![2i, 3]);
assert_eq!(x.shift(), Some(2));
assert_eq!(x.shift(), Some(3));
assert_eq!(x.shift(), None);
assert_eq!(x.len(), 0);
}
#[test]
#[allow(deprecated)]
fn test_unshift() {
let mut x = vec![1i, 2, 3];
x.unshift(0);
assert_eq!(x, vec![0, 1, 2, 3]);
}
#[test]
fn test_insert() {
let mut a = vec![1i, 2, 4];
@ -1689,17 +1596,6 @@ mod tests {
}
}
#[test]
#[should_fail]
#[allow(deprecated)]
fn test_copy_memory_oob() {
unsafe {
let mut a = [1i, 2, 3, 4];
let b = [1i, 2, 3, 4, 5];
a.copy_memory(b);
}
}
#[test]
fn test_total_ord() {
let c: &[int] = &[1, 2, 3];
@ -2005,19 +1901,6 @@ mod tests {
assert!(a == [1i,2,6,7,5]);
}
#[test]
#[allow(deprecated)]
fn test_copy_from() {
let mut a = [1i,2,3,4,5];
let b = [6i,7,8];
assert_eq!(a.copy_from(b), 3);
assert!(a == [6i,7,8,4,5]);
let mut c = [7i,2,8,1];
let d = [3i,1,4,1,5,9];
assert_eq!(c.copy_from(d), 4);
assert!(c == [3i,1,4,1]);
}
#[test]
fn test_reverse_part() {
let mut values = [1i,2,3,4,5];
@ -2198,34 +2081,6 @@ mod tests {
assert!(b"foobar".ends_with(empty));
}
#[test]
#[allow(deprecated)]
fn test_shift_ref() {
let mut x: &[int] = [1, 2, 3, 4, 5];
let h = x.shift_ref();
assert_eq!(*h.unwrap(), 1);
assert_eq!(x.len(), 4);
assert_eq!(x[0], 2);
assert_eq!(x[3], 5);
let mut y: &[int] = [];
assert_eq!(y.shift_ref(), None);
}
#[test]
#[allow(deprecated)]
fn test_pop_ref() {
let mut x: &[int] = [1, 2, 3, 4, 5];
let h = x.pop_ref();
assert_eq!(*h.unwrap(), 5);
assert_eq!(x.len(), 4);
assert_eq!(x[0], 1);
assert_eq!(x[3], 4);
let mut y: &[int] = [];
assert!(y.pop_ref().is_none());
}
#[test]
fn test_mut_splitator() {
let mut xs = [0i,1,0,2,3,0,0,4,5,0];
@ -2292,34 +2147,6 @@ mod tests {
let _it = v.chunks_mut(0);
}
#[test]
#[allow(deprecated)]
fn test_mut_shift_ref() {
let mut x: &mut [int] = [1, 2, 3, 4, 5];
let h = x.mut_shift_ref();
assert_eq!(*h.unwrap(), 1);
assert_eq!(x.len(), 4);
assert_eq!(x[0], 2);
assert_eq!(x[3], 5);
let mut y: &mut [int] = [];
assert!(y.mut_shift_ref().is_none());
}
#[test]
#[allow(deprecated)]
fn test_mut_pop_ref() {
let mut x: &mut [int] = [1, 2, 3, 4, 5];
let h = x.mut_pop_ref();
assert_eq!(*h.unwrap(), 5);
assert_eq!(x.len(), 4);
assert_eq!(x[0], 1);
assert_eq!(x[3], 4);
let mut y: &mut [int] = [];
assert!(y.mut_pop_ref().is_none());
}
#[test]
fn test_mut_last() {
let mut x = [1i, 2, 3, 4, 5];

View File

@ -199,29 +199,6 @@ impl<V> SmallIntMap<V> {
SmallIntMap { v: Vec::with_capacity(capacity) }
}
/// Retrieves a value for the given key.
/// See [`find`](../trait.Map.html#tymethod.find) for a non-failing alternative.
///
/// # Failure
///
/// Fails if the key is not present.
///
/// # Example
///
/// ```
/// #![allow(deprecated)]
///
/// use std::collections::SmallIntMap;
///
/// let mut map = SmallIntMap::new();
/// map.insert(1, "a");
/// assert_eq!(map.get(&1), &"a");
/// ```
#[deprecated = "prefer using indexing, e.g., map[0]"]
pub fn get<'a>(&'a self, key: &uint) -> &'a V {
self.find(key).expect("key not present")
}
/// Returns an iterator visiting all keys in ascending order by the keys.
/// The iterator's element type is `uint`.
pub fn keys<'r>(&'r self) -> Keys<'r, V> {
@ -260,12 +237,6 @@ impl<V> SmallIntMap<V> {
}
}
/// Deprecated: use `iter_mut`
#[deprecated = "use iter_mut"]
pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
self.iter_mut()
}
/// Returns an iterator visiting all key-value pairs in ascending order by the keys,
/// with mutable references to the values.
/// The iterator's element type is `(uint, &'r mut V)`.
@ -296,14 +267,6 @@ impl<V> SmallIntMap<V> {
}
}
/// Deprecated: use `into_iter` instead.
#[deprecated = "use into_iter"]
pub fn move_iter(&mut self)
-> FilterMap<(uint, Option<V>), (uint, V),
Enumerate<vec::MoveItems<Option<V>>>> {
self.into_iter()
}
/// Returns an iterator visiting all key-value pairs in ascending order by
/// the keys, emptying (but not consuming) the original `SmallIntMap`.
/// The iterator's element type is `(uint, &'r V)`.
@ -437,9 +400,8 @@ impl<V> Extendable<(uint, V)> for SmallIntMap<V> {
impl<V> Index<uint, V> for SmallIntMap<V> {
#[inline]
#[allow(deprecated)]
fn index<'a>(&'a self, i: &uint) -> &'a V {
self.get(i)
self.find(i).expect("key not present")
}
}

View File

@ -58,7 +58,6 @@ use core::default::Default;
use core::fmt;
use core::cmp;
use core::iter::AdditiveIterator;
use core::mem;
use core::prelude::{Char, Clone, Collection, Eq, Equiv, ImmutableSlice};
use core::prelude::{Iterator, MutableSlice, None, Option, Ord, Ordering};
use core::prelude::{PartialEq, PartialOrd, Result, AsSlice, Some, Tuple2};
@ -67,7 +66,6 @@ use core::prelude::{range};
use {Deque, MutableSeq};
use hash;
use ringbuf::RingBuf;
use slice::CloneableVector;
use string::String;
use unicode;
use vec::Vec;
@ -85,31 +83,6 @@ pub use unicode::str::{UnicodeStrSlice, Words, Graphemes, GraphemeIndices};
Section: Creating a string
*/
/// Deprecated. Replaced by `String::from_utf8`.
#[deprecated = "Replaced by `String::from_utf8`"]
pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> {
String::from_utf8(vv)
}
/// Deprecated. Replaced by `String::from_byte`.
#[deprecated = "Replaced by String::from_byte"]
pub fn from_byte(b: u8) -> String {
assert!(b < 128u8);
String::from_char(1, b as char)
}
/// Deprecated. Use `String::from_char` or `char::to_string()` instead.
#[deprecated = "use String::from_char or char.to_string()"]
pub fn from_char(ch: char) -> String {
String::from_char(1, ch)
}
/// Deprecated. Replaced by `String::from_chars`.
#[deprecated = "use String::from_chars instead"]
pub fn from_chars(chs: &[char]) -> String {
chs.iter().map(|c| *c).collect()
}
/// Methods for vectors of strings.
pub trait StrVector {
/// Concatenates a vector of strings.
@ -427,18 +400,6 @@ pub fn replace(s: &str, from: &str, to: &str) -> String {
Section: Misc
*/
/// Deprecated. Use `String::from_utf16`.
#[deprecated = "Replaced by String::from_utf16"]
pub fn from_utf16(v: &[u16]) -> Option<String> {
String::from_utf16(v)
}
/// Deprecated. Use `String::from_utf16_lossy`.
#[deprecated = "Replaced by String::from_utf16_lossy"]
pub fn from_utf16_lossy(v: &[u16]) -> String {
String::from_utf16_lossy(v)
}
// Return the initial codepoint accumulator for the first byte.
// The first byte is special, only want bottom 5 bits for width 2, 4 bits
// for width 3, and 3 bits for width 4
@ -451,12 +412,6 @@ macro_rules! utf8_acc_cont_byte(
($ch:expr, $byte:expr) => (($ch << 6) | ($byte & 63u8) as u32)
)
/// Deprecated. Use `String::from_utf8_lossy`.
#[deprecated = "Replaced by String::from_utf8_lossy"]
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
String::from_utf8_lossy(v)
}
/*
Section: MaybeOwned
*/
@ -644,38 +599,8 @@ impl<'a> fmt::Show for MaybeOwned<'a> {
/// Unsafe string operations.
pub mod raw {
use string;
use string::String;
use vec::Vec;
use MutableSeq;
pub use core::str::raw::{from_utf8, c_str_to_static_slice, slice_bytes};
pub use core::str::raw::{slice_unchecked};
/// Deprecated. Replaced by `string::raw::from_buf_len`
#[deprecated = "Use string::raw::from_buf_len"]
pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
string::raw::from_buf_len(buf, len)
}
/// Deprecated. Use `string::raw::from_buf`
#[deprecated = "Use string::raw::from_buf"]
pub unsafe fn from_c_str(c_string: *const i8) -> String {
string::raw::from_buf(c_string as *const u8)
}
/// Deprecated. Replaced by `string::raw::from_utf8`
#[deprecated = "Use string::raw::from_utf8"]
pub unsafe fn from_utf8_owned(v: Vec<u8>) -> String {
string::raw::from_utf8(v)
}
/// Deprecated. Use `string::raw::from_utf8`
#[deprecated = "Use string::raw::from_utf8"]
pub unsafe fn from_byte(u: u8) -> String {
string::raw::from_utf8(vec![u])
}
}
/*
@ -687,12 +612,6 @@ pub trait StrAllocating: Str {
/// Converts `self` into a `String`, not making a copy if possible.
fn into_string(self) -> String;
#[allow(missing_doc)]
#[deprecated = "replaced by .into_string()"]
fn into_owned(self) -> String {
self.into_string()
}
/// Escapes each char in `s` with `char::escape_default`.
fn escape_default(&self) -> String {
let me = self.as_slice();
@ -750,21 +669,6 @@ pub trait StrAllocating: Str {
result
}
#[allow(missing_doc)]
#[deprecated = "obsolete, use `to_string`"]
#[inline]
fn to_owned(&self) -> String {
unsafe {
mem::transmute(self.as_slice().as_bytes().to_vec())
}
}
/// Converts to a vector of `u16` encoded as UTF-16.
#[deprecated = "use `utf16_units` instead"]
fn to_utf16(&self) -> Vec<u16> {
self.as_slice().utf16_units().collect::<Vec<u16>>()
}
/// Given a string, makes a new string with repeated copies of it.
fn repeat(&self, nn: uint) -> String {
let me = self.as_slice();

View File

@ -84,20 +84,6 @@ impl String {
String { vec: string.as_bytes().to_vec() }
}
/// Deprecated. Replaced by `string::raw::from_parts`
#[inline]
#[deprecated = "Replaced by string::raw::from_parts"]
pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut u8) -> String {
raw::from_parts(ptr, length, capacity)
}
/// Deprecated.
#[deprecated = "obsoleted by the removal of ~str"]
#[inline]
pub fn from_owned_str(string: String) -> String {
string
}
/// Returns the vector as a string buffer, if possible, taking care not to
/// copy it.
///
@ -327,26 +313,6 @@ impl String {
self.vec
}
/// Pushes the given `String` onto this buffer then returns `self` so that it can be
/// used again.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let s = String::from_str("hello");
/// let big = s.append(" ").append("world").append("!");
/// // s has now been moved and cannot be used
///
/// assert_eq!(big.as_slice(), "hello world!");
/// ```
#[inline]
#[deprecated = "use .push_str() instead"]
pub fn append(mut self, second: &str) -> String {
self.push_str(second);
self
}
/// Creates a string buffer by repeating a character `length` times.
///
/// # Example
@ -373,25 +339,6 @@ impl String {
buf
}
/// Converts a byte to a UTF-8 string.
///
/// # Failure
///
/// Fails with invalid UTF-8 (i.e., the byte is greater than 127).
///
/// # Example
///
/// ```rust
/// # #![allow(deprecated)]
/// let s = String::from_byte(104);
/// assert_eq!(s.as_slice(), "h");
/// ```
#[deprecated = "use str::from_utf8 with a slice of one byte instead"]
pub fn from_byte(b: u8) -> String {
assert!(b < 128u8);
String::from_char(1, b as char)
}
/// Pushes the given string onto this string buffer.
///
/// # Example
@ -424,21 +371,6 @@ impl String {
}
}
/// Returns the number of bytes that this string buffer can hold without reallocating.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let s = String::with_capacity(10);
/// assert!(s.byte_capacity() >= 10);
/// ```
#[inline]
#[deprecated = "renamed to .capacity()"]
pub fn byte_capacity(&self) -> uint {
self.vec.capacity()
}
/// Returns the number of bytes that this string buffer can hold without reallocating.
///
/// # Example
@ -512,13 +444,6 @@ impl String {
self.vec.shrink_to_fit()
}
/// Deprecated, use .push() instead.
#[inline]
#[deprecated = "renamed to .push()"]
pub fn push_char(&mut self, ch: char) {
self.push(ch)
}
/// Adds the given character to the end of the string.
///
/// # Example
@ -549,26 +474,6 @@ impl String {
}
}
/// Pushes the given bytes onto this string buffer.
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::new();
/// unsafe {
/// s.push_bytes([104, 101, 108, 108, 111]);
/// }
/// assert_eq!(s.as_slice(), "hello");
/// ```
#[inline]
#[deprecated = "call .as_mut_vec() and push onto that"]
pub unsafe fn push_bytes(&mut self, bytes: &[u8]) {
self.vec.push_all(bytes)
}
/// Works with the underlying buffer as a byte slice.
///
/// # Example
@ -584,31 +489,6 @@ impl String {
self.vec.as_slice()
}
/// Works with the underlying buffer as a mutable byte slice.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::from_str("hello");
/// unsafe {
/// let bytes = s.as_mut_bytes();
/// bytes[1] = 51;
/// bytes[4] = 48;
/// }
/// let b: &[_] = &[104, 51, 108, 108, 48];
/// assert_eq!(s.as_bytes(), b);
/// assert_eq!(s.as_slice(), "h3ll0")
/// ```
#[inline]
#[deprecated = "call .as_mut_vec().as_mut_slice() instead"]
pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
self.vec.as_mut_slice()
}
/// Shortens a string to the specified length.
///
/// # Failure
@ -630,63 +510,6 @@ impl String {
self.vec.truncate(new_len)
}
/// Appends a byte to this string buffer.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::from_str("hell");
/// unsafe {
/// s.push_byte(111);
/// }
/// assert_eq!(s.as_slice(), "hello");
/// ```
#[inline]
#[deprecated = "call .as_mut_vec().push() instead"]
pub unsafe fn push_byte(&mut self, byte: u8) {
self.vec.push(byte)
}
/// Removes the last byte from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::from_str("foo");
/// unsafe {
/// assert_eq!(s.pop_byte(), Some(111));
/// assert_eq!(s.pop_byte(), Some(111));
/// assert_eq!(s.pop_byte(), Some(102));
/// assert_eq!(s.pop_byte(), None);
/// }
/// ```
#[inline]
#[deprecated = "call .as_mut_vec().pop() instead"]
pub unsafe fn pop_byte(&mut self) -> Option<u8> {
let len = self.len();
if len == 0 {
return None
}
let byte = self.as_bytes()[len - 1];
self.vec.set_len(len - 1);
Some(byte)
}
/// Deprecated. Renamed to `pop`.
#[inline]
#[deprecated = "renamed to .pop()"]
pub fn pop_char(&mut self) -> Option<char> { self.pop() }
/// Removes the last character from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
@ -714,35 +537,6 @@ impl String {
Some(ch)
}
/// Removes the first byte from the string buffer and returns it.
/// Returns `None` if this string buffer is empty.
///
/// This is unsafe because it does not check
/// to ensure that the resulting string will be valid UTF-8.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut s = String::from_str("foo");
/// unsafe {
/// assert_eq!(s.shift_byte(), Some(102));
/// assert_eq!(s.shift_byte(), Some(111));
/// assert_eq!(s.shift_byte(), Some(111));
/// assert_eq!(s.shift_byte(), None);
/// }
/// ```
#[deprecated = "call .as_mut_vec().remove(0)"]
pub unsafe fn shift_byte(&mut self) -> Option<u8> {
self.vec.remove(0)
}
/// Deprecated, call `remove(0)` instead
#[deprecated = "call .remove(0) instead"]
pub fn shift_char(&mut self) -> Option<char> {
self.remove(0)
}
/// Removes the character from the string buffer at byte position `idx` and
/// returns it. Returns `None` if `idx` is out of bounds.
///
@ -1251,18 +1045,6 @@ mod tests {
assert_eq!(data.as_slice(), "ประเทศไทย中");
}
#[test]
#[allow(deprecated)] // use remove(0) instead
fn test_shift_char() {
let mut data = String::from_str("𤭢€¢b华ประเทศไทย中");
assert_eq!(data.shift_char().unwrap(), '𤭢'); // 4 bytes
assert_eq!(data.shift_char().unwrap(), '€'); // 3 bytes
assert_eq!(data.shift_char().unwrap(), '¢'); // 2 bytes
assert_eq!(data.shift_char().unwrap(), 'b'); // 1 bytes
assert_eq!(data.shift_char().unwrap(), '华');
assert_eq!(data.as_slice(), "ประเทศไทย中");
}
#[test]
fn test_str_truncate() {
let mut s = String::from_str("12345");

View File

@ -361,12 +361,6 @@ impl<K: Ord, V> TreeMap<K, V> {
RevEntries{iter: self.iter()}
}
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
self.iter_mut()
}
/// Gets a lazy forward iterator over the key-value pairs in the
/// map, with the values being mutable.
///
@ -398,12 +392,6 @@ impl<K: Ord, V> TreeMap<K, V> {
}
}
/// Deprecated: use `rev_iter_mut`.
#[deprecated = "use rev_iter_mut"]
pub fn mut_rev_iter<'a>(&'a mut self) -> RevMutEntries<'a, K, V> {
self.rev_iter_mut()
}
/// Gets a lazy reverse iterator over the key-value pairs in the
/// map, with the values being mutable.
///
@ -430,12 +418,6 @@ impl<K: Ord, V> TreeMap<K, V> {
RevMutEntries{iter: self.iter_mut()}
}
/// Deprecated: use `into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> MoveEntries<K, V> {
self.into_iter()
}
/// Gets a lazy iterator that consumes the treemap.
///
/// # Example
@ -494,12 +476,6 @@ impl<K, V> TreeMap<K, V> {
tree_find_with(&self.root, f)
}
/// Deprecated: use `find_with_mut`.
#[deprecated = "use find_with_mut"]
pub fn find_mut_with<'a>(&'a mut self, f:|&K| -> Ordering) -> Option<&'a mut V> {
self.find_with_mut(f)
}
/// Returns the value for which `f(key)` returns `Equal`. `f` is invoked
/// with current key and guides tree navigation. That means `f` should
/// be aware of natural ordering of the tree.
@ -626,12 +602,6 @@ impl<K: Ord, V> TreeMap<K, V> {
}
}
/// Deprecated: use `lower_bound_mut`.
#[deprecated = "use lower_bound_mut"]
pub fn mut_lower_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
self.lower_bound_mut(k)
}
/// Returns a lazy value iterator to the first key-value pair (with
/// the value being mutable) whose key is not less than `k`.
///
@ -666,12 +636,6 @@ impl<K: Ord, V> TreeMap<K, V> {
bound_setup!(self.iter_mut_for_traversal(), k, true)
}
/// Deprecated: use `upper_bound_mut`.
#[deprecated = "use upper_bound_mut"]
pub fn mut_upper_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
self.upper_bound_mut(k)
}
/// Returns a lazy iterator to the first key-value pair (with the
/// value being mutable) whose key is greater than `k`.
///
@ -1204,12 +1168,6 @@ impl<T: Ord> TreeSet<T> {
RevSetItems{iter: self.map.rev_iter()}
}
/// Deprecated: use `into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> MoveSetItems<T> {
self.into_iter()
}
/// Creates a consuming iterator, that is, one that moves each value out of the
/// set in ascending order. The set cannot be used after calling this.
///

View File

@ -268,12 +268,6 @@ impl<T> TrieMap<T> {
iter
}
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, T> {
self.iter_mut()
}
/// Gets an iterator over the key-value pairs in the map, with the
/// ability to mutate the values.
///
@ -439,12 +433,6 @@ impl<T> TrieMap<T> {
mutability = mut)
}
/// Deprecated: use `lower_bound_mut`.
#[deprecated = "use lower_bound_mut"]
pub fn mut_lower_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
self.lower_bound_mut(key)
}
/// Gets an iterator pointing to the first key-value pair whose key is not less than `key`.
/// If all keys in the map are less than `key` an empty iterator is returned.
///
@ -470,12 +458,6 @@ impl<T> TrieMap<T> {
self.bound_mut(key, false)
}
/// Deprecated: use `upper_bound_mut`.
#[deprecated = "use upper_bound_mut"]
pub fn mut_upper_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
self.upper_bound_mut(key)
}
/// Gets an iterator pointing to the first key-value pair whose key is greater than `key`.
/// If all keys in the map are not greater than `key` an empty iterator is returned.
///

View File

@ -275,19 +275,6 @@ impl<T> Vec<T> {
}
impl<T: Clone> Vec<T> {
/// Deprecated, call `extend` instead.
#[inline]
#[deprecated = "this function has been deprecated in favor of extend()"]
pub fn append(mut self, second: &[T]) -> Vec<T> {
self.push_all(second);
self
}
/// Deprecated, call `to_vec()` instead
#[inline]
#[deprecated = "this function has been deprecated in favor of to_vec()"]
pub fn from_slice(values: &[T]) -> Vec<T> { values.to_vec() }
/// Constructs a `Vec` with copies of a value.
///
/// Creates a `Vec` with `length` copies of `value`.
@ -366,31 +353,6 @@ impl<T: Clone> Vec<T> {
}
}
/// Sets the value of a vector element at a given index, growing the vector
/// as needed.
///
/// Sets the element at position `index` to `value`. If `index` is past the
/// end of the vector, expands the vector by replicating `initval` to fill
/// the intervening space.
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut vec = vec!["a", "b", "c"];
/// vec.grow_set(1, &("fill"), "d");
/// vec.grow_set(4, &("fill"), "e");
/// assert_eq!(vec, vec!["a", "d", "c", "fill", "e"]);
/// ```
#[deprecated = "call .grow() and .push() manually instead"]
pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
let l = self.len();
if index >= l {
self.grow(index - l + 1u, initval.clone());
}
*self.get_mut(index) = value;
}
/// Partitions a vector based on a predicate.
///
/// Clones the elements of the vector, partitioning them into two `Vec`s
@ -447,9 +409,8 @@ impl<T:Clone> Clone for Vec<T> {
#[experimental = "waiting on Index stability"]
impl<T> Index<uint,T> for Vec<T> {
#[inline]
#[allow(deprecated)] // allow use of get
fn index<'a>(&'a self, index: &uint) -> &'a T {
self.get(*index)
&self.as_slice()[*index]
}
}
@ -721,14 +682,6 @@ impl<T> Vec<T> {
}
}
/// Deprecated, call `push` instead
#[inline]
#[deprecated = "call .push() instead"]
pub fn append_one(mut self, x: T) -> Vec<T> {
self.push(x);
self
}
/// Shorten a vector, dropping excess elements.
///
/// If `len` is greater than the vector's current length, this has no
@ -754,6 +707,14 @@ impl<T> Vec<T> {
}
}
/// Deprecated, use `.extend(other.into_iter())`
#[inline]
#[deprecated = "use .extend(other.into_iter())"]
#[cfg(stage0)]
pub fn push_all_move(&mut self, other: Vec<T>) {
self.extend(other.into_iter());
}
/// Returns a mutable slice of the elements of `self`.
///
/// # Example
@ -775,12 +736,6 @@ impl<T> Vec<T> {
}
}
/// Deprecated: use `into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> MoveItems<T> {
self.into_iter()
}
/// Creates a consuming iterator, that is, one that moves each
/// value out of the vector (from start to end). The vector cannot
/// be used after calling this.
@ -830,26 +785,6 @@ impl<T> Vec<T> {
self.len = len;
}
/// Returns a reference to the value at index `index`.
///
/// # Failure
///
/// Fails if `index` is out of bounds
///
/// # Example
///
/// ```
/// #![allow(deprecated)]
///
/// let vec = vec![1i, 2, 3];
/// assert!(vec.get(1) == &2);
/// ```
#[deprecated="prefer using indexing, e.g., vec[0]"]
#[inline]
pub fn get<'a>(&'a self, index: uint) -> &'a T {
&self.as_slice()[index]
}
/// Returns a mutable reference to the value at index `index`.
///
/// # Failure
@ -885,12 +820,6 @@ impl<T> Vec<T> {
self.as_slice().iter()
}
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
self.iter_mut()
}
/// Returns an iterator over mutable references to the elements of the
/// vector in order.
///
@ -963,25 +892,6 @@ impl<T> Vec<T> {
self[].tail()
}
/// Returns all but the first `n' elements of a vector.
///
/// # Failure
///
/// Fails when there are fewer than `n` elements in the vector.
///
/// # Example
///
/// ```
/// #![allow(deprecated)]
/// let vec = vec![1i, 2, 3, 4];
/// assert!(vec.tailn(2) == [3, 4]);
/// ```
#[inline]
#[deprecated = "use slice_from"]
pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
self[n..]
}
/// Returns a reference to the last element of a vector, or `None` if it is
/// empty.
///
@ -996,12 +906,6 @@ impl<T> Vec<T> {
self[].last()
}
/// Deprecated: use `last_mut`.
#[deprecated = "use last_mut"]
pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
self.last_mut()
}
/// Returns a mutable reference to the last element of a vector, or `None`
/// if it is empty.
///
@ -1047,48 +951,6 @@ impl<T> Vec<T> {
self.pop()
}
/// Prepends an element to the vector.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// vector.
///
/// # Example
///
/// ```ignore
/// let mut vec = vec![1i, 2, 3];
/// vec.unshift(4);
/// assert_eq!(vec, vec![4, 1, 2, 3]);
/// ```
#[inline]
#[deprecated = "use insert(0, ...)"]
pub fn unshift(&mut self, element: T) {
self.insert(0, element)
}
/// Removes the first element from a vector and returns it, or `None` if
/// the vector is empty.
///
/// # Warning
///
/// This is an O(n) operation as it requires copying every element in the
/// vector.
///
/// # Example
///
/// ```
/// #![allow(deprecated)]
/// let mut vec = vec![1i, 2, 3];
/// assert!(vec.shift() == Some(1));
/// assert_eq!(vec, vec![2, 3]);
/// ```
#[inline]
#[deprecated = "use remove(0)"]
pub fn shift(&mut self) -> Option<T> {
self.remove(0)
}
/// Inserts an element at position `index` within the vector, shifting all
/// elements after position `i` one position to the right.
///
@ -1167,32 +1029,6 @@ impl<T> Vec<T> {
}
}
/// Takes ownership of the vector `other`, moving all elements into
/// the current vector. This does not copy any elements, and it is
/// illegal to use the `other` vector after calling this method
/// (because it is moved here).
///
/// # Example
///
/// ```
/// # #![allow(deprecated)]
/// let mut vec = vec![box 1i];
/// vec.push_all_move(vec![box 2, box 3, box 4]);
/// assert_eq!(vec, vec![box 1, box 2, box 3, box 4]);
/// ```
#[inline]
#[deprecated = "use .extend(other.into_iter())"]
pub fn push_all_move(&mut self, other: Vec<T>) {
self.extend(other.into_iter());
}
/// Deprecated: use `slice_mut`.
#[deprecated = "use slice_mut"]
pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
-> &'a mut [T] {
self[mut start..end]
}
/// Returns a mutable slice of `self` between `start` and `end`.
///
/// # Failure
@ -1212,12 +1048,6 @@ impl<T> Vec<T> {
self[mut start..end]
}
/// Deprecated: use "slice_from_mut".
#[deprecated = "use slice_from_mut"]
pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
self[mut start..]
}
/// Returns a mutable slice of `self` from `start` to the end of the `Vec`.
///
/// # Failure
@ -1235,12 +1065,6 @@ impl<T> Vec<T> {
self[mut start..]
}
/// Deprecated: use `slice_to_mut`.
#[deprecated = "use slice_to_mut"]
pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
self[mut ..end]
}
/// Returns a mutable slice of `self` from the start of the `Vec` to `end`.
///
/// # Failure
@ -1258,12 +1082,6 @@ impl<T> Vec<T> {
self[mut ..end]
}
/// Deprecated: use `split_at_mut`.
#[deprecated = "use split_at_mut"]
pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
self.split_at_mut(mid)
}
/// Returns a pair of mutable slices that divides the `Vec` at an index.
///
/// The first will contain all indices from `[0, mid)` (excluding

View File

@ -76,11 +76,6 @@ use option::{Option, Some, None};
use raw::TraitObject;
use intrinsics::TypeId;
/// A type with no inhabitants
#[deprecated = "this type is being removed, define a type locally if \
necessary"]
pub enum Void { }
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
@ -117,13 +112,6 @@ pub trait AnyRefExt<'a> {
/// `None` if it isn't.
#[unstable = "naming conventions around acquiring references may change"]
fn downcast_ref<T: 'static>(self) -> Option<&'a T>;
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[deprecated = "this function has been renamed to `downcast_ref`"]
fn as_ref<T: 'static>(self) -> Option<&'a T> {
self.downcast_ref::<T>()
}
}
#[stable]
@ -166,13 +154,6 @@ pub trait AnyMutRefExt<'a> {
/// `None` if it isn't.
#[unstable = "naming conventions around acquiring references may change"]
fn downcast_mut<T: 'static>(self) -> Option<&'a mut T>;
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[deprecated = "this function has been renamed to `downcast_mut`"]
fn as_mut<T: 'static>(self) -> Option<&'a mut T> {
self.downcast_mut::<T>()
}
}
#[stable]

View File

@ -178,20 +178,6 @@ impl PartialOrd for Ordering {
}
}
/// Combine orderings, lexically.
///
/// For example for a type `(int, int)`, two comparisons could be done.
/// If the first ordering is different, the first ordering is all that must be returned.
/// If the first ordering is equal, then second ordering is returned.
#[inline]
#[deprecated = "Just call .cmp() on a tuple"]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
match o1 {
Equal => o2,
_ => o1
}
}
/// Trait for values that can be compared for a sort-order.
///
/// PartialOrd only requires implementation of the `partial_cmp` method,

View File

@ -428,27 +428,6 @@ pub trait Iterator<A> {
ByRef{iter: self}
}
/// Apply a function to each element, or stop iterating if the
/// function returns `false`.
///
/// # Example
///
/// ```rust,ignore
/// range(0u, 5).advance(|x| {print!("{} ", x); true});
/// ```
#[deprecated = "use the `all` method instead"]
#[inline]
fn advance(&mut self, f: |A| -> bool) -> bool {
loop {
match self.next() {
Some(x) => {
if !f(x) { return false; }
}
None => { return true; }
}
}
}
/// Loops through the entire iterator, collecting all of the elements into
/// a container implementing `FromIterator`.
///

View File

@ -20,9 +20,6 @@ by the compiler automatically for the types to which they apply.
*/
#[deprecated = "This has been renamed to Sync"]
pub use self::Sync as Share;
/// Types able to be transferred across task boundaries.
#[lang="send"]
pub trait Send for Sized? {

View File

@ -104,13 +104,6 @@ pub mod clone;
pub mod default;
pub mod collections;
#[deprecated = "all functionality now lives in `std::cell`"]
/// Deprecated module in favor of `std::cell`
pub mod ty {
#[deprecated = "this type has been renamed to `UnsafeCell`"]
pub use cell::UnsafeCell as Unsafe;
}
/* Core types and methods on primitives */
pub mod any;

View File

@ -14,7 +14,6 @@
//! types, initializing and manipulating memory.
use intrinsics;
use num::Int;
use ptr;
pub use intrinsics::transmute;
@ -43,26 +42,6 @@ pub fn size_of_val<T>(_val: &T) -> uint {
size_of::<T>()
}
/// Deprecated, this function will be removed soon
#[inline]
#[deprecated = "this function will be removed soon"]
pub fn nonzero_size_of<T>() -> uint {
match size_of::<T>() {
0 => 1,
n => n,
}
}
/// Deprecated, this function will be removed soon
#[inline]
#[deprecated = "this function will be removed soon"]
pub fn nonzero_size_of_val<T>(val: &T) -> uint {
match size_of_val::<T>(val) {
0 => 1,
n => n,
}
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller
@ -107,16 +86,6 @@ pub fn align_of_val<T>(_val: &T) -> uint {
align_of::<T>()
}
/// Deprecated, this function has been renamed to align_of
#[inline]
#[deprecated = "use mem::align_of instead"]
pub fn pref_align_of<T>() -> uint { align_of::<T>() }
/// Deprecated, this function has been renamed to align_of_val
#[inline]
#[deprecated = "use mem::align_of_val instead"]
pub fn pref_align_of_val<T>(val: &T) -> uint { align_of_val(val) }
/// Create a value initialized to zero.
///
/// This function is similar to allocating space for a a local variable and
@ -134,11 +103,6 @@ pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Deprecated, use zeroed() instead
#[inline]
#[deprecated = "this function has been renamed to zeroed()"]
pub unsafe fn init<T>() -> T { zeroed() }
/// Create an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a
@ -153,116 +117,6 @@ pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Deprecated, use `uninitialized` instead.
#[inline]
#[deprecated = "this function has been renamed to `uninitialized`"]
pub unsafe fn uninit<T>() -> T {
intrinsics::uninit()
}
/// Unsafely overwrite a memory location with the given value without destroying
/// the old value.
///
/// This operation is unsafe because it does not destroy the previous value
/// contained at the location `dst`. This could leak allocations or resources,
/// so care must be taken to previously deallocate the value at `dst`.
#[inline]
#[deprecated = "use ptr::write"]
pub unsafe fn overwrite<T>(dst: *mut T, src: T) {
intrinsics::move_val_init(&mut *dst, src)
}
/// Deprecated, use `overwrite` instead
#[inline]
#[deprecated = "this function has been renamed to overwrite()"]
pub unsafe fn move_val_init<T>(dst: &mut T, src: T) {
ptr::write(dst, src)
}
/// Convert an u16 to little endian from the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_le` instead"]
pub fn to_le16(x: u16) -> u16 { x.to_le() }
/// Convert an u32 to little endian from the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_le` instead"]
pub fn to_le32(x: u32) -> u32 { x.to_le() }
/// Convert an u64 to little endian from the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_le` instead"]
pub fn to_le64(x: u64) -> u64 { x.to_le() }
/// Convert an u16 to big endian from the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_be` instead"]
pub fn to_be16(x: u16) -> u16 { x.to_be() }
/// Convert an u32 to big endian from the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_be` instead"]
pub fn to_be32(x: u32) -> u32 { x.to_be() }
/// Convert an u64 to big endian from the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::to_be` instead"]
pub fn to_be64(x: u64) -> u64 { x.to_be() }
/// Convert an u16 from little endian to the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_le` instead"]
pub fn from_le16(x: u16) -> u16 { Int::from_le(x) }
/// Convert an u32 from little endian to the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_le` instead"]
pub fn from_le32(x: u32) -> u32 { Int::from_le(x) }
/// Convert an u64 from little endian to the target's endianness.
///
/// On little endian, this is a no-op. On big endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_le` instead"]
pub fn from_le64(x: u64) -> u64 { Int::from_le(x) }
/// Convert an u16 from big endian to the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_be` instead"]
pub fn from_be16(x: u16) -> u16 { Int::from_be(x) }
/// Convert an u32 from big endian to the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_be` instead"]
pub fn from_be32(x: u32) -> u32 { Int::from_be(x) }
/// Convert an u64 from big endian to the target's endianness.
///
/// On big endian, this is a no-op. On little endian, the bytes are swapped.
#[inline]
#[deprecated = "use `Int::from_be` instead"]
pub fn from_be64(x: u64) -> u64 { Int::from_be(x) }
/// Swap the values at two mutable locations of the same type, without
/// deinitialising or copying either one.
#[inline]

View File

@ -482,33 +482,6 @@ impl<T> Option<T> {
}
}
/// Deprecated.
///
/// Applies a function to the contained value or does nothing.
/// Returns true if the contained value was mutated.
#[deprecated = "removed due to lack of use"]
pub fn mutate(&mut self, f: |T| -> T) -> bool {
if self.is_some() {
*self = Some(f(self.take().unwrap()));
true
} else { false }
}
/// Deprecated.
///
/// Applies a function to the contained value or sets it to a default.
/// Returns true if the contained value was mutated, or false if set to the default.
#[deprecated = "removed due to lack of use"]
pub fn mutate_or_set(&mut self, def: T, f: |T| -> T) -> bool {
if self.is_some() {
*self = Some(f(self.take().unwrap()));
true
} else {
*self = Some(def);
false
}
}
/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
@ -530,12 +503,6 @@ impl<T> Option<T> {
Item{opt: self.as_ref()}
}
/// Deprecated: use `iter_mut`
#[deprecated = "use iter_mut"]
pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
self.iter_mut()
}
/// Returns a mutable iterator over the possibly contained value.
///
/// # Example
@ -557,12 +524,6 @@ impl<T> Option<T> {
Item{opt: self.as_mut()}
}
/// Deprecated: use `into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> Item<T> {
self.into_iter()
}
/// Returns a consuming iterator over the possibly contained value.
///
/// # Example
@ -713,100 +674,6 @@ impl<T> Option<T> {
pub fn take(&mut self) -> Option<T> {
mem::replace(self, None)
}
/// Deprecated.
///
/// Filters an optional value using a given function.
#[inline(always)]
#[deprecated = "removed due to lack of use"]
pub fn filtered(self, f: |t: &T| -> bool) -> Option<T> {
match self {
Some(x) => if f(&x) { Some(x) } else { None },
None => None
}
}
/// Deprecated.
///
/// Applies a function zero or more times until the result is `None`.
#[inline]
#[deprecated = "removed due to lack of use"]
pub fn while_some(self, f: |v: T| -> Option<T>) {
let mut opt = self;
loop {
match opt {
Some(x) => opt = f(x),
None => break
}
}
}
/////////////////////////////////////////////////////////////////////////
// Common special cases
/////////////////////////////////////////////////////////////////////////
/// Deprecated: use `take().unwrap()` instead.
///
/// The option dance. Moves a value out of an option type and returns it,
/// replacing the original with `None`.
///
/// # Failure
///
/// Fails if the value equals `None`.
#[inline]
#[deprecated = "use take().unwrap() instead"]
pub fn take_unwrap(&mut self) -> T {
match self.take() {
Some(x) => x,
None => fail!("called `Option::take_unwrap()` on a `None` value")
}
}
/// Deprecated: use `as_ref().unwrap()` instead.
///
/// Gets an immutable reference to the value inside an option.
///
/// # Failure
///
/// Fails if the value equals `None`
///
/// # Safety note
///
/// In general, because this function may fail, its use is discouraged
/// (calling `get` on `None` is akin to dereferencing a null pointer).
/// Instead, prefer to use pattern matching and handle the `None`
/// case explicitly.
#[inline]
#[deprecated = "use .as_ref().unwrap() instead"]
pub fn get_ref<'a>(&'a self) -> &'a T {
match *self {
Some(ref x) => x,
None => fail!("called `Option::get_ref()` on a `None` value"),
}
}
/// Deprecated: use `as_mut().unwrap()` instead.
///
/// Gets a mutable reference to the value inside an option.
///
/// # Failure
///
/// Fails if the value equals `None`
///
/// # Safety note
///
/// In general, because this function may fail, its use is discouraged
/// (calling `get` on `None` is akin to dereferencing a null pointer).
/// Instead, prefer to use pattern matching and handle the `None`
/// case explicitly.
#[inline]
#[deprecated = "use .as_mut().unwrap() instead"]
pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
match *self {
Some(ref mut x) => x,
None => fail!("called `Option::get_mut_ref()` on a `None` value"),
}
}
}
impl<T: Default> Option<T> {
@ -908,13 +775,6 @@ impl<A> ExactSize<A> for Item<A> {}
// Free functions
/////////////////////////////////////////////////////////////////////////////
/// Deprecated: use `Iterator::collect` instead.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(mut iter: Iter) -> Option<V> {
iter.collect()
}
impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V> {
/// Takes each element in the `Iterator`: if it is `None`, no further
/// elements are taken, and the `None` is returned. Should no `None` occur, a

View File

@ -90,7 +90,6 @@
use mem;
use clone::Clone;
use intrinsics;
use iter::range;
use option::{Some, None, Option};
use cmp::{PartialEq, Eq, PartialOrd, Equiv, Ordering, Less, Equal, Greater};
@ -113,10 +112,6 @@ pub use intrinsics::set_memory;
#[unstable = "may need a different name after pending changes to pointer types"]
pub fn null<T>() -> *const T { 0 as *const T }
/// Deprecated: use `null_mut`.
#[deprecated = "use null_mut"]
pub fn mut_null<T>() -> *mut T { null_mut() }
/// Create an unsafe mutable null pointer.
///
/// # Example
@ -203,59 +198,6 @@ pub unsafe fn write<T>(dst: *mut T, src: T) {
intrinsics::move_val_init(&mut *dst, src)
}
/// Given a *const *const T (pointer to an array of pointers),
/// iterate through each *const T, up to the provided `len`,
/// passing to the provided callback function
#[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
pub unsafe fn array_each_with_len<T>(arr: *const *const T, len: uint,
cb: |*const T|) {
if arr.is_null() {
fail!("ptr::array_each_with_len failure: arr input is null pointer");
}
//let start_ptr = *arr;
for e in range(0, len) {
let n = arr.offset(e as int);
cb(*n);
}
}
/// Given a null-pointer-terminated *const *const T (pointer to
/// an array of pointers), iterate through each *const T,
/// passing to the provided callback function
///
/// # Safety Note
///
/// This will only work with a null-terminated
/// pointer array.
#[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
#[allow(deprecated)]
pub unsafe fn array_each<T>(arr: *const *const T, cb: |*const T|) {
if arr.is_null() {
fail!("ptr::array_each_with_len failure: arr input is null pointer");
}
let len = buf_len(arr);
array_each_with_len(arr, len, cb);
}
/// Return the offset of the first null pointer in `buf`.
#[inline]
#[deprecated = "use a loop and RawPtr::offset"]
#[allow(deprecated)]
pub unsafe fn buf_len<T>(buf: *const *const T) -> uint {
position(buf, |i| *i == null())
}
/// Return the first offset `i` such that `f(buf[i]) == true`.
#[inline]
#[deprecated = "old-style iteration. use a loop and RawPtr::offset"]
pub unsafe fn position<T>(buf: *const T, f: |&T| -> bool) -> uint {
let mut i = 0;
loop {
if f(&(*buf.offset(i as int))) { return i; }
else { i += 1; }
}
}
/// Methods on raw pointers
pub trait RawPtr<T> {
/// Returns the null pointer.
@ -280,12 +222,6 @@ pub trait RawPtr<T> {
/// the returned value could be pointing to invalid memory.
unsafe fn as_ref<'a>(&self) -> Option<&'a T>;
/// A synonym for `as_ref`, except with incorrect lifetime semantics
#[deprecated="Use `as_ref` instead"]
unsafe fn to_option<'a>(&'a self) -> Option<&'a T> {
mem::transmute(self.as_ref())
}
/// Calculates the offset from a pointer. The offset *must* be in-bounds of
/// the object, or one-byte-past-the-end. `count` is in units of T; e.g. a
/// `count` of 3 represents a pointer offset of `3 * sizeof::<T>()` bytes.

View File

@ -566,12 +566,6 @@ impl<T, E> Result<T, E> {
Item{opt: self.as_ref().ok()}
}
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
self.iter_mut()
}
/// Returns a mutable iterator over the possibly contained value.
///
/// # Example
@ -593,12 +587,6 @@ impl<T, E> Result<T, E> {
Item{opt: self.as_mut().ok()}
}
/// Deprecated: `use into_iter`.
#[deprecated = "use into_iter"]
pub fn move_iter(self) -> Item<T> {
self.into_iter()
}
/// Returns a consuming iterator over the possibly contained value.
///
/// # Example
@ -771,13 +759,6 @@ impl<T, E> Result<T, E> {
Err(e) => op(e)
}
}
/// Deprecated name for `unwrap_or_else()`.
#[deprecated = "replaced by .unwrap_or_else()"]
#[inline]
pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
self.unwrap_or_else(op)
}
}
impl<T, E: Show> Result<T, E> {
@ -902,14 +883,6 @@ impl<A> ExactSize<A> for Item<A> {}
// Free functions
/////////////////////////////////////////////////////////////////////////////
/// Deprecated: use `Iterator::collect`.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(mut iter: Iter)
-> Result<V, E> {
iter.collect()
}
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
@ -984,16 +957,3 @@ pub fn fold<T,
}
Ok(init)
}
/// Deprecated.
///
/// Perform a trivial fold operation over the result values
/// from an iterator.
///
/// If an `Err` is encountered, it is immediately returned.
/// Otherwise, a simple `Ok(())` is returned.
#[inline]
#[deprecated = "use fold instead"]
pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
fold(iterator, (), |_, _| ())
}

View File

@ -176,27 +176,14 @@ pub trait ImmutableSlice<'a, T> {
#[unstable = "name may change"]
fn tail(&self) -> &'a [T];
/// Returns all but the first `n' elements of a slice.
#[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T];
/// Returns all but the last element of a slice.
#[unstable = "name may change"]
fn init(&self) -> &'a [T];
/// Returns all but the last `n' elements of a slice.
#[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T];
/// Returns the last element of a slice, or `None` if it is empty.
#[unstable = "name may change"]
fn last(&self) -> Option<&'a T>;
/// Returns a pointer to the element at the given index, without doing
/// bounds checking.
#[deprecated = "renamed to `unsafe_get`"]
unsafe fn unsafe_ref(self, index: uint) -> &'a T;
/// Returns a pointer to the element at the given index, without doing
/// bounds checking.
#[unstable]
@ -212,10 +199,6 @@ pub trait ImmutableSlice<'a, T> {
#[unstable]
fn as_ptr(&self) -> *const T;
/// Deprecated: use `binary_search`.
#[deprecated = "use binary_search"]
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
/// Binary search a sorted slice with a comparator function.
///
/// The comparator function should implement an order consistent
@ -251,44 +234,6 @@ pub trait ImmutableSlice<'a, T> {
/// ```
#[unstable = "waiting on unboxed closures"]
fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult;
/**
* Returns an immutable reference to the first element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None }
* let head = &self[0];
* *self = self[1..];
* Some(head)
* ```
*
* Returns `None` if vector is empty
*/
#[deprecated = "find some other way. sorry"]
fn shift_ref(&mut self) -> Option<&'a T>;
/**
* Returns an immutable reference to the last element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None; }
* let tail = &self[self.len() - 1];
* *self = self[..self.len() - 1];
* Some(tail)
* ```
*
* Returns `None` if slice is empty.
*/
#[deprecated = "find some other way. sorry"]
fn pop_ref(&mut self) -> Option<&'a T>;
}
#[unstable]
@ -388,32 +333,16 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
#[inline]
fn tail(&self) -> &'a [T] { (*self)[1..] }
#[inline]
#[deprecated = "use slice_from"]
fn tailn(&self, n: uint) -> &'a [T] { (*self)[n..] }
#[inline]
fn init(&self) -> &'a [T] {
(*self)[..self.len() - 1]
}
#[inline]
#[deprecated = "use slice_to but note the arguments are different"]
fn initn(&self, n: uint) -> &'a [T] {
(*self)[..self.len() - n]
}
#[inline]
fn last(&self) -> Option<&'a T> {
if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
}
#[inline]
#[deprecated = "renamed to `unsafe_get`"]
unsafe fn unsafe_ref(self, index: uint) -> &'a T {
transmute(self.repr().data.offset(index as int))
}
#[inline]
unsafe fn unsafe_get(self, index: uint) -> &'a T {
transmute(self.repr().data.offset(index as int))
@ -424,27 +353,6 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
self.repr().data
}
#[deprecated = "use binary_search"]
fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
let mut base : uint = 0;
let mut lim : uint = self.len();
while lim != 0 {
let ix = base + (lim >> 1);
match f(&self[ix]) {
Equal => return Some(ix),
Less => {
base = ix + 1;
lim -= 1;
}
Greater => ()
}
lim >>= 1;
}
return None;
}
#[unstable]
fn binary_search(&self, f: |&T| -> Ordering) -> BinarySearchResult {
let mut base : uint = 0;
@ -464,26 +372,6 @@ impl<'a,T> ImmutableSlice<'a, T> for &'a [T] {
}
return NotFound(base);
}
fn shift_ref(&mut self) -> Option<&'a T> {
unsafe {
let s: &mut RawSlice<T> = transmute(self);
match raw::shift_ptr(s) {
Some(p) => Some(&*p),
None => None
}
}
}
fn pop_ref(&mut self) -> Option<&'a T> {
unsafe {
let s: &mut RawSlice<T> = transmute(self);
match raw::pop_ptr(s) {
Some(p) => Some(&*p),
None => None
}
}
}
}
@ -557,12 +445,6 @@ pub trait MutableSlice<'a, T> {
/// Primarily intended for getting a &mut [T] from a [T, ..N].
fn as_mut_slice(self) -> &'a mut [T];
/// Deprecated: use `slice_mut`.
#[deprecated = "use slice_mut"]
fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
self.slice_mut(start, end)
}
/// Returns a mutable subslice spanning the interval [`start`, `end`).
///
/// Fails when the end of the new slice lies beyond the end of the
@ -572,12 +454,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on final error conventions"]
fn slice_mut(self, start: uint, end: uint) -> &'a mut [T];
/// Deprecated: use `slice_from_mut`.
#[deprecated = "use slice_from_mut"]
fn mut_slice_from(self, start: uint) -> &'a mut [T] {
self.slice_from_mut(start)
}
/// Returns a mutable subslice from `start` to the end of the slice.
///
/// Fails when `start` is strictly greater than the length of the original slice.
@ -586,12 +462,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on final error conventions"]
fn slice_from_mut(self, start: uint) -> &'a mut [T];
/// Deprecated: use `slice_to_mut`.
#[deprecated = "use slice_to_mut"]
fn mut_slice_to(self, end: uint) -> &'a mut [T] {
self.slice_to_mut(end)
}
/// Returns a mutable subslice from the start of the slice to `end`.
///
/// Fails when `end` is strictly greater than the length of the original slice.
@ -600,12 +470,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on final error conventions"]
fn slice_to_mut(self, end: uint) -> &'a mut [T];
/// Deprecated: use `iter_mut`.
#[deprecated = "use iter_mut"]
fn mut_iter(self) -> MutItems<'a, T> {
self.iter_mut()
}
/// Returns an iterator that allows modifying each value
#[unstable = "waiting on iterator type name conventions"]
fn iter_mut(self) -> MutItems<'a, T>;
@ -622,22 +486,10 @@ pub trait MutableSlice<'a, T> {
#[unstable = "name may change"]
fn init_mut(self) -> &'a mut [T];
/// Deprecated: use `last_mut`.
#[deprecated = "use last_mut"]
fn mut_last(self) -> Option<&'a mut T> {
self.last_mut()
}
/// Returns a mutable pointer to the last item in the slice.
#[unstable = "name may change"]
fn last_mut(self) -> Option<&'a mut T>;
/// Deprecated: use `split_mut`.
#[deprecated = "use split_mut"]
fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
self.split_mut(pred)
}
/// Returns an iterator over mutable subslices separated by elements that
/// match `pred`. The matched element is not contained in the subslices.
#[unstable = "waiting on unboxed closures, iterator type name conventions"]
@ -656,12 +508,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on unboxed closures, iterator type name conventions"]
fn rsplitn_mut(self, n: uint, pred: |&T|: 'a -> bool) -> SplitsN<MutSplits<'a, T>>;
/// Deprecated: use `chunks_mut`.
#[deprecated = "use chunks_mut"]
fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
self.chunks_mut(chunk_size)
}
/// Returns an iterator over `chunk_size` elements of the slice at a time.
/// The chunks are mutable and do not overlap. If `chunk_size` does
/// not divide the length of the slice, then the last chunk will not
@ -673,44 +519,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on iterator type name conventions"]
fn chunks_mut(self, chunk_size: uint) -> MutChunks<'a, T>;
/**
* Returns a mutable reference to the first element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None; }
* let head = &mut self[0];
* *self = self[mut 1..];
* Some(head)
* ```
*
* Returns `None` if slice is empty
*/
#[deprecated = "use iter_mut"]
fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
/**
* Returns a mutable reference to the last element in this slice
* and adjusts the slice in place so that it no longer contains
* that element. O(1).
*
* Equivalent to:
*
* ```ignore
* if self.len() == 0 { return None; }
* let tail = &mut self[self.len() - 1];
* *self = self[mut ..self.len() - 1];
* Some(tail)
* ```
*
* Returns `None` if slice is empty.
*/
#[deprecated = "use iter_mut"]
fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
/// Swaps two elements in a slice.
///
/// Fails if `a` or `b` are out of bounds.
@ -730,12 +538,6 @@ pub trait MutableSlice<'a, T> {
#[unstable = "waiting on final error conventions"]
fn swap(self, a: uint, b: uint);
/// Deprecated: use `split_at_mut`.
#[deprecated = "use split_at_mut"]
fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
self.split_at_mut(mid)
}
/// Divides one `&mut` into two at an index.
///
/// The first will contain all indices from `[0, mid)` (excluding
@ -783,12 +585,6 @@ pub trait MutableSlice<'a, T> {
#[experimental = "may be moved to iterators instead"]
fn reverse(self);
/// Deprecated: use `unsafe_mut`.
#[deprecated = "use unsafe_mut"]
unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
self.unsafe_mut(index)
}
/// Returns an unsafe mutable pointer to the element in index
#[experimental = "waiting on unsafe conventions"]
unsafe fn unsafe_mut(self, index: uint) -> &'a mut T;
@ -803,18 +599,6 @@ pub trait MutableSlice<'a, T> {
#[inline]
#[unstable]
fn as_mut_ptr(self) -> *mut T;
/// Deprecated: use `*foo.as_mut_ptr().offset(index) = val` instead.
#[deprecated = "use `*foo.as_mut_ptr().offset(index) = val`"]
unsafe fn unsafe_set(self, index: uint, val: T);
/// Deprecated: use `ptr::write(foo.as_mut_ptr().offset(i), val)` instead.
#[deprecated = "use `ptr::write(foo.as_mut_ptr().offset(i), val)`"]
unsafe fn init_elem(self, i: uint, val: T);
/// Deprecated: use `as_mut_ptr` and `ptr::copy_memory` instead.
#[deprecated = "use as_mut_ptr and ptr::copy_memory"]
unsafe fn copy_memory(self, src: &[T]);
}
#[experimental = "trait is experimental"]
@ -920,30 +704,6 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
MutChunks { v: self, chunk_size: chunk_size }
}
fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
unsafe {
let s: &mut RawSlice<T> = transmute(self);
match raw::shift_ptr(s) {
// FIXME #13933: this `&` -> `&mut` cast is a little
// dubious
Some(p) => Some(&mut *(p as *mut _)),
None => None,
}
}
}
fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
unsafe {
let s: &mut RawSlice<T> = transmute(self);
match raw::pop_ptr(s) {
// FIXME #13933: this `&` -> `&mut` cast is a little
// dubious
Some(p) => Some(&mut *(p as *mut _)),
None => None,
}
}
}
fn swap(self, a: uint, b: uint) {
unsafe {
// Can't take two mutable loans from one vector, so instead just cast
@ -977,23 +737,6 @@ impl<'a,T> MutableSlice<'a, T> for &'a mut [T] {
fn as_mut_ptr(self) -> *mut T {
self.repr().data as *mut T
}
#[inline]
unsafe fn unsafe_set(self, index: uint, val: T) {
*self.unsafe_mut(index) = val;
}
#[inline]
unsafe fn init_elem(self, i: uint, val: T) {
ptr::write(&mut (*self.as_mut_ptr().offset(i as int)), val);
}
#[inline]
unsafe fn copy_memory(self, src: &[T]) {
let len_src = src.len();
assert!(self.len() >= len_src);
ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
}
}
/// Extension methods for slices containing `PartialEq` elements.
@ -1048,10 +791,6 @@ impl<'a,T:PartialEq> ImmutablePartialEqSlice<T> for &'a [T] {
/// Extension methods for slices containing `Ord` elements.
#[unstable = "may merge with other traits"]
pub trait ImmutableOrdSlice<T: Ord> {
/// Deprecated: use `binary_search_elem`.
#[deprecated = "use binary_search_elem"]
fn bsearch_elem(&self, x: &T) -> Option<uint>;
/// Binary search a sorted slice for a given element.
///
/// If the value is found then `Found` is returned, containing the
@ -1082,12 +821,6 @@ pub trait ImmutableOrdSlice<T: Ord> {
#[unstable = "trait is unstable"]
impl<'a, T: Ord> ImmutableOrdSlice<T> for &'a [T] {
#[deprecated = "use binary_search_elem"]
#[allow(deprecated)]
fn bsearch_elem(&self, x: &T) -> Option<uint> {
self.bsearch(|p| p.cmp(x))
}
#[unstable]
fn binary_search_elem(&self, x: &T) -> BinarySearchResult {
self.binary_search(|p| p.cmp(x))
@ -1097,12 +830,6 @@ impl<'a, T: Ord> ImmutableOrdSlice<T> for &'a [T] {
/// Trait for &[T] where T is Cloneable
#[unstable = "may merge with other traits"]
pub trait MutableCloneableSlice<T> {
/// Copies as many elements from `src` as it can into `self` (the
/// shorter of `self.len()` and `src.len()`). Returns the number
/// of elements copied.
#[deprecated = "renamed to clone_from_slice"]
fn copy_from(self, s: &[T]) -> uint { self.clone_from_slice(s) }
/// Copies as many elements from `src` as it can into `self` (the
/// shorter of `self.len()` and `src.len()`). Returns the number
/// of elements copied.
@ -1780,7 +1507,7 @@ pub mod raw {
pub mod bytes {
use collections::Collection;
use ptr;
use slice::MutableSlice;
use slice::{ImmutableSlice, MutableSlice};
/// A trait for operations on mutable `[u8]`s.
pub trait MutableByteVector {
@ -1801,10 +1528,14 @@ pub mod bytes {
/// `src` and `dst` must not overlap. Fails if the length of `dst`
/// is less than the length of `src`.
#[inline]
#[allow(deprecated)]
pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
// Bound checks are done at .copy_memory.
unsafe { dst.copy_memory(src) }
let len_src = src.len();
assert!(dst.len() >= len_src);
unsafe {
ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(),
src.as_ptr(),
len_src);
}
}
}

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::cmp::lexical_ordering;
use core::cmp::{ partial_min, partial_max };
#[test]
@ -42,21 +41,6 @@ fn test_ordering_order() {
assert_eq!(Greater.cmp(&Less), Greater);
}
#[test]
#[allow(deprecated)]
fn test_lexical_ordering() {
fn t(o1: Ordering, o2: Ordering, e: Ordering) {
assert_eq!(lexical_ordering(o1, o2), e);
}
let xs = [Less, Equal, Greater];
for &o in xs.iter() {
t(Less, o, Less);
t(Equal, o, o);
t(Greater, o, Greater);
}
}
#[test]
fn test_partial_min() {
use core::f64::NAN;

View File

@ -130,21 +130,6 @@ fn test_or_else() {
assert_eq!(x.or_else(|| None), None);
}
#[test]
#[allow(deprecated)]
fn test_option_while_some() {
let mut i = 0i;
Some(10i).while_some(|j| {
i += 1;
if j > 0 {
Some(j-1)
} else {
None
}
});
assert_eq!(i, 11);
}
#[test]
fn test_unwrap() {
assert_eq!(Some(1i).unwrap(), 1);
@ -184,15 +169,6 @@ fn test_unwrap_or_else() {
assert_eq!(x.unwrap_or_else(|| 2), 2);
}
#[test]
#[allow(deprecated)]
fn test_filtered() {
let some_stuff = Some(42i);
let modified_stuff = some_stuff.filtered(|&x| {x < 10});
assert_eq!(some_stuff.unwrap(), 42);
assert!(modified_stuff.is_none());
}
#[test]
fn test_iter() {
let val = 5i;
@ -244,39 +220,22 @@ fn test_ord() {
}
#[test]
#[allow(deprecated)]
fn test_mutate() {
let mut x = Some(3i);
assert!(x.mutate(|i| i+1));
assert_eq!(x, Some(4i));
assert!(x.mutate_or_set(0, |i| i+1));
assert_eq!(x, Some(5i));
x = None;
assert!(!x.mutate(|i| i+1));
assert_eq!(x, None);
assert!(!x.mutate_or_set(0i, |i| i+1));
assert_eq!(x, Some(0i));
}
#[test]
#[allow(deprecated)]
fn test_collect() {
let v: Option<Vec<int>> = collect(range(0i, 0)
.map(|_| Some(0i)));
let v: Option<Vec<int>> = range(0i, 0).map(|_| Some(0i)).collect();
assert!(v == Some(vec![]));
let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| Some(x)));
let v: Option<Vec<int>> = range(0i, 3).map(|x| Some(x)).collect();
assert!(v == Some(vec![0, 1, 2]));
let v: Option<Vec<int>> = collect(range(0i, 3)
.map(|x| if x > 1 { None } else { Some(x) }));
let v: Option<Vec<int>> = range(0i, 3).map(|x| {
if x > 1 { None } else { Some(x) }
}).collect();
assert!(v == None);
// test that it does not take more elements than it needs
let mut functions = [|| Some(()), || None, || fail!()];
let v: Option<Vec<()>> = collect(functions.iter_mut().map(|f| (*f)()));
let v: Option<Vec<()>> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == None);
}

View File

@ -7,12 +7,9 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(deprecated)]
use core::ptr::*;
use libc::c_char;
use core::mem;
use libc;
use std::c_str::CString;
#[test]
fn test() {
@ -39,49 +36,22 @@ fn test() {
copy_memory(v1.as_mut_ptr().offset(1),
v0.as_ptr().offset(1), 1);
assert!((*v1.get(0) == 0u16 &&
*v1.get(1) == 32001u16 &&
*v1.get(2) == 0u16));
assert!((v1[0] == 0u16 &&
v1[1] == 32001u16 &&
v1[2] == 0u16));
copy_memory(v1.as_mut_ptr(),
v0.as_ptr().offset(2), 1);
assert!((*v1.get(0) == 32002u16 &&
*v1.get(1) == 32001u16 &&
*v1.get(2) == 0u16));
assert!((v1[0] == 32002u16 &&
v1[1] == 32001u16 &&
v1[2] == 0u16));
copy_memory(v1.as_mut_ptr().offset(2),
v0.as_ptr(), 1u);
assert!((*v1.get(0) == 32002u16 &&
*v1.get(1) == 32001u16 &&
*v1.get(2) == 32000u16));
assert!((v1[0] == 32002u16 &&
v1[1] == 32001u16 &&
v1[2] == 32000u16));
}
}
#[test]
fn test_position() {
use libc::c_char;
"hello".with_c_str(|p| {
unsafe {
assert!(2u == position(p, |c| *c == 'l' as c_char));
assert!(4u == position(p, |c| *c == 'o' as c_char));
assert!(5u == position(p, |c| *c == 0 as c_char));
}
})
}
#[test]
fn test_buf_len() {
"hello".with_c_str(|p0| {
"there".with_c_str(|p1| {
"thing".with_c_str(|p2| {
let v = vec![p0, p1, p2, null()];
unsafe {
assert_eq!(buf_len(v.as_ptr()), 3u);
}
})
})
})
}
#[test]
fn test_is_null() {
let p: *const int = null();
@ -92,7 +62,7 @@ fn test_is_null() {
assert!(!q.is_null());
assert!(q.is_not_null());
let mp: *mut int = mut_null();
let mp: *mut int = null_mut();
assert!(mp.is_null());
assert!(!mp.is_not_null());
@ -110,7 +80,7 @@ fn test_as_ref() {
let q: *const int = &2;
assert_eq!(q.as_ref().unwrap(), &2);
let p: *mut int = mut_null();
let p: *mut int = null_mut();
assert_eq!(p.as_ref(), None);
let q: *mut int = &mut 2;
@ -128,7 +98,7 @@ fn test_as_ref() {
#[test]
fn test_as_mut() {
unsafe {
let p: *mut int = mut_null();
let p: *mut int = null_mut();
assert!(p.as_mut() == None);
let q: *mut int = &mut 2;
@ -193,82 +163,6 @@ fn test_ptr_subtraction() {
}
}
#[test]
fn test_ptr_array_each_with_len() {
unsafe {
let one = "oneOne".to_c_str();
let two = "twoTwo".to_c_str();
let three = "threeThree".to_c_str();
let arr = vec![
one.as_ptr(),
two.as_ptr(),
three.as_ptr()
];
let expected_arr = [
one, two, three
];
let mut ctr = 0;
let mut iteration_count = 0;
array_each_with_len(arr.as_ptr(), arr.len(), |e| {
let actual = CString::new(e, false);
assert_eq!(actual.as_str(), expected_arr[ctr].as_str());
ctr += 1;
iteration_count += 1;
});
assert_eq!(iteration_count, 3u);
}
}
#[test]
fn test_ptr_array_each() {
unsafe {
let one = "oneOne".to_c_str();
let two = "twoTwo".to_c_str();
let three = "threeThree".to_c_str();
let arr = vec![
one.as_ptr(),
two.as_ptr(),
three.as_ptr(),
// fake a null terminator
null()
];
let expected_arr = [
one, two, three
];
let arr_ptr = arr.as_ptr();
let mut ctr = 0u;
let mut iteration_count = 0u;
array_each(arr_ptr, |e| {
let actual = CString::new(e, false);
assert_eq!(actual.as_str(), expected_arr[ctr].as_str());
ctr += 1;
iteration_count += 1;
});
assert_eq!(iteration_count, 3);
}
}
#[test]
#[should_fail]
fn test_ptr_array_each_with_len_null_ptr() {
unsafe {
array_each_with_len(0 as *const *const libc::c_char, 1, |e| {
CString::new(e, false).as_str().unwrap();
});
}
}
#[test]
#[should_fail]
fn test_ptr_array_each_null_ptr() {
unsafe {
array_each(0 as *const *const libc::c_char, |e| {
CString::new(e, false).as_str().unwrap();
});
}
}
#[test]
fn test_set_memory() {
let mut xs = [0u8, ..20];

View File

@ -8,7 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::result::{collect, fold, fold_};
use core::iter::range;
pub fn op1() -> Result<int, &'static str> { Ok(666) }
@ -69,47 +68,25 @@ pub fn test_impl_map_err() {
}
#[test]
#[allow(deprecated)]
fn test_collect() {
let v: Result<Vec<int>, ()> = collect(range(0i, 0).map(|_| Ok::<int, ()>(0)));
let v: Result<Vec<int>, ()> = range(0i, 0).map(|_| Ok::<int, ()>(0)).collect();
assert!(v == Ok(vec![]));
let v: Result<Vec<int>, ()> = collect(range(0i, 3).map(|x| Ok::<int, ()>(x)));
let v: Result<Vec<int>, ()> = range(0i, 3).map(|x| Ok::<int, ()>(x)).collect();
assert!(v == Ok(vec![0, 1, 2]));
let v: Result<Vec<int>, int> = collect(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(x) }));
let v: Result<Vec<int>, int> = range(0i, 3).map(|x| {
if x > 1 { Err(x) } else { Ok(x) }
}).collect();
assert!(v == Err(2));
// test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1i), || fail!()];
let v: Result<Vec<()>, int> = collect(functions.iter_mut().map(|f| (*f)()));
let v: Result<Vec<()>, int> = functions.iter_mut().map(|f| (*f)()).collect();
assert!(v == Err(1));
}
#[test]
#[allow(deprecated)] // we know fold_ is deprecated
fn test_fold() {
assert_eq!(fold_(range(0i, 0)
.map(|_| Ok::<(), ()>(()))),
Ok(()));
assert_eq!(fold(range(0i, 3)
.map(|x| Ok::<int, ()>(x)),
0, |a, b| a + b),
Ok(3));
assert_eq!(fold_(range(0i, 3)
.map(|x| if x > 1 { Err(x) } else { Ok(()) })),
Err(2));
// test that it does not take more elements than it needs
let mut functions = [|| Ok(()), || Err(1i), || fail!()];
assert_eq!(fold_(functions.iter_mut()
.map(|f| (*f)())),
Err(1));
}
#[test]
pub fn test_fmt_default() {
let ok: Result<int, &'static str> = Ok(100);

View File

@ -1,163 +0,0 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Syntax extension to generate FourCCs.
Once loaded, fourcc!() is called with a single 4-character string,
and an optional ident that is either `big`, `little`, or `target`.
The ident represents endianness, and specifies in which direction
the characters should be read. If the ident is omitted, it is assumed
to be `big`, i.e. left-to-right order. It returns a u32.
# Examples
To load the extension and use it:
```rust,ignore
#[phase(plugin)]
extern crate fourcc;
fn main() {
let val = fourcc!("\xC0\xFF\xEE!");
assert_eq!(val, 0xC0FFEE21u32);
let little_val = fourcc!("foo ", little);
assert_eq!(little_val, 0x21EEFFC0u32);
}
```
# References
* [Wikipedia: FourCC](http://en.wikipedia.org/wiki/FourCC)
*/
#![crate_name = "fourcc"]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/fourcc"]
#![allow(deprecated)]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(plugin_registrar)]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::attr::contains;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, MacExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::parse::token::InternedString;
use syntax::ptr::P;
use rustc::plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("fourcc", expand_syntax_ext);
}
pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'cx> {
let (expr, endian) = parse_tts(cx, tts);
let little = match endian {
None => false,
Some(Ident{ident, span}) => match token::get_ident(ident).get() {
"little" => true,
"big" => false,
"target" => target_endian_little(cx, sp),
_ => {
cx.span_err(span, "invalid endian directive in fourcc!");
target_endian_little(cx, sp)
}
}
};
let s = match expr.node {
// expression is a literal
ast::ExprLit(ref lit) => match lit.node {
// string literal
ast::LitStr(ref s, _) => {
if s.get().char_len() != 4 {
cx.span_err(expr.span, "string literal with len != 4 in fourcc!");
}
s
}
_ => {
cx.span_err(expr.span, "unsupported literal in fourcc!");
return base::DummyResult::expr(sp)
}
},
_ => {
cx.span_err(expr.span, "non-literal in fourcc!");
return base::DummyResult::expr(sp)
}
};
let mut val = 0u32;
for codepoint in s.get().chars().take(4) {
let byte = if codepoint as u32 > 0xFF {
cx.span_err(expr.span, "fourcc! literal character out of range 0-255");
0u8
} else {
codepoint as u8
};
val = if little {
(val >> 8) | ((byte as u32) << 24)
} else {
(val << 8) | (byte as u32)
};
}
let e = cx.expr_lit(sp, ast::LitInt(val as u64, ast::UnsignedIntLit(ast::TyU32)));
MacExpr::new(e)
}
struct Ident {
ident: ast::Ident,
span: Span
}
fn parse_tts(cx: &ExtCtxt,
tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) {
let p = &mut cx.new_parser_from_tts(tts);
let ex = p.parse_expr();
let id = if p.token == token::EOF {
None
} else {
p.expect(&token::COMMA);
let lo = p.span.lo;
let ident = p.parse_ident();
let hi = p.last_span.hi;
Some(Ident{ident: ident, span: mk_sp(lo, hi)})
};
if p.token != token::EOF {
p.unexpected();
}
(ex, id)
}
fn target_endian_little(cx: &ExtCtxt, sp: Span) -> bool {
let meta = cx.meta_name_value(sp, InternedString::new("target_endian"),
ast::LitStr(InternedString::new("little"), ast::CookedStr));
contains(cx.cfg().as_slice(), &*meta)
}
// FIXME (10872): This is required to prevent an LLVM assert on Windows
#[test]
fn dummy_test() { }

View File

@ -1,893 +0,0 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Support for matching file paths against Unix shell style patterns.
*
* The `glob` and `glob_with` functions, in concert with the `Paths`
* type, allow querying the filesystem for all files that match a particular
* pattern - just like the libc `glob` function (for an example see the `glob`
* documentation). The methods on the `Pattern` type provide functionality
* for checking if individual paths match a particular pattern - in a similar
* manner to the libc `fnmatch` function
*
* For consistency across platforms, and for Windows support, this module
* is implemented entirely in Rust rather than deferring to the libc
* `glob`/`fnmatch` functions.
*/
#![crate_name = "glob"]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/glob"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(deprecated)]
use std::cell::Cell;
use std::{cmp, os, path};
use std::io::fs::PathExtensions;
use std::io::fs;
use std::path::is_sep;
use std::string::String;
/**
* An iterator that yields Paths from the filesystem that match a particular
* pattern - see the `glob` function for more details.
*/
pub struct Paths {
dir_patterns: Vec<Pattern>,
require_dir: bool,
options: MatchOptions,
todo: Vec<(Path,uint)>,
}
///
/// Return an iterator that produces all the Paths that match the given pattern,
/// which may be absolute or relative to the current working directory.
///
/// This method uses the default match options and is equivalent to calling
/// `glob_with(pattern, MatchOptions::new())`. Use `glob_with` directly if you
/// want to use non-default match options.
///
/// # Example
///
/// Consider a directory `/media/pictures` containing only the files `kittens.jpg`,
/// `puppies.jpg` and `hamsters.gif`:
///
/// ```rust
/// # #![allow(deprecated)]
/// use glob::glob;
///
/// for path in glob("/media/pictures/*.jpg") {
/// println!("{}", path.display());
/// }
/// ```
///
/// The above code will print:
///
/// ```ignore
/// /media/pictures/kittens.jpg
/// /media/pictures/puppies.jpg
/// ```
///
pub fn glob(pattern: &str) -> Paths {
glob_with(pattern, MatchOptions::new())
}
/**
* Return an iterator that produces all the Paths that match the given pattern,
* which may be absolute or relative to the current working directory.
*
* This function accepts Unix shell style patterns as described by `Pattern::new(..)`.
* The options given are passed through unchanged to `Pattern::matches_with(..)` with
* the exception that `require_literal_separator` is always set to `true` regardless of the
* value passed to this function.
*
* Paths are yielded in alphabetical order, as absolute paths.
*/
pub fn glob_with(pattern: &str, options: MatchOptions) -> Paths {
#[cfg(windows)]
fn check_windows_verbatim(p: &Path) -> bool { path::windows::is_verbatim(p) }
#[cfg(not(windows))]
fn check_windows_verbatim(_: &Path) -> bool { false }
// calculate root this way to handle volume-relative Windows paths correctly
let mut root = os::getcwd();
let pat_root = Path::new(pattern).root_path();
if pat_root.is_some() {
if check_windows_verbatim(pat_root.as_ref().unwrap()) {
// FIXME: How do we want to handle verbatim paths? I'm inclined to return nothing,
// since we can't very well find all UNC shares with a 1-letter server name.
return Paths {
dir_patterns: Vec::new(),
require_dir: false,
options: options,
todo: Vec::new(),
};
}
root.push(pat_root.as_ref().unwrap());
}
let root_len = pat_root.map_or(0u, |p| p.as_vec().len());
let dir_patterns = pattern.slice_from(cmp::min(root_len, pattern.len()))
.split_terminator(is_sep)
.map(|s| Pattern::new(s))
.collect::<Vec<Pattern>>();
let require_dir = pattern.chars().next_back().map(is_sep) == Some(true);
let mut todo = Vec::new();
if dir_patterns.len() > 0 {
// Shouldn't happen, but we're using -1 as a special index.
assert!(dir_patterns.len() < -1 as uint);
fill_todo(&mut todo, dir_patterns.as_slice(), 0, &root, options);
}
Paths {
dir_patterns: dir_patterns,
require_dir: require_dir,
options: options,
todo: todo,
}
}
impl Iterator<Path> for Paths {
fn next(&mut self) -> Option<Path> {
loop {
if self.dir_patterns.is_empty() || self.todo.is_empty() {
return None;
}
let (path,idx) = self.todo.pop().unwrap();
// idx -1: was already checked by fill_todo, maybe path was '.' or
// '..' that we can't match here because of normalization.
if idx == -1 as uint {
if self.require_dir && !path.is_dir() { continue; }
return Some(path);
}
let ref pattern = self.dir_patterns[idx];
if pattern.matches_with(match path.filename_str() {
// this ugly match needs to go here to avoid a borrowck error
None => {
// FIXME (#9639): How do we handle non-utf8 filenames? Ignore them for now
// Ideally we'd still match them against a *
continue;
}
Some(x) => x
}, self.options) {
if idx == self.dir_patterns.len() - 1 {
// it is not possible for a pattern to match a directory *AND* its children
// so we don't need to check the children
if !self.require_dir || path.is_dir() {
return Some(path);
}
} else {
fill_todo(&mut self.todo, self.dir_patterns.as_slice(),
idx + 1, &path, self.options);
}
}
}
}
}
fn list_dir_sorted(path: &Path) -> Option<Vec<Path>> {
match fs::readdir(path) {
Ok(mut children) => {
children.sort_by(|p1, p2| p2.filename().cmp(&p1.filename()));
Some(children.into_iter().collect())
}
Err(..) => None
}
}
/**
* A compiled Unix shell style pattern.
*/
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct Pattern {
tokens: Vec<PatternToken>,
}
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum PatternToken {
Char(char),
AnyChar,
AnySequence,
AnyWithin(Vec<CharSpecifier> ),
AnyExcept(Vec<CharSpecifier> )
}
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum CharSpecifier {
SingleChar(char),
CharRange(char, char)
}
#[deriving(PartialEq)]
enum MatchResult {
Match,
SubPatternDoesntMatch,
EntirePatternDoesntMatch
}
impl Pattern {
/**
* This function compiles Unix shell style patterns: `?` matches any single
* character, `*` matches any (possibly empty) sequence of characters and
* `[...]` matches any character inside the brackets, unless the first
* character is `!` in which case it matches any character except those
* between the `!` and the `]`. Character sequences can also specify ranges
* of characters, as ordered by Unicode, so e.g. `[0-9]` specifies any
* character between 0 and 9 inclusive.
*
* The metacharacters `?`, `*`, `[`, `]` can be matched by using brackets
* (e.g. `[?]`). When a `]` occurs immediately following `[` or `[!` then
* it is interpreted as being part of, rather then ending, the character
* set, so `]` and NOT `]` can be matched by `[]]` and `[!]]` respectively.
* The `-` character can be specified inside a character sequence pattern by
* placing it at the start or the end, e.g. `[abc-]`.
*
* When a `[` does not have a closing `]` before the end of the string then
* the `[` will be treated literally.
*/
pub fn new(pattern: &str) -> Pattern {
let chars = pattern.chars().collect::<Vec<_>>();
let mut tokens = Vec::new();
let mut i = 0;
while i < chars.len() {
match chars[i] {
'?' => {
tokens.push(AnyChar);
i += 1;
}
'*' => {
// *, **, ***, ****, ... are all equivalent
while i < chars.len() && chars[i] == '*' {
i += 1;
}
tokens.push(AnySequence);
}
'[' => {
if i <= chars.len() - 4 && chars[i + 1] == '!' {
match chars.slice_from(i + 3).position_elem(&']') {
None => (),
Some(j) => {
let chars = chars.slice(i + 2, i + 3 + j);
let cs = parse_char_specifiers(chars);
tokens.push(AnyExcept(cs));
i += j + 4;
continue;
}
}
}
else if i <= chars.len() - 3 && chars[i + 1] != '!' {
match chars.slice_from(i + 2).position_elem(&']') {
None => (),
Some(j) => {
let cs = parse_char_specifiers(chars.slice(i + 1, i + 2 + j));
tokens.push(AnyWithin(cs));
i += j + 3;
continue;
}
}
}
// if we get here then this is not a valid range pattern
tokens.push(Char('['));
i += 1;
}
c => {
tokens.push(Char(c));
i += 1;
}
}
}
Pattern { tokens: tokens }
}
/**
* Escape metacharacters within the given string by surrounding them in
* brackets. The resulting string will, when compiled into a `Pattern`,
* match the input string and nothing else.
*/
pub fn escape(s: &str) -> String {
let mut escaped = String::new();
for c in s.chars() {
match c {
// note that ! does not need escaping because it is only special inside brackets
'?' | '*' | '[' | ']' => {
escaped.push_char('[');
escaped.push_char(c);
escaped.push_char(']');
}
c => {
escaped.push_char(c);
}
}
}
escaped
}
/**
* Return if the given `str` matches this `Pattern` using the default
* match options (i.e. `MatchOptions::new()`).
*
* # Example
*
* ```rust
* #![allow(deprecated)]
* use glob::Pattern;
*
* assert!(Pattern::new("c?t").matches("cat"));
* assert!(Pattern::new("k[!e]tteh").matches("kitteh"));
* assert!(Pattern::new("d*g").matches("doog"));
* ```
*/
pub fn matches(&self, str: &str) -> bool {
self.matches_with(str, MatchOptions::new())
}
/**
* Return if the given `Path`, when converted to a `str`, matches this `Pattern`
* using the default match options (i.e. `MatchOptions::new()`).
*/
pub fn matches_path(&self, path: &Path) -> bool {
// FIXME (#9639): This needs to handle non-utf8 paths
path.as_str().map_or(false, |s| {
self.matches(s)
})
}
/**
* Return if the given `str` matches this `Pattern` using the specified match options.
*/
pub fn matches_with(&self, str: &str, options: MatchOptions) -> bool {
self.matches_from(None, str, 0, options) == Match
}
/**
* Return if the given `Path`, when converted to a `str`, matches this `Pattern`
* using the specified match options.
*/
pub fn matches_path_with(&self, path: &Path, options: MatchOptions) -> bool {
// FIXME (#9639): This needs to handle non-utf8 paths
path.as_str().map_or(false, |s| {
self.matches_with(s, options)
})
}
fn matches_from(&self,
prev_char: Option<char>,
mut file: &str,
i: uint,
options: MatchOptions) -> MatchResult {
let prev_char = Cell::new(prev_char);
let require_literal = |c| {
(options.require_literal_separator && is_sep(c)) ||
(options.require_literal_leading_dot && c == '.'
&& is_sep(prev_char.get().unwrap_or('/')))
};
for (ti, token) in self.tokens.slice_from(i).iter().enumerate() {
match *token {
AnySequence => {
loop {
match self.matches_from(prev_char.get(), file, i + ti + 1, options) {
SubPatternDoesntMatch => (), // keep trying
m => return m,
}
if file.is_empty() {
return EntirePatternDoesntMatch;
}
let (some_c, next) = file.slice_shift_char();
if require_literal(some_c.unwrap()) {
return SubPatternDoesntMatch;
}
prev_char.set(some_c);
file = next;
}
}
_ => {
if file.is_empty() {
return EntirePatternDoesntMatch;
}
let (some_c, next) = file.slice_shift_char();
let c = some_c.unwrap();
let matches = match *token {
AnyChar => {
!require_literal(c)
}
AnyWithin(ref specifiers) => {
!require_literal(c) &&
in_char_specifiers(specifiers.as_slice(),
c,
options)
}
AnyExcept(ref specifiers) => {
!require_literal(c) &&
!in_char_specifiers(specifiers.as_slice(),
c,
options)
}
Char(c2) => {
chars_eq(c, c2, options.case_sensitive)
}
AnySequence => {
unreachable!()
}
};
if !matches {
return SubPatternDoesntMatch;
}
prev_char.set(some_c);
file = next;
}
}
}
if file.is_empty() {
Match
} else {
SubPatternDoesntMatch
}
}
}
// Fills `todo` with paths under `path` to be matched by `patterns[idx]`,
// special-casing patterns to match `.` and `..`, and avoiding `readdir()`
// calls when there are no metacharacters in the pattern.
fn fill_todo(todo: &mut Vec<(Path, uint)>, patterns: &[Pattern], idx: uint, path: &Path,
options: MatchOptions) {
// convert a pattern that's just many Char(_) to a string
fn pattern_as_str(pattern: &Pattern) -> Option<String> {
let mut s = String::new();
for token in pattern.tokens.iter() {
match *token {
Char(c) => s.push_char(c),
_ => return None
}
}
return Some(s);
}
let add = |todo: &mut Vec<_>, next_path: Path| {
if idx + 1 == patterns.len() {
// We know it's good, so don't make the iterator match this path
// against the pattern again. In particular, it can't match
// . or .. globs since these never show up as path components.
todo.push((next_path, -1 as uint));
} else {
fill_todo(todo, patterns, idx + 1, &next_path, options);
}
};
let pattern = &patterns[idx];
match pattern_as_str(pattern) {
Some(s) => {
// This pattern component doesn't have any metacharacters, so we
// don't need to read the current directory to know where to
// continue. So instead of passing control back to the iterator,
// we can just check for that one entry and potentially recurse
// right away.
let special = "." == s.as_slice() || ".." == s.as_slice();
let next_path = path.join(s.as_slice());
if (special && path.is_dir()) || (!special && next_path.exists()) {
add(todo, next_path);
}
},
None => {
match list_dir_sorted(path) {
Some(entries) => {
todo.extend(entries.into_iter().map(|x|(x, idx)));
// Matching the special directory entries . and .. that refer to
// the current and parent directory respectively requires that
// the pattern has a leading dot, even if the `MatchOptions` field
// `require_literal_leading_dot` is not set.
if pattern.tokens.len() > 0 && pattern.tokens[0] == Char('.') {
for &special in [".", ".."].iter() {
if pattern.matches_with(special, options) {
add(todo, path.join(special));
}
}
}
}
None => {}
}
}
}
}
fn parse_char_specifiers(s: &[char]) -> Vec<CharSpecifier> {
let mut cs = Vec::new();
let mut i = 0;
while i < s.len() {
if i + 3 <= s.len() && s[i + 1] == '-' {
cs.push(CharRange(s[i], s[i + 2]));
i += 3;
} else {
cs.push(SingleChar(s[i]));
i += 1;
}
}
cs
}
fn in_char_specifiers(specifiers: &[CharSpecifier], c: char, options: MatchOptions) -> bool {
for &specifier in specifiers.iter() {
match specifier {
SingleChar(sc) => {
if chars_eq(c, sc, options.case_sensitive) {
return true;
}
}
CharRange(start, end) => {
// FIXME: work with non-ascii chars properly (issue #1347)
if !options.case_sensitive && c.is_ascii() && start.is_ascii() && end.is_ascii() {
let start = start.to_ascii().to_lowercase();
let end = end.to_ascii().to_lowercase();
let start_up = start.to_uppercase();
let end_up = end.to_uppercase();
// only allow case insensitive matching when
// both start and end are within a-z or A-Z
if start != start_up && end != end_up {
let start = start.to_char();
let end = end.to_char();
let c = c.to_ascii().to_lowercase().to_char();
if c >= start && c <= end {
return true;
}
}
}
if c >= start && c <= end {
return true;
}
}
}
}
false
}
/// A helper function to determine if two chars are (possibly case-insensitively) equal.
fn chars_eq(a: char, b: char, case_sensitive: bool) -> bool {
if cfg!(windows) && path::windows::is_sep(a) && path::windows::is_sep(b) {
true
} else if !case_sensitive && a.is_ascii() && b.is_ascii() {
// FIXME: work with non-ascii chars properly (issue #1347)
a.to_ascii().eq_ignore_case(b.to_ascii())
} else {
a == b
}
}
/**
* Configuration options to modify the behaviour of `Pattern::matches_with(..)`
*/
#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct MatchOptions {
/**
* Whether or not patterns should be matched in a case-sensitive manner. This
* currently only considers upper/lower case relationships between ASCII characters,
* but in future this might be extended to work with Unicode.
*/
pub case_sensitive: bool,
/**
* If this is true then path-component separator characters (e.g. `/` on Posix)
* must be matched by a literal `/`, rather than by `*` or `?` or `[...]`
*/
pub require_literal_separator: bool,
/**
* If this is true then paths that contain components that start with a `.` will
* not match unless the `.` appears literally in the pattern: `*`, `?` or `[...]`
* will not match. This is useful because such files are conventionally considered
* hidden on Unix systems and it might be desirable to skip them when listing files.
*/
pub require_literal_leading_dot: bool
}
impl MatchOptions {
/**
* Constructs a new `MatchOptions` with default field values. This is used
* when calling functions that do not take an explicit `MatchOptions` parameter.
*
* This function always returns this value:
*
* ```rust,ignore
* MatchOptions {
* case_sensitive: true,
* require_literal_separator: false.
* require_literal_leading_dot: false
* }
* ```
*/
pub fn new() -> MatchOptions {
MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: false
}
}
}
#[cfg(test)]
mod test {
use std::os;
use super::{glob, Pattern, MatchOptions};
#[test]
fn test_absolute_pattern() {
// assume that the filesystem is not empty!
assert!(glob("/*").next().is_some());
assert!(glob("//").next().is_some());
// check windows absolute paths with host/device components
let root_with_device = os::getcwd().root_path().unwrap().join("*");
// FIXME (#9639): This needs to handle non-utf8 paths
assert!(glob(root_with_device.as_str().unwrap()).next().is_some());
}
#[test]
fn test_wildcard_optimizations() {
assert!(Pattern::new("a*b").matches("a___b"));
assert!(Pattern::new("a**b").matches("a___b"));
assert!(Pattern::new("a***b").matches("a___b"));
assert!(Pattern::new("a*b*c").matches("abc"));
assert!(!Pattern::new("a*b*c").matches("abcd"));
assert!(Pattern::new("a*b*c").matches("a_b_c"));
assert!(Pattern::new("a*b*c").matches("a___b___c"));
assert!(Pattern::new("abc*abc*abc").matches("abcabcabcabcabcabcabc"));
assert!(!Pattern::new("abc*abc*abc").matches("abcabcabcabcabcabcabca"));
assert!(Pattern::new("a*a*a*a*a*a*a*a*a").matches("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
assert!(Pattern::new("a*b[xyz]c*d").matches("abxcdbxcddd"));
}
#[test]
#[cfg_attr(windows, ignore)] // FIXME (#9406)
fn test_lots_of_files() {
// this is a good test because it touches lots of differently named files
glob("/*/*/*/*").skip(10000).next();
}
#[test]
fn test_range_pattern() {
let pat = Pattern::new("a[0-9]b");
for i in range(0u, 10) {
assert!(pat.matches(format!("a{}b", i).as_slice()));
}
assert!(!pat.matches("a_b"));
let pat = Pattern::new("a[!0-9]b");
for i in range(0u, 10) {
assert!(!pat.matches(format!("a{}b", i).as_slice()));
}
assert!(pat.matches("a_b"));
let pats = ["[a-z123]", "[1a-z23]", "[123a-z]"];
for &p in pats.iter() {
let pat = Pattern::new(p);
for c in "abcdefghijklmnopqrstuvwxyz".chars() {
assert!(pat.matches(c.to_string().as_slice()));
}
for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() {
let options = MatchOptions {case_sensitive: false, .. MatchOptions::new()};
assert!(pat.matches_with(c.to_string().as_slice(), options));
}
assert!(pat.matches("1"));
assert!(pat.matches("2"));
assert!(pat.matches("3"));
}
let pats = ["[abc-]", "[-abc]", "[a-c-]"];
for &p in pats.iter() {
let pat = Pattern::new(p);
assert!(pat.matches("a"));
assert!(pat.matches("b"));
assert!(pat.matches("c"));
assert!(pat.matches("-"));
assert!(!pat.matches("d"));
}
let pat = Pattern::new("[2-1]");
assert!(!pat.matches("1"));
assert!(!pat.matches("2"));
assert!(Pattern::new("[-]").matches("-"));
assert!(!Pattern::new("[!-]").matches("-"));
}
#[test]
fn test_unclosed_bracket() {
// unclosed `[` should be treated literally
assert!(Pattern::new("abc[def").matches("abc[def"));
assert!(Pattern::new("abc[!def").matches("abc[!def"));
assert!(Pattern::new("abc[").matches("abc["));
assert!(Pattern::new("abc[!").matches("abc[!"));
assert!(Pattern::new("abc[d").matches("abc[d"));
assert!(Pattern::new("abc[!d").matches("abc[!d"));
assert!(Pattern::new("abc[]").matches("abc[]"));
assert!(Pattern::new("abc[!]").matches("abc[!]"));
}
#[test]
fn test_pattern_matches() {
let txt_pat = Pattern::new("*hello.txt");
assert!(txt_pat.matches("hello.txt"));
assert!(txt_pat.matches("gareth_says_hello.txt"));
assert!(txt_pat.matches("some/path/to/hello.txt"));
assert!(txt_pat.matches("some\\path\\to\\hello.txt"));
assert!(txt_pat.matches("/an/absolute/path/to/hello.txt"));
assert!(!txt_pat.matches("hello.txt-and-then-some"));
assert!(!txt_pat.matches("goodbye.txt"));
let dir_pat = Pattern::new("*some/path/to/hello.txt");
assert!(dir_pat.matches("some/path/to/hello.txt"));
assert!(dir_pat.matches("a/bigger/some/path/to/hello.txt"));
assert!(!dir_pat.matches("some/path/to/hello.txt-and-then-some"));
assert!(!dir_pat.matches("some/other/path/to/hello.txt"));
}
#[test]
fn test_pattern_escape() {
let s = "_[_]_?_*_!_";
assert_eq!(Pattern::escape(s), "_[[]_[]]_[?]_[*]_!_".to_string());
assert!(Pattern::new(Pattern::escape(s).as_slice()).matches(s));
}
#[test]
fn test_pattern_matches_case_insensitive() {
let pat = Pattern::new("aBcDeFg");
let options = MatchOptions {
case_sensitive: false,
require_literal_separator: false,
require_literal_leading_dot: false
};
assert!(pat.matches_with("aBcDeFg", options));
assert!(pat.matches_with("abcdefg", options));
assert!(pat.matches_with("ABCDEFG", options));
assert!(pat.matches_with("AbCdEfG", options));
}
#[test]
fn test_pattern_matches_case_insensitive_range() {
let pat_within = Pattern::new("[a]");
let pat_except = Pattern::new("[!a]");
let options_case_insensitive = MatchOptions {
case_sensitive: false,
require_literal_separator: false,
require_literal_leading_dot: false
};
let options_case_sensitive = MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: false
};
assert!(pat_within.matches_with("a", options_case_insensitive));
assert!(pat_within.matches_with("A", options_case_insensitive));
assert!(!pat_within.matches_with("A", options_case_sensitive));
assert!(!pat_except.matches_with("a", options_case_insensitive));
assert!(!pat_except.matches_with("A", options_case_insensitive));
assert!(pat_except.matches_with("A", options_case_sensitive));
}
#[test]
fn test_pattern_matches_require_literal_separator() {
let options_require_literal = MatchOptions {
case_sensitive: true,
require_literal_separator: true,
require_literal_leading_dot: false
};
let options_not_require_literal = MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: false
};
assert!(Pattern::new("abc/def").matches_with("abc/def", options_require_literal));
assert!(!Pattern::new("abc?def").matches_with("abc/def", options_require_literal));
assert!(!Pattern::new("abc*def").matches_with("abc/def", options_require_literal));
assert!(!Pattern::new("abc[/]def").matches_with("abc/def", options_require_literal));
assert!(Pattern::new("abc/def").matches_with("abc/def", options_not_require_literal));
assert!(Pattern::new("abc?def").matches_with("abc/def", options_not_require_literal));
assert!(Pattern::new("abc*def").matches_with("abc/def", options_not_require_literal));
assert!(Pattern::new("abc[/]def").matches_with("abc/def", options_not_require_literal));
}
#[test]
fn test_pattern_matches_require_literal_leading_dot() {
let options_require_literal_leading_dot = MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: true
};
let options_not_require_literal_leading_dot = MatchOptions {
case_sensitive: true,
require_literal_separator: false,
require_literal_leading_dot: false
};
let f = |options| Pattern::new("*.txt").matches_with(".hello.txt", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(!f(options_require_literal_leading_dot));
let f = |options| Pattern::new(".*.*").matches_with(".hello.txt", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(f(options_require_literal_leading_dot));
let f = |options| Pattern::new("aaa/bbb/*").matches_with("aaa/bbb/.ccc", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(!f(options_require_literal_leading_dot));
let f = |options| Pattern::new("aaa/bbb/*").matches_with("aaa/bbb/c.c.c.", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(f(options_require_literal_leading_dot));
let f = |options| Pattern::new("aaa/bbb/.*").matches_with("aaa/bbb/.ccc", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(f(options_require_literal_leading_dot));
let f = |options| Pattern::new("aaa/?bbb").matches_with("aaa/.bbb", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(!f(options_require_literal_leading_dot));
let f = |options| Pattern::new("aaa/[.]bbb").matches_with("aaa/.bbb", options);
assert!(f(options_not_require_literal_leading_dot));
assert!(!f(options_require_literal_leading_dot));
}
#[test]
fn test_matches_path() {
// on windows, (Path::new("a/b").as_str().unwrap() == "a\\b"), so this
// tests that / and \ are considered equivalent on windows
assert!(Pattern::new("a/b").matches_path(&Path::new("a/b")));
}
}

View File

@ -127,14 +127,6 @@ impl<'a,T:Clone> CloneableVector<T> for MaybeOwnedVector<'a,T> {
fn to_vec(&self) -> Vec<T> {
self.as_slice().to_vec()
}
/// Convert `self` into an owned slice, not making a copy if possible.
fn into_vec(self) -> Vec<T> {
match self {
Growable(v) => v.as_slice().to_vec(),
Borrowed(v) => v.to_vec(),
}
}
}
impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> {

View File

@ -89,7 +89,7 @@ impl BasicLoop {
fn idle(&mut self) {
match self.idle {
Some(ref mut idle) => {
if self.idle_active.get_ref().load(atomic::SeqCst) {
if self.idle_active.as_ref().unwrap().load(atomic::SeqCst) {
idle.call();
}
}
@ -98,7 +98,7 @@ impl BasicLoop {
}
fn has_idle(&self) -> bool {
self.idle.is_some() && self.idle_active.get_ref().load(atomic::SeqCst)
self.idle.is_some() && self.idle_active.as_ref().unwrap().load(atomic::SeqCst)
}
}

View File

@ -193,7 +193,7 @@ impl Scheduler {
// Before starting our first task, make sure the idle callback
// is active. As we do not start in the sleep state this is
// important.
self.idle_callback.get_mut_ref().resume();
self.idle_callback.as_mut().unwrap().resume();
// Now, as far as all the scheduler state is concerned, we are inside
// the "scheduler" context. The scheduler immediately hands over control
@ -213,10 +213,10 @@ impl Scheduler {
// cleaning up the memory it uses. As we didn't actually call
// task.run() on the scheduler task we never get through all
// the cleanup code it runs.
rtdebug!("stopping scheduler {}", stask.sched.get_ref().sched_id());
rtdebug!("stopping scheduler {}", stask.sched.as_ref().unwrap().sched_id());
// Should not have any messages
let message = stask.sched.get_mut_ref().message_queue.pop();
let message = stask.sched.as_mut().unwrap().message_queue.pop();
rtassert!(match message { msgq::Empty => true, _ => false });
stask.task.take().unwrap().drop();
@ -279,7 +279,7 @@ impl Scheduler {
// Assume that we need to continue idling unless we reach the
// end of this function without performing an action.
self.idle_callback.get_mut_ref().resume();
self.idle_callback.as_mut().unwrap().resume();
// First we check for scheduler messages, these are higher
// priority than regular tasks.
@ -333,12 +333,12 @@ impl Scheduler {
let handle = sched.make_handle();
sched.sleeper_list.push(handle);
// Since we are sleeping, deactivate the idle callback.
sched.idle_callback.get_mut_ref().pause();
sched.idle_callback.as_mut().unwrap().pause();
} else {
rtdebug!("not sleeping, already doing so or no_sleep set");
// We may not be sleeping, but we still need to deactivate
// the idle callback.
sched.idle_callback.get_mut_ref().pause();
sched.idle_callback.as_mut().unwrap().pause();
}
// Finished a cycle without using the Scheduler. Place it back
@ -633,7 +633,7 @@ impl Scheduler {
unsafe {
let sched: &mut Scheduler =
mem::transmute(&**next_task.sched.get_mut_ref());
mem::transmute(&**next_task.sched.as_mut().unwrap());
let current_task: &mut GreenTask = match sched.cleanup_job {
Some(CleanupJob { task: ref mut task, .. }) => &mut **task,
@ -661,7 +661,7 @@ impl Scheduler {
let mut current_task: Box<GreenTask> = unsafe {
mem::transmute(current_task_dupe)
};
current_task.sched.get_mut_ref().run_cleanup_job();
current_task.sched.as_mut().unwrap().run_cleanup_job();
// See the comments in switch_running_tasks_and_then for why a lock
// is acquired here. This is the resumption points and the "bounce"
@ -682,9 +682,9 @@ impl Scheduler {
-> (&'a mut Context, &'a mut Context)
{
let current_task_context =
&mut current_task.coroutine.get_mut_ref().saved_context;
&mut current_task.coroutine.as_mut().unwrap().saved_context;
let next_task_context =
&mut next_task.coroutine.get_mut_ref().saved_context;
&mut next_task.coroutine.as_mut().unwrap().saved_context;
unsafe {
(mem::transmute(current_task_context),
mem::transmute(next_task_context))
@ -1050,7 +1050,7 @@ mod test {
let mut task = Local::borrow(None::<Task>);
match task.maybe_take_runtime::<GreenTask>() {
Some(green) => {
let ret = green.sched.get_ref().sched_id();
let ret = green.sched.as_ref().unwrap().sched_id();
task.put_runtime(green);
return ret;
}
@ -1190,8 +1190,8 @@ mod test {
fn on_appropriate_sched() -> bool {
use task::{TypeGreen, TypeSched, HomeSched};
let task = GreenTask::convert(Local::take());
let sched_id = task.sched.get_ref().sched_id();
let run_any = task.sched.get_ref().run_anything;
let sched_id = task.sched.as_ref().unwrap().sched_id();
let run_any = task.sched.as_ref().unwrap().run_anything;
let ret = match task.task_type {
TypeGreen(Some(AnySched)) => {
run_any

View File

@ -100,7 +100,7 @@ extern fn bootstrap_green_task(task: uint, code: *mut (), env: *mut ()) -> ! {
// First code after swap to this new context. Run our cleanup job
task.pool_id = {
let sched = task.sched.get_mut_ref();
let sched = task.sched.as_mut().unwrap();
sched.run_cleanup_job();
sched.task_state.increment();
sched.pool_id
@ -179,7 +179,7 @@ impl GreenTask {
let mut green = GreenTask::new(pool, stack_size, f);
{
let task = green.task.get_mut_ref();
let task = green.task.as_mut().unwrap();
task.name = name;
task.death.on_exit = on_exit;
}
@ -314,7 +314,7 @@ impl GreenTask {
fn reawaken_remotely(mut self: Box<GreenTask>) {
unsafe {
let mtx = &mut self.nasty_deschedule_lock as *mut NativeMutex;
let handle = self.handle.get_mut_ref() as *mut SchedHandle;
let handle = self.handle.as_mut().unwrap() as *mut SchedHandle;
let _guard = (*mtx).lock();
(*handle).send(RunOnce(self));
}
@ -460,7 +460,7 @@ impl Runtime for GreenTask {
//
// Upon returning, our task is back in TLS and we're good to return.
let sibling = {
let sched = bomb.inner.get_mut_ref().sched.get_mut_ref();
let sched = bomb.inner.as_mut().unwrap().sched.as_mut().unwrap();
GreenTask::configure(&mut sched.stack_pool, opts, f)
};
let mut me = bomb.inner.take().unwrap();
@ -470,7 +470,7 @@ impl Runtime for GreenTask {
// Local I/O is provided by the scheduler's event loop
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> {
match self.sched.get_mut_ref().event_loop.io() {
match self.sched.as_mut().unwrap().event_loop.io() {
Some(io) => Some(rtio::LocalIo::new(io)),
None => None,
}

View File

@ -1,189 +0,0 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Syntax extension to create floating point literals from hexadecimal strings
Once loaded, hexfloat!() is called with a string containing the hexadecimal
floating-point literal, and an optional type (f32 or f64).
If the type is omitted, the literal is treated the same as a normal unsuffixed
literal.
# Examples
To load the extension and use it:
```rust,ignore
#[phase(plugin)]
extern crate hexfloat;
fn main() {
let val = hexfloat!("0x1.ffffb4", f32);
}
```
# References
* [ExploringBinary: hexadecimal floating point constants]
(http://www.exploringbinary.com/hexadecimal-floating-point-constants/)
*/
#![crate_name = "hexfloat"]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/hexfloat"]
#![allow(deprecated)]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(plugin_registrar)]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap::{Span, mk_sp};
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, MacExpr};
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;
use rustc::plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("hexfloat", expand_syntax_ext);
}
//Check if the literal is valid (as LLVM expects),
//and return a descriptive error if not.
fn hex_float_lit_err(s: &str) -> Option<(uint, String)> {
let mut chars = s.chars().peekable();
let mut i = 0;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
if chars.next() != Some('0') {
return Some((i, "Expected '0'".to_string()));
} i+=1;
if chars.next() != Some('x') {
return Some((i, "Expected 'x'".to_string()));
} i+=1;
let mut d_len = 0i;
for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; d_len += 1;}
if chars.next() != Some('.') {
return Some((i, "Expected '.'".to_string()));
} i+=1;
let mut f_len = 0i;
for _ in chars.take_while(|c| c.is_digit_radix(16)) { chars.next(); i+=1; f_len += 1;}
if d_len == 0 && f_len == 0 {
return Some((i, "Expected digits before or after decimal \
point".to_string()));
}
if chars.next() != Some('p') {
return Some((i, "Expected 'p'".to_string()));
} i+=1;
if chars.peek() == Some(&'-') { chars.next(); i+= 1 }
let mut e_len = 0i;
for _ in chars.take_while(|c| c.is_digit()) { chars.next(); i+=1; e_len += 1}
if e_len == 0 {
return Some((i, "Expected exponent digits".to_string()));
}
match chars.next() {
None => None,
Some(_) => Some((i, "Expected end of string".to_string()))
}
}
pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
-> Box<base::MacResult+'static> {
let (expr, ty_lit) = parse_tts(cx, tts);
let ty = match ty_lit {
None => None,
Some(Ident{ident, span}) => match token::get_ident(ident).get() {
"f32" => Some(ast::TyF32),
"f64" => Some(ast::TyF64),
_ => {
cx.span_err(span, "invalid floating point type in hexfloat!");
None
}
}
};
let s = match expr.node {
// expression is a literal
ast::ExprLit(ref lit) => match lit.node {
// string literal
ast::LitStr(ref s, _) => {
s.clone()
}
_ => {
cx.span_err(expr.span, "unsupported literal in hexfloat!");
return base::DummyResult::expr(sp);
}
},
_ => {
cx.span_err(expr.span, "non-literal in hexfloat!");
return base::DummyResult::expr(sp);
}
};
{
let err = hex_float_lit_err(s.get());
match err {
Some((err_pos, err_str)) => {
let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1);
let span = syntax::codemap::mk_sp(pos,pos);
cx.span_err(span,
format!("invalid hex float literal in hexfloat!: \
{}",
err_str).as_slice());
return base::DummyResult::expr(sp);
}
_ => ()
}
}
let lit = match ty {
None => ast::LitFloatUnsuffixed(s),
Some (ty) => ast::LitFloat(s, ty)
};
MacExpr::new(cx.expr_lit(sp, lit))
}
struct Ident {
ident: ast::Ident,
span: Span
}
fn parse_tts(cx: &ExtCtxt,
tts: &[ast::TokenTree]) -> (P<ast::Expr>, Option<Ident>) {
let p = &mut cx.new_parser_from_tts(tts);
let ex = p.parse_expr();
let id = if p.token == token::EOF {
None
} else {
p.expect(&token::COMMA);
let lo = p.span.lo;
let ident = p.parse_ident();
let hi = p.last_span.hi;
Some(Ident{ident: ident, span: mk_sp(lo, hi)})
};
if p.token != token::EOF {
p.unexpected();
}
(ex, id)
}
// FIXME (10872): This is required to prevent an LLVM assert on Windows
#[test]
fn dummy_test() { }

View File

@ -11,7 +11,7 @@
use libc::{c_char, c_int};
use libc;
use std::mem;
use std::ptr::{null, mut_null};
use std::ptr::{null, null_mut};
use std::rt::rtio;
use std::rt::rtio::IoError;
@ -38,16 +38,16 @@ impl GetAddrInfoRequest {
ai_socktype: 0,
ai_protocol: 0,
ai_addrlen: 0,
ai_canonname: mut_null(),
ai_addr: mut_null(),
ai_next: mut_null()
ai_canonname: null_mut(),
ai_addr: null_mut(),
ai_next: null_mut()
}
});
let hint_ptr = hint.as_ref().map_or(null(), |x| {
x as *const libc::addrinfo
});
let mut res = mut_null();
let mut res = null_mut();
// Make the call
let s = unsafe {

View File

@ -141,8 +141,8 @@ pub mod compat {
// layer (after it's loaded) shouldn't be any slower than a regular DLL
// call.
unsafe fn store_func(ptr: *mut uint, module: &str, symbol: &str, fallback: uint) {
let module: Vec<u16> = module.utf16_units().collect();
let module = module.append_one(0);
let mut module: Vec<u16> = module.utf16_units().collect();
module.push(0);
symbol.with_c_str(|symbol| {
let handle = GetModuleHandleW(module.as_ptr());
let func: uint = transmute(GetProcAddress(handle, symbol));

View File

@ -253,7 +253,11 @@ impl Drop for Inner {
pub fn to_utf16(s: &CString) -> IoResult<Vec<u16>> {
match s.as_str() {
Some(s) => Ok(s.utf16_units().collect::<Vec<u16>>().append_one(0)),
Some(s) => Ok({
let mut s = s.utf16_units().collect::<Vec<u16>>();
s.push(0);
s
}),
None => Err(IoError {
code: libc::ERROR_INVALID_NAME as uint,
extra: 0,

View File

@ -22,13 +22,14 @@
#![macro_escape]
use std::cell::UnsafeCell;
use std::mem;
use std::rt::bookkeeping;
use std::rt::mutex::StaticNativeMutex;
use std::rt;
use std::cell::UnsafeCell;
use std::task::TaskBuilder;
use task;
use NativeTaskBuilder;
/// A structure for management of a helper thread.
///
@ -86,7 +87,7 @@ impl<M: Send> Helper<M> {
*self.signal.get() = send as uint;
let t = f();
task::spawn(proc() {
TaskBuilder::new().native().spawn(proc() {
bookkeeping::decrement();
helper(receive, rx, t);
self.lock.lock().signal()

View File

@ -359,7 +359,7 @@ impl rtio::RtioPipe for UnixStream {
let mut bytes_read = 0;
let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() };
overlapped.hEvent = self.read.get_ref().handle();
overlapped.hEvent = self.read.as_ref().unwrap().handle();
// Pre-flight check to see if the reading half has been closed. This
// must be done before issuing the ReadFile request, but after we
@ -431,7 +431,7 @@ impl rtio::RtioPipe for UnixStream {
let mut offset = 0;
let mut overlapped: libc::OVERLAPPED = unsafe { mem::zeroed() };
overlapped.hEvent = self.write.get_ref().handle();
overlapped.hEvent = self.write.as_ref().unwrap().handle();
while offset < buf.len() {
let mut bytes_written = 0;

View File

@ -350,8 +350,8 @@ fn spawn_process_os(cfg: ProcessConfig,
lpSecurityDescriptor: ptr::null_mut(),
bInheritHandle: 1,
};
let filename: Vec<u16> = "NUL".utf16_units().collect();
let filename = filename.append_one(0);
let mut filename: Vec<u16> = "NUL".utf16_units().collect();
filename.push(0);
*slot = libc::CreateFileW(filename.as_ptr(),
access,
libc::FILE_SHARE_READ |
@ -396,7 +396,7 @@ fn spawn_process_os(cfg: ProcessConfig,
with_envp(cfg.env, |envp| {
with_dirp(cfg.cwd, |dirp| {
let mut cmd_str: Vec<u16> = cmd_str.as_slice().utf16_units().collect();
cmd_str = cmd_str.append_one(0);
cmd_str.push(0);
let created = CreateProcessW(ptr::null(),
cmd_str.as_mut_ptr(),
ptr::null_mut(),
@ -473,7 +473,7 @@ fn make_command_line(prog: &CString, args: &[CString]) -> String {
append_arg(&mut cmd, prog.as_str()
.expect("expected program name to be utf-8 encoded"));
for arg in args.iter() {
cmd.push_char(' ');
cmd.push(' ');
append_arg(&mut cmd, arg.as_str()
.expect("expected argument to be utf-8 encoded"));
}
@ -485,19 +485,19 @@ fn make_command_line(prog: &CString, args: &[CString]) -> String {
// it will be dropped entirely when parsed on the other end.
let quote = arg.chars().any(|c| c == ' ' || c == '\t') || arg.len() == 0;
if quote {
cmd.push_char('"');
cmd.push('"');
}
let argvec: Vec<char> = arg.chars().collect();
for i in range(0u, argvec.len()) {
append_char_at(cmd, &argvec, i);
append_char_at(cmd, argvec.as_slice(), i);
}
if quote {
cmd.push_char('"');
cmd.push('"');
}
}
fn append_char_at(cmd: &mut String, arg: &Vec<char>, i: uint) {
match *arg.get(i) {
fn append_char_at(cmd: &mut String, arg: &[char], i: uint) {
match arg[i] {
'"' => {
// Escape quotes.
cmd.push_str("\\\"");
@ -508,20 +508,20 @@ fn make_command_line(prog: &CString, args: &[CString]) -> String {
cmd.push_str("\\\\");
} else {
// Pass other backslashes through unescaped.
cmd.push_char('\\');
cmd.push('\\');
}
}
c => {
cmd.push_char(c);
cmd.push(c);
}
}
}
fn backslash_run_ends_in_quote(s: &Vec<char>, mut i: uint) -> bool {
while i < s.len() && *s.get(i) == '\\' {
fn backslash_run_ends_in_quote(s: &[char], mut i: uint) -> bool {
while i < s.len() && s[i] == '\\' {
i += 1;
}
return i < s.len() && *s.get(i) == '"';
return i < s.len() && s[i] == '"';
}
}
@ -817,9 +817,8 @@ fn with_dirp<T>(d: Option<&CString>, cb: |*const u16| -> T) -> T {
Some(dir) => {
let dir_str = dir.as_str()
.expect("expected workingdirectory to be utf-8 encoded");
let dir_str: Vec<u16> = dir_str.utf16_units().collect();
let dir_str = dir_str.append_one(0);
let mut dir_str: Vec<u16> = dir_str.utf16_units().collect();
dir_str.push(0);
cb(dir_str.as_ptr())
},
None => cb(ptr::null())

View File

@ -115,7 +115,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
// signals the first requests in the queue, possible re-enqueueing it.
fn signal(active: &mut Vec<Box<Inner>>,
dead: &mut Vec<(uint, Box<Inner>)>) {
let mut timer = match active.shift() {
let mut timer = match active.remove(0) {
Some(timer) => timer, None => return
};
let mut cb = timer.cb.take().unwrap();
@ -137,7 +137,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
let now = now();
// If this request has already expired, then signal it and go
// through another iteration
if active.get(0).target <= now {
if active[0].target <= now {
signal(&mut active, &mut dead);
continue;
}
@ -145,7 +145,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
// The actual timeout listed in the requests array is an
// absolute date, so here we translate the absolute time to a
// relative time.
let tm = active.get(0).target - now;
let tm = active[0].target - now;
timeout.tv_sec = (tm / 1000) as libc::time_t;
timeout.tv_usec = ((tm % 1000) * 1000) as libc::suseconds_t;
&mut timeout as *mut libc::timeval

View File

@ -36,7 +36,7 @@ use libc::types::os::arch::extra::LPCVOID;
use std::io::MemReader;
use std::ptr;
use std::rt::rtio::{IoResult, IoError, RtioTTY};
use std::str::{from_utf16, from_utf8};
use std::str::from_utf8;
fn invalid_encoding() -> IoError {
IoError {
@ -103,7 +103,7 @@ impl RtioTTY for WindowsTTY {
_ => (),
};
utf16.truncate(num as uint);
let utf8 = match from_utf16(utf16.as_slice()) {
let utf8 = match String::from_utf16(utf16.as_slice()) {
Some(utf8) => utf8.into_bytes(),
None => return Err(invalid_encoding()),
};
@ -115,7 +115,9 @@ impl RtioTTY for WindowsTTY {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let utf16 = match from_utf8(buf) {
Some(utf8) => utf8.to_utf16(),
Some(utf8) => {
utf8.as_slice().utf16_units().collect::<Vec<u16>>()
}
None => return Err(invalid_encoding()),
};
let mut num: DWORD = 0;

View File

@ -56,7 +56,7 @@
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![deny(unused_result, unused_must_use)]
#![allow(non_camel_case_types, deprecated)]
#![allow(non_camel_case_types)]
#![allow(unknown_features)]
#![feature(default_type_params, lang_items, slicing_syntax)]

View File

@ -26,7 +26,6 @@ use std::rt::thread::Thread;
use std::rt;
use io;
use task;
use std::task::{TaskBuilder, Spawner};
/// Creates a new Task which is ready to execute as a 1:1 task.
@ -48,61 +47,49 @@ fn ops() -> Box<Ops> {
}
}
/// Spawns a function with the default configuration
#[deprecated = "use the native method of NativeTaskBuilder instead"]
pub fn spawn(f: proc():Send) {
spawn_opts(TaskOpts { name: None, stack_size: None, on_exit: None }, f)
}
/// Spawns a new task given the configuration options and a procedure to run
/// inside the task.
#[deprecated = "use the native method of NativeTaskBuilder instead"]
pub fn spawn_opts(opts: TaskOpts, f: proc():Send) {
let TaskOpts { name, stack_size, on_exit } = opts;
let mut task = box Task::new();
task.name = name;
task.death.on_exit = on_exit;
let stack = stack_size.unwrap_or(rt::min_stack());
let task = task;
let ops = ops();
// Note that this increment must happen *before* the spawn in order to
// guarantee that if this task exits it will always end up waiting for the
// spawned task to exit.
let token = bookkeeping::increment();
// Spawning a new OS thread guarantees that __morestack will never get
// triggered, but we must manually set up the actual stack bounds once this
// function starts executing. This raises the lower limit by a bit because
// by the time that this function is executing we've already consumed at
// least a little bit of stack (we don't know the exact byte address at
// which our stack started).
Thread::spawn_stack(stack, proc() {
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const int;
let my_stack = addr as uint;
unsafe {
stack::record_os_managed_stack_bounds(my_stack - stack + 1024, my_stack);
}
let mut ops = ops;
ops.stack_bounds = (my_stack - stack + 1024, my_stack);
let mut f = Some(f);
let mut task = task;
task.put_runtime(ops);
drop(task.run(|| { f.take().unwrap()() }).destroy());
drop(token);
})
}
/// A spawner for native tasks
pub struct NativeSpawner;
impl Spawner for NativeSpawner {
fn spawn(self, opts: TaskOpts, f: proc():Send) {
spawn_opts(opts, f)
let TaskOpts { name, stack_size, on_exit } = opts;
let mut task = box Task::new();
task.name = name;
task.death.on_exit = on_exit;
let stack = stack_size.unwrap_or(rt::min_stack());
let task = task;
let ops = ops();
// Note that this increment must happen *before* the spawn in order to
// guarantee that if this task exits it will always end up waiting for
// the spawned task to exit.
let token = bookkeeping::increment();
// Spawning a new OS thread guarantees that __morestack will never get
// triggered, but we must manually set up the actual stack bounds once
// this function starts executing. This raises the lower limit by a bit
// because by the time that this function is executing we've already
// consumed at least a little bit of stack (we don't know the exact byte
// address at which our stack started).
Thread::spawn_stack(stack, proc() {
let something_around_the_top_of_the_stack = 1;
let addr = &something_around_the_top_of_the_stack as *const int;
let my_stack = addr as uint;
unsafe {
stack::record_os_managed_stack_bounds(my_stack - stack + 1024,
my_stack);
}
let mut ops = ops;
ops.stack_bounds = (my_stack - stack + 1024, my_stack);
let mut f = Some(f);
let mut task = task;
task.put_runtime(ops);
drop(task.run(|| { f.take().unwrap()() }).destroy());
drop(token);
})
}
}
@ -270,7 +257,7 @@ impl rt::Runtime for Ops {
cur_task.put_runtime(self);
Local::put(cur_task);
task::spawn_opts(opts, f);
NativeSpawner.spawn(opts, f);
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> {
@ -283,8 +270,9 @@ mod tests {
use std::rt::local::Local;
use std::rt::task::{Task, TaskOpts};
use std::task;
use std::task::TaskBuilder;
use super::{spawn, spawn_opts, Ops, NativeTaskBuilder};
use std::task::{TaskBuilder, Spawner};
use super::{Ops, NativeTaskBuilder, NativeSpawner};
#[test]
fn smoke() {
@ -312,7 +300,7 @@ mod tests {
opts.stack_size = Some(20 * 4096);
let (tx, rx) = channel();
opts.on_exit = Some(proc(r) tx.send(r));
spawn_opts(opts, proc() {});
NativeSpawner.spawn(opts, proc() {});
assert!(rx.recv().is_ok());
}
@ -321,7 +309,7 @@ mod tests {
let mut opts = TaskOpts::new();
let (tx, rx) = channel();
opts.on_exit = Some(proc(r) tx.send(r));
spawn_opts(opts, proc() { fail!() });
NativeSpawner.spawn(opts, proc() { fail!() });
assert!(rx.recv().is_err());
}
@ -357,7 +345,7 @@ mod tests {
#[test]
fn spawn_inherits() {
let (tx, rx) = channel();
spawn(proc() {
TaskBuilder::new().spawner(NativeSpawner).spawn(proc() {
spawn(proc() {
let mut task: Box<Task> = Local::take();
match task.maybe_take_runtime::<Ops>() {

File diff suppressed because it is too large Load Diff

View File

@ -1,379 +0,0 @@
// Copyright 2013 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Complex numbers.
use std::fmt;
use std::num::{Zero, One, ToStrRadix};
// FIXME #1284: handle complex NaN & infinity etc. This
// probably doesn't map to C's _Complex correctly.
/// A complex number in Cartesian form.
#[deriving(PartialEq, Clone, Hash)]
pub struct Complex<T> {
/// Real portion of the complex number
pub re: T,
/// Imaginary portion of the complex number
pub im: T
}
pub type Complex32 = Complex<f32>;
pub type Complex64 = Complex<f64>;
impl<T: Clone + Num> Complex<T> {
/// Create a new Complex
#[inline]
pub fn new(re: T, im: T) -> Complex<T> {
Complex { re: re, im: im }
}
/// Returns the square of the norm (since `T` doesn't necessarily
/// have a sqrt function), i.e. `re^2 + im^2`.
#[inline]
pub fn norm_sqr(&self) -> T {
self.re * self.re + self.im * self.im
}
/// Returns the complex conjugate. i.e. `re - i im`
#[inline]
pub fn conj(&self) -> Complex<T> {
Complex::new(self.re.clone(), -self.im)
}
/// Multiplies `self` by the scalar `t`.
#[inline]
pub fn scale(&self, t: T) -> Complex<T> {
Complex::new(self.re * t, self.im * t)
}
/// Divides `self` by the scalar `t`.
#[inline]
pub fn unscale(&self, t: T) -> Complex<T> {
Complex::new(self.re / t, self.im / t)
}
/// Returns `1/self`
#[inline]
pub fn inv(&self) -> Complex<T> {
let norm_sqr = self.norm_sqr();
Complex::new(self.re / norm_sqr,
-self.im / norm_sqr)
}
}
impl<T: Clone + FloatMath> Complex<T> {
/// Calculate |self|
#[inline]
pub fn norm(&self) -> T {
self.re.hypot(self.im)
}
}
impl<T: Clone + FloatMath> Complex<T> {
/// Calculate the principal Arg of self.
#[inline]
pub fn arg(&self) -> T {
self.im.atan2(self.re)
}
/// Convert to polar form (r, theta), such that `self = r * exp(i
/// * theta)`
#[inline]
pub fn to_polar(&self) -> (T, T) {
(self.norm(), self.arg())
}
/// Convert a polar representation into a complex number.
#[inline]
pub fn from_polar(r: &T, theta: &T) -> Complex<T> {
Complex::new(*r * theta.cos(), *r * theta.sin())
}
}
/* arithmetic */
// (a + i b) + (c + i d) == (a + c) + i (b + d)
impl<T: Clone + Num> Add<Complex<T>, Complex<T>> for Complex<T> {
#[inline]
fn add(&self, other: &Complex<T>) -> Complex<T> {
Complex::new(self.re + other.re, self.im + other.im)
}
}
// (a + i b) - (c + i d) == (a - c) + i (b - d)
impl<T: Clone + Num> Sub<Complex<T>, Complex<T>> for Complex<T> {
#[inline]
fn sub(&self, other: &Complex<T>) -> Complex<T> {
Complex::new(self.re - other.re, self.im - other.im)
}
}
// (a + i b) * (c + i d) == (a*c - b*d) + i (a*d + b*c)
impl<T: Clone + Num> Mul<Complex<T>, Complex<T>> for Complex<T> {
#[inline]
fn mul(&self, other: &Complex<T>) -> Complex<T> {
Complex::new(self.re*other.re - self.im*other.im,
self.re*other.im + self.im*other.re)
}
}
// (a + i b) / (c + i d) == [(a + i b) * (c - i d)] / (c*c + d*d)
// == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)]
impl<T: Clone + Num> Div<Complex<T>, Complex<T>> for Complex<T> {
#[inline]
fn div(&self, other: &Complex<T>) -> Complex<T> {
let norm_sqr = other.norm_sqr();
Complex::new((self.re*other.re + self.im*other.im) / norm_sqr,
(self.im*other.re - self.re*other.im) / norm_sqr)
}
}
impl<T: Clone + Num> Neg<Complex<T>> for Complex<T> {
#[inline]
fn neg(&self) -> Complex<T> {
Complex::new(-self.re, -self.im)
}
}
/* constants */
impl<T: Clone + Num> Zero for Complex<T> {
#[inline]
fn zero() -> Complex<T> {
Complex::new(Zero::zero(), Zero::zero())
}
#[inline]
fn is_zero(&self) -> bool {
self.re.is_zero() && self.im.is_zero()
}
}
impl<T: Clone + Num> One for Complex<T> {
#[inline]
fn one() -> Complex<T> {
Complex::new(One::one(), Zero::zero())
}
}
/* string conversions */
impl<T: fmt::Show + Num + PartialOrd> fmt::Show for Complex<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.im < Zero::zero() {
write!(f, "{}-{}i", self.re, -self.im)
} else {
write!(f, "{}+{}i", self.re, self.im)
}
}
}
impl<T: ToStrRadix + Num + PartialOrd> ToStrRadix for Complex<T> {
fn to_str_radix(&self, radix: uint) -> String {
if self.im < Zero::zero() {
format!("{}-{}i",
self.re.to_str_radix(radix),
(-self.im).to_str_radix(radix))
} else {
format!("{}+{}i",
self.re.to_str_radix(radix),
self.im.to_str_radix(radix))
}
}
}
#[cfg(test)]
mod test {
#![allow(non_uppercase_statics)]
use super::{Complex64, Complex};
use std::num::{Zero, One, Float};
use std::hash::hash;
pub const _0_0i : Complex64 = Complex { re: 0.0, im: 0.0 };
pub const _1_0i : Complex64 = Complex { re: 1.0, im: 0.0 };
pub const _1_1i : Complex64 = Complex { re: 1.0, im: 1.0 };
pub const _0_1i : Complex64 = Complex { re: 0.0, im: 1.0 };
pub const _neg1_1i : Complex64 = Complex { re: -1.0, im: 1.0 };
pub const _05_05i : Complex64 = Complex { re: 0.5, im: 0.5 };
pub const all_consts : [Complex64, .. 5] = [_0_0i, _1_0i, _1_1i, _neg1_1i, _05_05i];
#[test]
fn test_consts() {
// check our constants are what Complex::new creates
fn test(c : Complex64, r : f64, i: f64) {
assert_eq!(c, Complex::new(r,i));
}
test(_0_0i, 0.0, 0.0);
test(_1_0i, 1.0, 0.0);
test(_1_1i, 1.0, 1.0);
test(_neg1_1i, -1.0, 1.0);
test(_05_05i, 0.5, 0.5);
assert_eq!(_0_0i, Zero::zero());
assert_eq!(_1_0i, One::one());
}
#[test]
#[cfg_attr(target_arch = "x86", ignore)]
// FIXME #7158: (maybe?) currently failing on x86.
fn test_norm() {
fn test(c: Complex64, ns: f64) {
assert_eq!(c.norm_sqr(), ns);
assert_eq!(c.norm(), ns.sqrt())
}
test(_0_0i, 0.0);
test(_1_0i, 1.0);
test(_1_1i, 2.0);
test(_neg1_1i, 2.0);
test(_05_05i, 0.5);
}
#[test]
fn test_scale_unscale() {
assert_eq!(_05_05i.scale(2.0), _1_1i);
assert_eq!(_1_1i.unscale(2.0), _05_05i);
for &c in all_consts.iter() {
assert_eq!(c.scale(2.0).unscale(2.0), c);
}
}
#[test]
fn test_conj() {
for &c in all_consts.iter() {
assert_eq!(c.conj(), Complex::new(c.re, -c.im));
assert_eq!(c.conj().conj(), c);
}
}
#[test]
fn test_inv() {
assert_eq!(_1_1i.inv(), _05_05i.conj());
assert_eq!(_1_0i.inv(), _1_0i.inv());
}
#[test]
#[should_fail]
fn test_divide_by_zero_natural() {
let n = Complex::new(2i, 3i);
let d = Complex::new(0, 0);
let _x = n / d;
}
#[test]
#[should_fail]
#[ignore]
fn test_inv_zero() {
// FIXME #5736: should this really fail, or just NaN?
_0_0i.inv();
}
#[test]
fn test_arg() {
fn test(c: Complex64, arg: f64) {
assert!((c.arg() - arg).abs() < 1.0e-6)
}
test(_1_0i, 0.0);
test(_1_1i, 0.25 * Float::pi());
test(_neg1_1i, 0.75 * Float::pi());
test(_05_05i, 0.25 * Float::pi());
}
#[test]
fn test_polar_conv() {
fn test(c: Complex64) {
let (r, theta) = c.to_polar();
assert!((c - Complex::from_polar(&r, &theta)).norm() < 1e-6);
}
for &c in all_consts.iter() { test(c); }
}
mod arith {
use super::{_0_0i, _1_0i, _1_1i, _0_1i, _neg1_1i, _05_05i, all_consts};
use std::num::Zero;
#[test]
fn test_add() {
assert_eq!(_05_05i + _05_05i, _1_1i);
assert_eq!(_0_1i + _1_0i, _1_1i);
assert_eq!(_1_0i + _neg1_1i, _0_1i);
for &c in all_consts.iter() {
assert_eq!(_0_0i + c, c);
assert_eq!(c + _0_0i, c);
}
}
#[test]
fn test_sub() {
assert_eq!(_05_05i - _05_05i, _0_0i);
assert_eq!(_0_1i - _1_0i, _neg1_1i);
assert_eq!(_0_1i - _neg1_1i, _1_0i);
for &c in all_consts.iter() {
assert_eq!(c - _0_0i, c);
assert_eq!(c - c, _0_0i);
}
}
#[test]
fn test_mul() {
assert_eq!(_05_05i * _05_05i, _0_1i.unscale(2.0));
assert_eq!(_1_1i * _0_1i, _neg1_1i);
// i^2 & i^4
assert_eq!(_0_1i * _0_1i, -_1_0i);
assert_eq!(_0_1i * _0_1i * _0_1i * _0_1i, _1_0i);
for &c in all_consts.iter() {
assert_eq!(c * _1_0i, c);
assert_eq!(_1_0i * c, c);
}
}
#[test]
fn test_div() {
assert_eq!(_neg1_1i / _0_1i, _1_1i);
for &c in all_consts.iter() {
if c != Zero::zero() {
assert_eq!(c / c, _1_0i);
}
}
}
#[test]
fn test_neg() {
assert_eq!(-_1_0i + _0_1i, _neg1_1i);
assert_eq!((-_0_1i) * _0_1i, _1_0i);
for &c in all_consts.iter() {
assert_eq!(-(-c), c);
}
}
}
#[test]
fn test_to_string() {
fn test(c : Complex64, s: String) {
assert_eq!(c.to_string(), s);
}
test(_0_0i, "0+0i".to_string());
test(_1_0i, "1+0i".to_string());
test(_0_1i, "0+1i".to_string());
test(_1_1i, "1+1i".to_string());
test(_neg1_1i, "-1+1i".to_string());
test(-_neg1_1i, "1-1i".to_string());
test(_05_05i, "0.5+0.5i".to_string());
}
#[test]
fn test_hash() {
let a = Complex::new(0i32, 0i32);
let b = Complex::new(1i32, 0i32);
let c = Complex::new(0i32, 1i32);
assert!(hash(&a) != hash(&b));
assert!(hash(&b) != hash(&c));
assert!(hash(&c) != hash(&a));
}
}

View File

@ -1,507 +0,0 @@
// Copyright 2013-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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Integer trait and functions.
pub trait Integer: Num + PartialOrd
+ Div<Self, Self>
+ Rem<Self, Self> {
/// Floored integer division.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert!(( 8i).div_floor(& 3) == 2);
/// assert!(( 8i).div_floor(&-3) == -3);
/// assert!((-8i).div_floor(& 3) == -3);
/// assert!((-8i).div_floor(&-3) == 2);
///
/// assert!(( 1i).div_floor(& 2) == 0);
/// assert!(( 1i).div_floor(&-2) == -1);
/// assert!((-1i).div_floor(& 2) == -1);
/// assert!((-1i).div_floor(&-2) == 0);
/// ```
fn div_floor(&self, other: &Self) -> Self;
/// Floored integer modulo, satisfying:
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// # let n = 1i; let d = 1i;
/// assert!(n.div_floor(&d) * d + n.mod_floor(&d) == n)
/// ```
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert!(( 8i).mod_floor(& 3) == 2);
/// assert!(( 8i).mod_floor(&-3) == -1);
/// assert!((-8i).mod_floor(& 3) == 1);
/// assert!((-8i).mod_floor(&-3) == -2);
///
/// assert!(( 1i).mod_floor(& 2) == 1);
/// assert!(( 1i).mod_floor(&-2) == -1);
/// assert!((-1i).mod_floor(& 2) == 1);
/// assert!((-1i).mod_floor(&-2) == -1);
/// ```
fn mod_floor(&self, other: &Self) -> Self;
/// Greatest Common Divisor (GCD).
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(6i.gcd(&8), 2);
/// assert_eq!(7i.gcd(&3), 1);
/// ```
fn gcd(&self, other: &Self) -> Self;
/// Lowest Common Multiple (LCM).
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(7i.lcm(&3), 21);
/// assert_eq!(2i.lcm(&4), 4);
/// ```
fn lcm(&self, other: &Self) -> Self;
/// Deprecated, use `is_multiple_of` instead.
#[deprecated = "function renamed to `is_multiple_of`"]
fn divides(&self, other: &Self) -> bool;
/// Returns `true` if `other` is a multiple of `self`.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(9i.is_multiple_of(&3), true);
/// assert_eq!(3i.is_multiple_of(&9), false);
/// ```
fn is_multiple_of(&self, other: &Self) -> bool;
/// Returns `true` if the number is even.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(3i.is_even(), false);
/// assert_eq!(4i.is_even(), true);
/// ```
fn is_even(&self) -> bool;
/// Returns `true` if the number is odd.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(3i.is_odd(), true);
/// assert_eq!(4i.is_odd(), false);
/// ```
fn is_odd(&self) -> bool;
/// Simultaneous truncated integer division and modulus.
/// Returns `(quotient, remainder)`.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(( 8i).div_rem( &3), ( 2, 2));
/// assert_eq!(( 8i).div_rem(&-3), (-2, 2));
/// assert_eq!((-8i).div_rem( &3), (-2, -2));
/// assert_eq!((-8i).div_rem(&-3), ( 2, -2));
///
/// assert_eq!(( 1i).div_rem( &2), ( 0, 1));
/// assert_eq!(( 1i).div_rem(&-2), ( 0, 1));
/// assert_eq!((-1i).div_rem( &2), ( 0, -1));
/// assert_eq!((-1i).div_rem(&-2), ( 0, -1));
/// ```
#[inline]
fn div_rem(&self, other: &Self) -> (Self, Self) {
(*self / *other, *self % *other)
}
/// Simultaneous floored integer division and modulus.
/// Returns `(quotient, remainder)`.
///
/// # Examples
///
/// ```
/// # #![allow(deprecated)]
/// # use num::Integer;
/// assert_eq!(( 8i).div_mod_floor( &3), ( 2, 2));
/// assert_eq!(( 8i).div_mod_floor(&-3), (-3, -1));
/// assert_eq!((-8i).div_mod_floor( &3), (-3, 1));
/// assert_eq!((-8i).div_mod_floor(&-3), ( 2, -2));
///
/// assert_eq!(( 1i).div_mod_floor( &2), ( 0, 1));
/// assert_eq!(( 1i).div_mod_floor(&-2), (-1, -1));
/// assert_eq!((-1i).div_mod_floor( &2), (-1, 1));
/// assert_eq!((-1i).div_mod_floor(&-2), ( 0, -1));
/// ```
fn div_mod_floor(&self, other: &Self) -> (Self, Self) {
(self.div_floor(other), self.mod_floor(other))
}
}
/// Simultaneous integer division and modulus
#[inline] pub fn div_rem<T: Integer>(x: T, y: T) -> (T, T) { x.div_rem(&y) }
/// Floored integer division
#[inline] pub fn div_floor<T: Integer>(x: T, y: T) -> T { x.div_floor(&y) }
/// Floored integer modulus
#[inline] pub fn mod_floor<T: Integer>(x: T, y: T) -> T { x.mod_floor(&y) }
/// Simultaneous floored integer division and modulus
#[inline] pub fn div_mod_floor<T: Integer>(x: T, y: T) -> (T, T) { x.div_mod_floor(&y) }
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`. The
/// result is always positive.
#[inline(always)] pub fn gcd<T: Integer>(x: T, y: T) -> T { x.gcd(&y) }
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
#[inline(always)] pub fn lcm<T: Integer>(x: T, y: T) -> T { x.lcm(&y) }
macro_rules! impl_integer_for_int {
($T:ty, $test_mod:ident) => (
impl Integer for $T {
/// Floored integer division
#[inline]
fn div_floor(&self, other: &$T) -> $T {
// Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
// December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
match self.div_rem(other) {
(d, r) if (r > 0 && *other < 0)
|| (r < 0 && *other > 0) => d - 1,
(d, _) => d,
}
}
/// Floored integer modulo
#[inline]
fn mod_floor(&self, other: &$T) -> $T {
// Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
// December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
match *self % *other {
r if (r > 0 && *other < 0)
|| (r < 0 && *other > 0) => r + *other,
r => r,
}
}
/// Calculates `div_floor` and `mod_floor` simultaneously
#[inline]
fn div_mod_floor(&self, other: &$T) -> ($T,$T) {
// Algorithm from [Daan Leijen. _Division and Modulus for Computer Scientists_,
// December 2001](http://research.microsoft.com/pubs/151917/divmodnote-letter.pdf)
match self.div_rem(other) {
(d, r) if (r > 0 && *other < 0)
|| (r < 0 && *other > 0) => (d - 1, r + *other),
(d, r) => (d, r),
}
}
/// Calculates the Greatest Common Divisor (GCD) of the number and
/// `other`. The result is always positive.
#[inline]
fn gcd(&self, other: &$T) -> $T {
// Use Euclid's algorithm
let mut m = *self;
let mut n = *other;
while m != 0 {
let temp = m;
m = n % temp;
n = temp;
}
n.abs()
}
/// Calculates the Lowest Common Multiple (LCM) of the number and
/// `other`.
#[inline]
fn lcm(&self, other: &$T) -> $T {
// should not have to recalculate abs
((*self * *other) / self.gcd(other)).abs()
}
/// Deprecated, use `is_multiple_of` instead.
#[deprecated = "function renamed to `is_multiple_of`"]
#[inline]
fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); }
/// Returns `true` if the number is a multiple of `other`.
#[inline]
fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 }
/// Returns `true` if the number is divisible by `2`
#[inline]
fn is_even(&self) -> bool { self & 1 == 0 }
/// Returns `true` if the number is not divisible by `2`
#[inline]
fn is_odd(&self) -> bool { !self.is_even() }
}
#[cfg(test)]
mod $test_mod {
use Integer;
/// Checks that the division rule holds for:
///
/// - `n`: numerator (dividend)
/// - `d`: denominator (divisor)
/// - `qr`: quotient and remainder
#[cfg(test)]
fn test_division_rule((n,d): ($T,$T), (q,r): ($T,$T)) {
assert_eq!(d * q + r, n);
}
#[test]
fn test_div_rem() {
fn test_nd_dr(nd: ($T,$T), qr: ($T,$T)) {
let (n,d) = nd;
let separate_div_rem = (n / d, n % d);
let combined_div_rem = n.div_rem(&d);
assert_eq!(separate_div_rem, qr);
assert_eq!(combined_div_rem, qr);
test_division_rule(nd, separate_div_rem);
test_division_rule(nd, combined_div_rem);
}
test_nd_dr(( 8, 3), ( 2, 2));
test_nd_dr(( 8, -3), (-2, 2));
test_nd_dr((-8, 3), (-2, -2));
test_nd_dr((-8, -3), ( 2, -2));
test_nd_dr(( 1, 2), ( 0, 1));
test_nd_dr(( 1, -2), ( 0, 1));
test_nd_dr((-1, 2), ( 0, -1));
test_nd_dr((-1, -2), ( 0, -1));
}
#[test]
fn test_div_mod_floor() {
fn test_nd_dm(nd: ($T,$T), dm: ($T,$T)) {
let (n,d) = nd;
let separate_div_mod_floor = (n.div_floor(&d), n.mod_floor(&d));
let combined_div_mod_floor = n.div_mod_floor(&d);
assert_eq!(separate_div_mod_floor, dm);
assert_eq!(combined_div_mod_floor, dm);
test_division_rule(nd, separate_div_mod_floor);
test_division_rule(nd, combined_div_mod_floor);
}
test_nd_dm(( 8, 3), ( 2, 2));
test_nd_dm(( 8, -3), (-3, -1));
test_nd_dm((-8, 3), (-3, 1));
test_nd_dm((-8, -3), ( 2, -2));
test_nd_dm(( 1, 2), ( 0, 1));
test_nd_dm(( 1, -2), (-1, -1));
test_nd_dm((-1, 2), (-1, 1));
test_nd_dm((-1, -2), ( 0, -1));
}
#[test]
fn test_gcd() {
assert_eq!((10 as $T).gcd(&2), 2 as $T);
assert_eq!((10 as $T).gcd(&3), 1 as $T);
assert_eq!((0 as $T).gcd(&3), 3 as $T);
assert_eq!((3 as $T).gcd(&3), 3 as $T);
assert_eq!((56 as $T).gcd(&42), 14 as $T);
assert_eq!((3 as $T).gcd(&-3), 3 as $T);
assert_eq!((-6 as $T).gcd(&3), 3 as $T);
assert_eq!((-4 as $T).gcd(&-2), 2 as $T);
}
#[test]
fn test_lcm() {
assert_eq!((1 as $T).lcm(&0), 0 as $T);
assert_eq!((0 as $T).lcm(&1), 0 as $T);
assert_eq!((1 as $T).lcm(&1), 1 as $T);
assert_eq!((-1 as $T).lcm(&1), 1 as $T);
assert_eq!((1 as $T).lcm(&-1), 1 as $T);
assert_eq!((-1 as $T).lcm(&-1), 1 as $T);
assert_eq!((8 as $T).lcm(&9), 72 as $T);
assert_eq!((11 as $T).lcm(&5), 55 as $T);
}
#[test]
fn test_even() {
assert_eq!((-4 as $T).is_even(), true);
assert_eq!((-3 as $T).is_even(), false);
assert_eq!((-2 as $T).is_even(), true);
assert_eq!((-1 as $T).is_even(), false);
assert_eq!((0 as $T).is_even(), true);
assert_eq!((1 as $T).is_even(), false);
assert_eq!((2 as $T).is_even(), true);
assert_eq!((3 as $T).is_even(), false);
assert_eq!((4 as $T).is_even(), true);
}
#[test]
fn test_odd() {
assert_eq!((-4 as $T).is_odd(), false);
assert_eq!((-3 as $T).is_odd(), true);
assert_eq!((-2 as $T).is_odd(), false);
assert_eq!((-1 as $T).is_odd(), true);
assert_eq!((0 as $T).is_odd(), false);
assert_eq!((1 as $T).is_odd(), true);
assert_eq!((2 as $T).is_odd(), false);
assert_eq!((3 as $T).is_odd(), true);
assert_eq!((4 as $T).is_odd(), false);
}
}
)
}
impl_integer_for_int!(i8, test_integer_i8)
impl_integer_for_int!(i16, test_integer_i16)
impl_integer_for_int!(i32, test_integer_i32)
impl_integer_for_int!(i64, test_integer_i64)
impl_integer_for_int!(int, test_integer_int)
macro_rules! impl_integer_for_uint {
($T:ty, $test_mod:ident) => (
impl Integer for $T {
/// Unsigned integer division. Returns the same result as `div` (`/`).
#[inline]
fn div_floor(&self, other: &$T) -> $T { *self / *other }
/// Unsigned integer modulo operation. Returns the same result as `rem` (`%`).
#[inline]
fn mod_floor(&self, other: &$T) -> $T { *self % *other }
/// Calculates the Greatest Common Divisor (GCD) of the number and `other`
#[inline]
fn gcd(&self, other: &$T) -> $T {
// Use Euclid's algorithm
let mut m = *self;
let mut n = *other;
while m != 0 {
let temp = m;
m = n % temp;
n = temp;
}
n
}
/// Calculates the Lowest Common Multiple (LCM) of the number and `other`.
#[inline]
fn lcm(&self, other: &$T) -> $T {
(*self * *other) / self.gcd(other)
}
/// Deprecated, use `is_multiple_of` instead.
#[deprecated = "function renamed to `is_multiple_of`"]
#[inline]
fn divides(&self, other: &$T) -> bool { return self.is_multiple_of(other); }
/// Returns `true` if the number is a multiple of `other`.
#[inline]
fn is_multiple_of(&self, other: &$T) -> bool { *self % *other == 0 }
/// Returns `true` if the number is divisible by `2`.
#[inline]
fn is_even(&self) -> bool { self & 1 == 0 }
/// Returns `true` if the number is not divisible by `2`.
#[inline]
fn is_odd(&self) -> bool { !self.is_even() }
}
#[cfg(test)]
mod $test_mod {
use Integer;
#[test]
fn test_div_mod_floor() {
assert_eq!((10 as $T).div_floor(&(3 as $T)), 3 as $T);
assert_eq!((10 as $T).mod_floor(&(3 as $T)), 1 as $T);
assert_eq!((10 as $T).div_mod_floor(&(3 as $T)), (3 as $T, 1 as $T));
assert_eq!((5 as $T).div_floor(&(5 as $T)), 1 as $T);
assert_eq!((5 as $T).mod_floor(&(5 as $T)), 0 as $T);
assert_eq!((5 as $T).div_mod_floor(&(5 as $T)), (1 as $T, 0 as $T));
assert_eq!((3 as $T).div_floor(&(7 as $T)), 0 as $T);
assert_eq!((3 as $T).mod_floor(&(7 as $T)), 3 as $T);
assert_eq!((3 as $T).div_mod_floor(&(7 as $T)), (0 as $T, 3 as $T));
}
#[test]
fn test_gcd() {
assert_eq!((10 as $T).gcd(&2), 2 as $T);
assert_eq!((10 as $T).gcd(&3), 1 as $T);
assert_eq!((0 as $T).gcd(&3), 3 as $T);
assert_eq!((3 as $T).gcd(&3), 3 as $T);
assert_eq!((56 as $T).gcd(&42), 14 as $T);
}
#[test]
#[allow(type_overflow)]
fn test_lcm() {
assert_eq!((1 as $T).lcm(&0), 0 as $T);
assert_eq!((0 as $T).lcm(&1), 0 as $T);
assert_eq!((1 as $T).lcm(&1), 1 as $T);
assert_eq!((8 as $T).lcm(&9), 72 as $T);
assert_eq!((11 as $T).lcm(&5), 55 as $T);
assert_eq!((99 as $T).lcm(&17), 1683 as $T);
}
#[test]
fn test_is_multiple_of() {
assert!((6 as $T).is_multiple_of(&(6 as $T)));
assert!((6 as $T).is_multiple_of(&(3 as $T)));
assert!((6 as $T).is_multiple_of(&(1 as $T)));
}
#[test]
fn test_even() {
assert_eq!((0 as $T).is_even(), true);
assert_eq!((1 as $T).is_even(), false);
assert_eq!((2 as $T).is_even(), true);
assert_eq!((3 as $T).is_even(), false);
assert_eq!((4 as $T).is_even(), true);
}
#[test]
fn test_odd() {
assert_eq!((0 as $T).is_odd(), false);
assert_eq!((1 as $T).is_odd(), true);
assert_eq!((2 as $T).is_odd(), false);
assert_eq!((3 as $T).is_odd(), true);
assert_eq!((4 as $T).is_odd(), false);
}
}
)
}
impl_integer_for_uint!(u8, test_integer_u8)
impl_integer_for_uint!(u16, test_integer_u16)
impl_integer_for_uint!(u32, test_integer_u32)
impl_integer_for_uint!(u64, test_integer_u64)
impl_integer_for_uint!(uint, test_integer_uint)

View File

@ -1,73 +0,0 @@
// 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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Simple numerics.
//!
//! This crate contains arbitrary-sized integer, rational, and complex types.
//!
//! ## Example
//!
//! This example uses the BigRational type and [Newton's method][newt] to
//! approximate a square root to arbitrary precision:
//!
//! ```
//! # #![allow(deprecated)]
//! extern crate num;
//!
//! use num::bigint::BigInt;
//! use num::rational::{Ratio, BigRational};
//!
//! fn approx_sqrt(number: u64, iterations: uint) -> BigRational {
//! let start: Ratio<BigInt> = Ratio::from_integer(FromPrimitive::from_u64(number).unwrap());
//! let mut approx = start.clone();
//!
//! for _ in range(0, iterations) {
//! approx = (approx + (start / approx)) /
//! Ratio::from_integer(FromPrimitive::from_u64(2).unwrap());
//! }
//!
//! approx
//! }
//!
//! fn main() {
//! println!("{}", approx_sqrt(10, 4)); // prints 4057691201/1283082416
//! }
//! ```
//!
//! [newt]: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
#![allow(unknown_features)]
#![feature(macro_rules, slicing_syntax)]
#![feature(default_type_params)]
#![crate_name = "num"]
#![deprecated = "This is now a cargo package located at: \
https://github.com/rust-lang/num"]
#![allow(deprecated)]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/",
html_playground_url = "http://play.rust-lang.org/")]
#![allow(deprecated)] // from_str_radix
extern crate rand;
pub use bigint::{BigInt, BigUint};
pub use rational::{Rational, BigRational};
pub use complex::Complex;
pub use integer::Integer;
pub mod bigint;
pub mod complex;
pub mod integer;
pub mod rational;

View File

@ -1,803 +0,0 @@
// Copyright 2013-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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Rational numbers
use Integer;
use std::cmp;
use std::fmt;
use std::from_str::FromStr;
use std::num;
use std::num::{Zero, One, ToStrRadix, FromStrRadix};
use bigint::{BigInt, BigUint, Sign, Plus, Minus};
/// Represents the ratio between 2 numbers.
#[deriving(Clone, Hash)]
#[allow(missing_doc)]
pub struct Ratio<T> {
numer: T,
denom: T
}
/// Alias for a `Ratio` of machine-sized integers.
pub type Rational = Ratio<int>;
pub type Rational32 = Ratio<i32>;
pub type Rational64 = Ratio<i64>;
/// Alias for arbitrary precision rationals.
pub type BigRational = Ratio<BigInt>;
impl<T: Clone + Integer + PartialOrd>
Ratio<T> {
/// Creates a ratio representing the integer `t`.
#[inline]
pub fn from_integer(t: T) -> Ratio<T> {
Ratio::new_raw(t, One::one())
}
/// Creates a ratio without checking for `denom == 0` or reducing.
#[inline]
pub fn new_raw(numer: T, denom: T) -> Ratio<T> {
Ratio { numer: numer, denom: denom }
}
/// Create a new Ratio. Fails if `denom == 0`.
#[inline]
pub fn new(numer: T, denom: T) -> Ratio<T> {
if denom == Zero::zero() {
fail!("denominator == 0");
}
let mut ret = Ratio::new_raw(numer, denom);
ret.reduce();
ret
}
/// Converts to an integer.
#[inline]
pub fn to_integer(&self) -> T {
self.trunc().numer
}
/// Gets an immutable reference to the numerator.
#[inline]
pub fn numer<'a>(&'a self) -> &'a T {
&self.numer
}
/// Gets an immutable reference to the denominator.
#[inline]
pub fn denom<'a>(&'a self) -> &'a T {
&self.denom
}
/// Returns true if the rational number is an integer (denominator is 1).
#[inline]
pub fn is_integer(&self) -> bool {
self.denom == One::one()
}
/// Put self into lowest terms, with denom > 0.
fn reduce(&mut self) {
let g : T = self.numer.gcd(&self.denom);
// FIXME(#5992): assignment operator overloads
// self.numer /= g;
self.numer = self.numer / g;
// FIXME(#5992): assignment operator overloads
// self.denom /= g;
self.denom = self.denom / g;
// keep denom positive!
if self.denom < Zero::zero() {
self.numer = -self.numer;
self.denom = -self.denom;
}
}
/// Returns a `reduce`d copy of self.
pub fn reduced(&self) -> Ratio<T> {
let mut ret = self.clone();
ret.reduce();
ret
}
/// Returns the reciprocal.
#[inline]
pub fn recip(&self) -> Ratio<T> {
Ratio::new_raw(self.denom.clone(), self.numer.clone())
}
/// Rounds towards minus infinity.
#[inline]
pub fn floor(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer((self.numer - self.denom + One::one()) / self.denom)
} else {
Ratio::from_integer(self.numer / self.denom)
}
}
/// Rounds towards plus infinity.
#[inline]
pub fn ceil(&self) -> Ratio<T> {
if *self < Zero::zero() {
Ratio::from_integer(self.numer / self.denom)
} else {
Ratio::from_integer((self.numer + self.denom - One::one()) / self.denom)
}
}
/// Rounds to the nearest integer. Rounds half-way cases away from zero.
#[inline]
pub fn round(&self) -> Ratio<T> {
let one: T = One::one();
let two: T = one + one;
// Find unsigned fractional part of rational number
let fractional = self.fract().abs();
// The algorithm compares the unsigned fractional part with 1/2, that
// is, a/b >= 1/2, or a >= b/2. For odd denominators, we use
// a >= (b/2)+1. This avoids overflow issues.
let half_or_larger = if fractional.denom().is_even() {
*fractional.numer() >= *fractional.denom() / two
} else {
*fractional.numer() >= (*fractional.denom() / two) + one
};
if half_or_larger {
if *self >= Zero::zero() {
self.trunc() + One::one()
} else {
self.trunc() - One::one()
}
} else {
self.trunc()
}
}
/// Rounds towards zero.
#[inline]
pub fn trunc(&self) -> Ratio<T> {
Ratio::from_integer(self.numer / self.denom)
}
/// Returns the fractional part of a number.
#[inline]
pub fn fract(&self) -> Ratio<T> {
Ratio::new_raw(self.numer % self.denom, self.denom.clone())
}
}
impl Ratio<BigInt> {
/// Converts a float into a rational number.
pub fn from_float<T: Float>(f: T) -> Option<BigRational> {
if !f.is_finite() {
return None;
}
let (mantissa, exponent, sign) = f.integer_decode();
let bigint_sign: Sign = if sign == 1 { Plus } else { Minus };
if exponent < 0 {
let one: BigInt = One::one();
let denom: BigInt = one << ((-exponent) as uint);
let numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
Some(Ratio::new(BigInt::from_biguint(bigint_sign, numer), denom))
} else {
let mut numer: BigUint = FromPrimitive::from_u64(mantissa).unwrap();
numer = numer << (exponent as uint);
Some(Ratio::from_integer(BigInt::from_biguint(bigint_sign, numer)))
}
}
}
/* Comparisons */
// comparing a/b and c/d is the same as comparing a*d and b*c, so we
// abstract that pattern. The following macro takes a trait and either
// a comma-separated list of "method name -> return value" or just
// "method name" (return value is bool in that case)
macro_rules! cmp_impl {
(impl $imp:ident, $($method:ident),+) => {
cmp_impl!(impl $imp, $($method -> bool),+)
};
// return something other than a Ratio<T>
(impl $imp:ident, $($method:ident -> $res:ty),*) => {
impl<T: Mul<T,T> + $imp> $imp for Ratio<T> {
$(
#[inline]
fn $method(&self, other: &Ratio<T>) -> $res {
(self.numer * other.denom). $method (&(self.denom*other.numer))
}
)*
}
};
}
cmp_impl!(impl PartialEq, eq, ne)
cmp_impl!(impl PartialOrd, lt -> bool, gt -> bool, le -> bool, ge -> bool,
partial_cmp -> Option<cmp::Ordering>)
cmp_impl!(impl Eq, )
cmp_impl!(impl Ord, cmp -> cmp::Ordering)
/* Arithmetic */
// a/b * c/d = (a*c)/(b*d)
impl<T: Clone + Integer + PartialOrd>
Mul<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn mul(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom)
}
}
// (a/b) / (c/d) = (a*d)/(b*c)
impl<T: Clone + Integer + PartialOrd>
Div<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn div(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new(self.numer * rhs.denom, self.denom * rhs.numer)
}
}
// Abstracts the a/b `op` c/d = (a*d `op` b*d) / (b*d) pattern
macro_rules! arith_impl {
(impl $imp:ident, $method:ident) => {
impl<T: Clone + Integer + PartialOrd>
$imp<Ratio<T>,Ratio<T>> for Ratio<T> {
#[inline]
fn $method(&self, rhs: &Ratio<T>) -> Ratio<T> {
Ratio::new((self.numer * rhs.denom).$method(&(self.denom * rhs.numer)),
self.denom * rhs.denom)
}
}
}
}
// a/b + c/d = (a*d + b*c)/(b*d)
arith_impl!(impl Add, add)
// a/b - c/d = (a*d - b*c)/(b*d)
arith_impl!(impl Sub, sub)
// a/b % c/d = (a*d % b*c)/(b*d)
arith_impl!(impl Rem, rem)
impl<T: Clone + Integer + PartialOrd>
Neg<Ratio<T>> for Ratio<T> {
#[inline]
fn neg(&self) -> Ratio<T> {
Ratio::new_raw(-self.numer, self.denom.clone())
}
}
/* Constants */
impl<T: Clone + Integer + PartialOrd>
Zero for Ratio<T> {
#[inline]
fn zero() -> Ratio<T> {
Ratio::new_raw(Zero::zero(), One::one())
}
#[inline]
fn is_zero(&self) -> bool {
*self == Zero::zero()
}
}
impl<T: Clone + Integer + PartialOrd>
One for Ratio<T> {
#[inline]
fn one() -> Ratio<T> {
Ratio::new_raw(One::one(), One::one())
}
}
impl<T: Clone + Integer + PartialOrd>
Num for Ratio<T> {}
impl<T: Clone + Integer + PartialOrd>
num::Signed for Ratio<T> {
#[inline]
fn abs(&self) -> Ratio<T> {
if self.is_negative() { -self.clone() } else { self.clone() }
}
#[inline]
fn abs_sub(&self, other: &Ratio<T>) -> Ratio<T> {
if *self <= *other { Zero::zero() } else { *self - *other }
}
#[inline]
fn signum(&self) -> Ratio<T> {
if *self > Zero::zero() {
num::one()
} else if self.is_zero() {
num::zero()
} else {
- num::one::<Ratio<T>>()
}
}
#[inline]
fn is_positive(&self) -> bool { *self > Zero::zero() }
#[inline]
fn is_negative(&self) -> bool { *self < Zero::zero() }
}
/* String conversions */
impl<T: fmt::Show + Eq + One> fmt::Show for Ratio<T> {
/// Renders as `numer/denom`. If denom=1, renders as numer.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.denom == One::one() {
write!(f, "{}", self.numer)
} else {
write!(f, "{}/{}", self.numer, self.denom)
}
}
}
impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
/// Renders as `numer/denom` where the numbers are in base `radix`.
fn to_str_radix(&self, radix: uint) -> String {
format!("{}/{}",
self.numer.to_str_radix(radix),
self.denom.to_str_radix(radix))
}
}
impl<T: FromStr + Clone + Integer + PartialOrd>
FromStr for Ratio<T> {
/// Parses `numer/denom` or just `numer`.
fn from_str(s: &str) -> Option<Ratio<T>> {
let mut split = s.splitn(1, '/');
let num = split.next().and_then(|n| FromStr::from_str(n));
let den = split.next().or(Some("1")).and_then(|d| FromStr::from_str(d));
match (num, den) {
(Some(n), Some(d)) => Some(Ratio::new(n, d)),
_ => None
}
}
}
impl<T: FromStrRadix + Clone + Integer + PartialOrd>
FromStrRadix for Ratio<T> {
/// Parses `numer/denom` where the numbers are in base `radix`.
fn from_str_radix(s: &str, radix: uint) -> Option<Ratio<T>> {
let split: Vec<&str> = s.splitn(1, '/').collect();
if split.len() < 2 {
None
} else {
let a_option: Option<T> = FromStrRadix::from_str_radix(
*split.get(0),
radix);
a_option.and_then(|a| {
let b_option: Option<T> =
FromStrRadix::from_str_radix(*split.get(1), radix);
b_option.and_then(|b| {
Some(Ratio::new(a.clone(), b.clone()))
})
})
}
}
}
#[cfg(test)]
mod test {
use super::{Ratio, Rational, BigRational};
use std::num::{Zero, One, FromStrRadix, FromPrimitive, ToStrRadix};
use std::from_str::FromStr;
use std::hash::hash;
use std::num;
use std::i32;
pub static _0 : Rational = Ratio { numer: 0, denom: 1};
pub static _1 : Rational = Ratio { numer: 1, denom: 1};
pub static _2: Rational = Ratio { numer: 2, denom: 1};
pub static _1_2: Rational = Ratio { numer: 1, denom: 2};
pub static _3_2: Rational = Ratio { numer: 3, denom: 2};
#[allow(non_uppercase_statics)]
pub static _neg1_2: Rational = Ratio { numer: -1, denom: 2};
pub static _1_3: Rational = Ratio { numer: 1, denom: 3};
#[allow(non_uppercase_statics)]
pub static _neg1_3: Rational = Ratio { numer: -1, denom: 3};
pub static _2_3: Rational = Ratio { numer: 2, denom: 3};
#[allow(non_uppercase_statics)]
pub static _neg2_3: Rational = Ratio { numer: -2, denom: 3};
pub fn to_big(n: Rational) -> BigRational {
Ratio::new(
FromPrimitive::from_int(n.numer).unwrap(),
FromPrimitive::from_int(n.denom).unwrap()
)
}
#[test]
fn test_test_constants() {
// check our constants are what Ratio::new etc. would make.
assert_eq!(_0, Zero::zero());
assert_eq!(_1, One::one());
assert_eq!(_2, Ratio::from_integer(2i));
assert_eq!(_1_2, Ratio::new(1i,2i));
assert_eq!(_3_2, Ratio::new(3i,2i));
assert_eq!(_neg1_2, Ratio::new(-1i,2i));
}
#[test]
fn test_new_reduce() {
let one22 = Ratio::new(2i,2);
assert_eq!(one22, One::one());
}
#[test]
#[should_fail]
fn test_new_zero() {
let _a = Ratio::new(1i,0);
}
#[test]
fn test_cmp() {
assert!(_0 == _0 && _1 == _1);
assert!(_0 != _1 && _1 != _0);
assert!(_0 < _1 && !(_1 < _0));
assert!(_1 > _0 && !(_0 > _1));
assert!(_0 <= _0 && _1 <= _1);
assert!(_0 <= _1 && !(_1 <= _0));
assert!(_0 >= _0 && _1 >= _1);
assert!(_1 >= _0 && !(_0 >= _1));
}
#[test]
fn test_to_integer() {
assert_eq!(_0.to_integer(), 0);
assert_eq!(_1.to_integer(), 1);
assert_eq!(_2.to_integer(), 2);
assert_eq!(_1_2.to_integer(), 0);
assert_eq!(_3_2.to_integer(), 1);
assert_eq!(_neg1_2.to_integer(), 0);
}
#[test]
fn test_numer() {
assert_eq!(_0.numer(), &0);
assert_eq!(_1.numer(), &1);
assert_eq!(_2.numer(), &2);
assert_eq!(_1_2.numer(), &1);
assert_eq!(_3_2.numer(), &3);
assert_eq!(_neg1_2.numer(), &(-1));
}
#[test]
fn test_denom() {
assert_eq!(_0.denom(), &1);
assert_eq!(_1.denom(), &1);
assert_eq!(_2.denom(), &1);
assert_eq!(_1_2.denom(), &2);
assert_eq!(_3_2.denom(), &2);
assert_eq!(_neg1_2.denom(), &2);
}
#[test]
fn test_is_integer() {
assert!(_0.is_integer());
assert!(_1.is_integer());
assert!(_2.is_integer());
assert!(!_1_2.is_integer());
assert!(!_3_2.is_integer());
assert!(!_neg1_2.is_integer());
}
#[test]
fn test_show() {
assert_eq!(format!("{}", _2), "2".to_string());
assert_eq!(format!("{}", _1_2), "1/2".to_string());
assert_eq!(format!("{}", _0), "0".to_string());
assert_eq!(format!("{}", Ratio::from_integer(-2i)), "-2".to_string());
}
mod arith {
use super::{_0, _1, _2, _1_2, _3_2, _neg1_2, to_big};
use super::super::{Ratio, Rational};
#[test]
fn test_add() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a + b, c);
assert_eq!(to_big(a) + to_big(b), to_big(c));
}
test(_1, _1_2, _3_2);
test(_1, _1, _2);
test(_1_2, _3_2, _2);
test(_1_2, _neg1_2, _0);
}
#[test]
fn test_sub() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a - b, c);
assert_eq!(to_big(a) - to_big(b), to_big(c))
}
test(_1, _1_2, _1_2);
test(_3_2, _1_2, _1);
test(_1, _neg1_2, _3_2);
}
#[test]
fn test_mul() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a * b, c);
assert_eq!(to_big(a) * to_big(b), to_big(c))
}
test(_1, _1_2, _1_2);
test(_1_2, _3_2, Ratio::new(3i,4i));
test(_1_2, _neg1_2, Ratio::new(-1i, 4i));
}
#[test]
fn test_div() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a / b, c);
assert_eq!(to_big(a) / to_big(b), to_big(c))
}
test(_1, _1_2, _2);
test(_3_2, _1_2, _1 + _2);
test(_1, _neg1_2, _neg1_2 + _neg1_2 + _neg1_2 + _neg1_2);
}
#[test]
fn test_rem() {
fn test(a: Rational, b: Rational, c: Rational) {
assert_eq!(a % b, c);
assert_eq!(to_big(a) % to_big(b), to_big(c))
}
test(_3_2, _1, _1_2);
test(_2, _neg1_2, _0);
test(_1_2, _2, _1_2);
}
#[test]
fn test_neg() {
fn test(a: Rational, b: Rational) {
assert_eq!(-a, b);
assert_eq!(-to_big(a), to_big(b))
}
test(_0, _0);
test(_1_2, _neg1_2);
test(-_1, _1);
}
#[test]
fn test_zero() {
assert_eq!(_0 + _0, _0);
assert_eq!(_0 * _0, _0);
assert_eq!(_0 * _1, _0);
assert_eq!(_0 / _neg1_2, _0);
assert_eq!(_0 - _0, _0);
}
#[test]
#[should_fail]
fn test_div_0() {
let _a = _1 / _0;
}
}
#[test]
fn test_round() {
assert_eq!(_1_3.ceil(), _1);
assert_eq!(_1_3.floor(), _0);
assert_eq!(_1_3.round(), _0);
assert_eq!(_1_3.trunc(), _0);
assert_eq!(_neg1_3.ceil(), _0);
assert_eq!(_neg1_3.floor(), -_1);
assert_eq!(_neg1_3.round(), _0);
assert_eq!(_neg1_3.trunc(), _0);
assert_eq!(_2_3.ceil(), _1);
assert_eq!(_2_3.floor(), _0);
assert_eq!(_2_3.round(), _1);
assert_eq!(_2_3.trunc(), _0);
assert_eq!(_neg2_3.ceil(), _0);
assert_eq!(_neg2_3.floor(), -_1);
assert_eq!(_neg2_3.round(), -_1);
assert_eq!(_neg2_3.trunc(), _0);
assert_eq!(_1_2.ceil(), _1);
assert_eq!(_1_2.floor(), _0);
assert_eq!(_1_2.round(), _1);
assert_eq!(_1_2.trunc(), _0);
assert_eq!(_neg1_2.ceil(), _0);
assert_eq!(_neg1_2.floor(), -_1);
assert_eq!(_neg1_2.round(), -_1);
assert_eq!(_neg1_2.trunc(), _0);
assert_eq!(_1.ceil(), _1);
assert_eq!(_1.floor(), _1);
assert_eq!(_1.round(), _1);
assert_eq!(_1.trunc(), _1);
// Overflow checks
let _neg1 = Ratio::from_integer(-1);
let _large_rat1 = Ratio::new(i32::MAX, i32::MAX-1);
let _large_rat2 = Ratio::new(i32::MAX-1, i32::MAX);
let _large_rat3 = Ratio::new(i32::MIN+2, i32::MIN+1);
let _large_rat4 = Ratio::new(i32::MIN+1, i32::MIN+2);
let _large_rat5 = Ratio::new(i32::MIN+2, i32::MAX);
let _large_rat6 = Ratio::new(i32::MAX, i32::MIN+2);
let _large_rat7 = Ratio::new(1, i32::MIN+1);
let _large_rat8 = Ratio::new(1, i32::MAX);
assert_eq!(_large_rat1.round(), One::one());
assert_eq!(_large_rat2.round(), One::one());
assert_eq!(_large_rat3.round(), One::one());
assert_eq!(_large_rat4.round(), One::one());
assert_eq!(_large_rat5.round(), _neg1);
assert_eq!(_large_rat6.round(), _neg1);
assert_eq!(_large_rat7.round(), Zero::zero());
assert_eq!(_large_rat8.round(), Zero::zero());
}
#[test]
fn test_fract() {
assert_eq!(_1.fract(), _0);
assert_eq!(_neg1_2.fract(), _neg1_2);
assert_eq!(_1_2.fract(), _1_2);
assert_eq!(_3_2.fract(), _1_2);
}
#[test]
fn test_recip() {
assert_eq!(_1 * _1.recip(), _1);
assert_eq!(_2 * _2.recip(), _1);
assert_eq!(_1_2 * _1_2.recip(), _1);
assert_eq!(_3_2 * _3_2.recip(), _1);
assert_eq!(_neg1_2 * _neg1_2.recip(), _1);
}
#[test]
fn test_to_from_str() {
fn test(r: Rational, s: String) {
assert_eq!(FromStr::from_str(s.as_slice()), Some(r));
assert_eq!(r.to_string(), s);
}
test(_1, "1".to_string());
test(_0, "0".to_string());
test(_1_2, "1/2".to_string());
test(_3_2, "3/2".to_string());
test(_2, "2".to_string());
test(_neg1_2, "-1/2".to_string());
}
#[test]
fn test_from_str_fail() {
fn test(s: &str) {
let rational: Option<Rational> = FromStr::from_str(s);
assert_eq!(rational, None);
}
let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1"];
for &s in xs.iter() {
test(s);
}
}
#[test]
fn test_to_from_str_radix() {
fn test(r: Rational, s: String, n: uint) {
assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n),
Some(r));
assert_eq!(r.to_str_radix(n).to_string(), s);
}
fn test3(r: Rational, s: String) { test(r, s, 3) }
fn test16(r: Rational, s: String) { test(r, s, 16) }
test3(_1, "1/1".to_string());
test3(_0, "0/1".to_string());
test3(_1_2, "1/2".to_string());
test3(_3_2, "10/2".to_string());
test3(_2, "2/1".to_string());
test3(_neg1_2, "-1/2".to_string());
test3(_neg1_2 / _2, "-1/11".to_string());
test16(_1, "1/1".to_string());
test16(_0, "0/1".to_string());
test16(_1_2, "1/2".to_string());
test16(_3_2, "3/2".to_string());
test16(_2, "2/1".to_string());
test16(_neg1_2, "-1/2".to_string());
test16(_neg1_2 / _2, "-1/4".to_string());
test16(Ratio::new(13i,15i), "d/f".to_string());
test16(_1_2*_1_2*_1_2*_1_2, "1/10".to_string());
}
#[test]
fn test_from_str_radix_fail() {
fn test(s: &str) {
let radix: Option<Rational> = FromStrRadix::from_str_radix(s, 3);
assert_eq!(radix, None);
}
let xs = ["0 /1", "abc", "", "1/", "--1/2","3/2/1", "3/2"];
for &s in xs.iter() {
test(s);
}
}
#[test]
fn test_from_float() {
fn test<T: Float>(given: T, (numer, denom): (&str, &str)) {
let ratio: BigRational = Ratio::from_float(given).unwrap();
assert_eq!(ratio, Ratio::new(
FromStr::from_str(numer).unwrap(),
FromStr::from_str(denom).unwrap()));
}
// f32
test(3.14159265359f32, ("13176795", "4194304"));
test(2f32.powf(100.), ("1267650600228229401496703205376", "1"));
test(-2f32.powf(100.), ("-1267650600228229401496703205376", "1"));
test(1.0 / 2f32.powf(100.), ("1", "1267650600228229401496703205376"));
test(684729.48391f32, ("1369459", "2"));
test(-8573.5918555f32, ("-4389679", "512"));
// f64
test(3.14159265359f64, ("3537118876014453", "1125899906842624"));
test(2f64.powf(100.), ("1267650600228229401496703205376", "1"));
test(-2f64.powf(100.), ("-1267650600228229401496703205376", "1"));
test(684729.48391f64, ("367611342500051", "536870912"));
test(-8573.5918555f64, ("-4713381968463931", "549755813888"));
test(1.0 / 2f64.powf(100.), ("1", "1267650600228229401496703205376"));
}
#[test]
fn test_from_float_fail() {
use std::{f32, f64};
assert_eq!(Ratio::from_float(f32::NAN), None);
assert_eq!(Ratio::from_float(f32::INFINITY), None);
assert_eq!(Ratio::from_float(f32::NEG_INFINITY), None);
assert_eq!(Ratio::from_float(f64::NAN), None);
assert_eq!(Ratio::from_float(f64::INFINITY), None);
assert_eq!(Ratio::from_float(f64::NEG_INFINITY), None);
}
#[test]
fn test_signed() {
assert_eq!(_neg1_2.abs(), _1_2);
assert_eq!(_3_2.abs_sub(&_1_2), _1);
assert_eq!(_1_2.abs_sub(&_3_2), Zero::zero());
assert_eq!(_1_2.signum(), One::one());
assert_eq!(_neg1_2.signum(), - num::one::<Ratio<int>>());
assert!(_neg1_2.is_negative());
assert!(! _neg1_2.is_positive());
assert!(! _1_2.is_negative());
}
#[test]
fn test_hash() {
assert!(hash(&_0) != hash(&_1));
assert!(hash(&_0) != hash(&_3_2));
}
}

View File

@ -377,10 +377,10 @@ impl Isaac64Rng {
let x = *self.mem.unsafe_get(base + mr_offset);
a = mix + *self.mem.unsafe_get(base + m2_offset);
let y = ind!(x) + a + b;
self.mem.unsafe_set(base + mr_offset, y);
*self.mem.unsafe_mut(base + mr_offset) = y;
b = ind!(y >> RAND_SIZE_64_LEN) + x;
self.rsl.unsafe_set(base + mr_offset, b);
*self.rsl.unsafe_mut(base + mr_offset) = b;
}
}}
);
@ -394,10 +394,10 @@ impl Isaac64Rng {
let x = *self.mem.unsafe_get(base + mr_offset);
a = mix + *self.mem.unsafe_get(base + m2_offset);
let y = ind!(x) + a + b;
self.mem.unsafe_set(base + mr_offset, y);
*self.mem.unsafe_mut(base + mr_offset) = y;
b = ind!(y >> RAND_SIZE_64_LEN) + x;
self.rsl.unsafe_set(base + mr_offset, b);
*self.rsl.unsafe_mut(base + mr_offset) = b;
}
}}
);

View File

@ -239,12 +239,6 @@ pub trait Rng {
}
}
/// Deprecated name for `choose()`.
#[deprecated = "replaced by .choose()"]
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
self.choose(values)
}
/// Shuffle a mutable slice in place.
///
/// # Example

View File

@ -129,8 +129,6 @@ pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: uint =
pub fn find_crate_name(sess: Option<&Session>,
attrs: &[ast::Attribute],
input: &Input) -> String {
use syntax::crateid::CrateId;
let validate = |s: String, span: Option<Span>| {
creader::validate_crate_name(sess, s.as_slice(), span);
s
@ -168,25 +166,6 @@ pub fn find_crate_name(sess: Option<&Session>,
Some((attr, s)) => return validate(s.get().to_string(), Some(attr.span)),
None => {}
}
let crate_id = attrs.iter().find(|at| at.check_name("crate_id"))
.and_then(|at| at.value_str().map(|s| (at, s)))
.and_then(|(at, s)| {
from_str::<CrateId>(s.get()).map(|id| (at, id))
});
match crate_id {
Some((attr, id)) => {
match sess {
Some(sess) => {
sess.span_warn(attr.span, "the #[crate_id] attribute is \
deprecated for the \
#[crate_name] attribute");
}
None => {}
}
return validate(id.name, Some(attr.span))
}
None => {}
}
match *input {
FileInput(ref path) => {
match path.filestem_str() {
@ -274,18 +253,18 @@ pub fn sanitize(s: &str) -> String {
// '.' doesn't occur in types and functions, so reuse it
// for ':' and '-'
'-' | ':' => result.push_char('.'),
'-' | ':' => result.push('.'),
// These are legal symbols
'a' ... 'z'
| 'A' ... 'Z'
| '0' ... '9'
| '_' | '.' | '$' => result.push_char(c),
| '_' | '.' | '$' => result.push(c),
_ => {
let mut tstr = String::new();
char::escape_unicode(c, |c| tstr.push_char(c));
result.push_char('$');
char::escape_unicode(c, |c| tstr.push(c));
result.push('$');
result.push_str(tstr.as_slice().slice_from(1));
}
}
@ -334,7 +313,7 @@ pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
None => {}
}
n.push_char('E'); // End name-sequence.
n.push('E'); // End name-sequence.
n
}
@ -360,9 +339,9 @@ pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems,
let extra2 = id % EXTRA_CHARS.len();
let id = id / EXTRA_CHARS.len();
let extra3 = id % EXTRA_CHARS.len();
hash.push_char(EXTRA_CHARS.as_bytes()[extra1] as char);
hash.push_char(EXTRA_CHARS.as_bytes()[extra2] as char);
hash.push_char(EXTRA_CHARS.as_bytes()[extra3] as char);
hash.push(EXTRA_CHARS.as_bytes()[extra1] as char);
hash.push(EXTRA_CHARS.as_bytes()[extra2] as char);
hash.push(EXTRA_CHARS.as_bytes()[extra3] as char);
exported_name(path, hash.as_slice())
}
@ -838,8 +817,8 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
sess.note(str::from_utf8(output.as_slice()).unwrap());
sess.abort_if_errors();
}
debug!("linker stderr:\n{}", str::from_utf8_owned(prog.error).unwrap());
debug!("linker stdout:\n{}", str::from_utf8_owned(prog.output).unwrap());
debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap());
debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap());
},
Err(e) => {
sess.err(format!("could not exec the linker `{}`: {}",
@ -1088,7 +1067,7 @@ fn link_args(cmd: &mut Command,
cmd.args(["-dynamiclib", "-Wl,-dylib"]);
if sess.opts.cg.rpath {
let mut v = Vec::from_slice("-Wl,-install_name,@rpath/".as_bytes());
let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec();
v.push_all(out_filename.filename().unwrap());
cmd.arg(v.as_slice());
}
@ -1247,9 +1226,9 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
// involves just passing the right -l flag.
let data = if dylib {
trans.crate_formats.get(&config::CrateTypeDylib)
&trans.crate_formats[config::CrateTypeDylib]
} else {
trans.crate_formats.get(&config::CrateTypeExecutable)
&trans.crate_formats[config::CrateTypeExecutable]
};
// Invoke get_used_crates to ensure that we get a topological sorting of
@ -1260,7 +1239,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
// We may not pass all crates through to the linker. Some crates may
// appear statically in an existing dylib, meaning we'll pick up all the
// symbols from the dylib.
let kind = match *data.get(cnum as uint - 1) {
let kind = match data[cnum as uint - 1] {
Some(t) => t,
None => continue
};
@ -1279,7 +1258,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
// Converts a library file-stem into a cc -l argument
fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
if stem.starts_with("lib".as_bytes()) && config.os != abi::OsWindows {
stem.tailn(3)
stem[3..]
} else {
stem
}
@ -1362,7 +1341,7 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
let dir = cratepath.dirname();
if !dir.is_empty() { cmd.arg("-L").arg(dir); }
let mut v = Vec::from_slice("-l".as_bytes());
let mut v = "-l".as_bytes().to_vec();
v.push_all(unlib(&sess.targ_cfg, cratepath.filestem().unwrap()));
cmd.arg(v.as_slice());
}

View File

@ -487,7 +487,9 @@ pub fn build_configuration(sess: &Session) -> ast::CrateConfig {
if sess.opts.test {
append_configuration(&mut user_cfg, InternedString::new("test"))
}
user_cfg.into_iter().collect::<Vec<_>>().append(default_cfg.as_slice())
let mut v = user_cfg.into_iter().collect::<Vec<_>>();
v.push_all(default_cfg.as_slice());
v
}
pub fn get_os(triple: &str) -> Option<abi::Os> {

View File

@ -284,7 +284,7 @@ pub fn phase_2_configure_and_expand(sess: &Session,
if cfg!(windows) {
_old_path = os::getenv("PATH").unwrap_or(_old_path);
let mut new_path = sess.host_filesearch().get_dylib_search_paths();
new_path.push_all_move(os::split_paths(_old_path.as_slice()));
new_path.extend(os::split_paths(_old_path.as_slice()).into_iter());
os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
}
let cfg = syntax::ext::expand::ExpansionConfig {
@ -569,7 +569,7 @@ pub fn phase_6_link_output(sess: &Session,
outputs: &OutputFilenames) {
let old_path = os::getenv("PATH").unwrap_or_else(||String::new());
let mut new_path = os::split_paths(old_path.as_slice());
new_path.push_all_move(sess.host_filesearch().get_tools_search_paths());
new_path.extend(sess.host_filesearch().get_tools_search_paths().into_iter());
os::setenv("PATH", os::join_paths(new_path.as_slice()).unwrap());
time(sess.time_passes(), "linking", (), |_|
@ -818,17 +818,6 @@ pub fn build_output_filenames(input: &Input,
// If a crate name is present, we use it as the link name
let stem = sess.opts.crate_name.clone().or_else(|| {
attr::find_crate_name(attrs).map(|n| n.get().to_string())
}).or_else(|| {
// NB: this clause can be removed once #[crate_id] is no longer
// deprecated.
//
// Also note that this will be warned about later so we don't
// warn about it here.
use syntax::crateid::CrateId;
attrs.iter().find(|at| at.check_name("crate_id"))
.and_then(|at| at.value_str())
.and_then(|s| from_str::<CrateId>(s.get()))
.map(|id| id.name)
}).unwrap_or(input.filestem());
OutputFilenames {

View File

@ -43,7 +43,7 @@ static BUG_REPORT_URL: &'static str =
"http://doc.rust-lang.org/complement-bugreport.html";
fn run_compiler(args: &[String]) {
let matches = match handle_options(Vec::from_slice(args)) {
let matches = match handle_options(args.to_vec()) {
Some(matches) => matches,
None => return
};
@ -76,7 +76,7 @@ fn run_compiler(args: &[String]) {
early_error("no input filename given");
}
1u => {
let ifile = matches.free.get(0).as_slice();
let ifile = matches.free[0].as_slice();
if ifile == "-" {
let contents = io::stdin().read_to_end().unwrap();
let src = String::from_utf8(contents).unwrap();
@ -216,7 +216,9 @@ Available lint options:
.map(|&s| s.name.width(true))
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
let mut s = " ".repeat(max_name_len - x.char_len());
s.push_str(x);
s
};
println!("Lint checks provided by rustc:\n");
@ -240,7 +242,9 @@ Available lint options:
.map(|&(s, _)| s.width(true))
.max().unwrap_or(0);
let padded = |x: &str| {
" ".repeat(max_name_len - x.char_len()).append(x)
let mut s = " ".repeat(max_name_len - x.char_len());
s.push_str(x);
s
};
println!("Lint groups provided by rustc:\n");
@ -313,7 +317,7 @@ fn describe_codegen_flags() {
/// returns None.
pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
// Throw away the first argument, the name of the binary
let _binary = args.shift().unwrap();
let _binary = args.remove(0).unwrap();
if args.is_empty() {
usage();

View File

@ -434,10 +434,8 @@ pub fn pretty_print_input(sess: Session,
};
let src_name = driver::source_name(input);
let src = Vec::from_slice(sess.codemap()
.get_filemap(src_name.as_slice())
.src
.as_bytes());
let src = sess.codemap().get_filemap(src_name.as_slice())
.src.as_bytes().to_vec();
let mut rdr = MemReader::new(src);
let out = match ofile {

View File

@ -28,7 +28,6 @@ This API is completely unstable and subject to change.
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![allow(deprecated)]
#![feature(default_type_params, globs, if_let, import_shadowing, macro_rules, phase, quote)]
#![feature(slicing_syntax, struct_variant, unsafe_destructor)]
#![feature(rustc_diagnostic_macros)]

View File

@ -883,7 +883,7 @@ impl NonSnakeCase {
buf = String::new();
}
last_upper = ch.is_uppercase();
buf.push_char(ch.to_lowercase());
buf.push(ch.to_lowercase());
}
words.push(buf);
}
@ -1062,7 +1062,7 @@ impl UnusedParens {
ast::ExprMethodCall(_, _, ref exprs) => {
// X { y: 1 }.bar(...)
contains_exterior_struct_lit(&**exprs.get(0))
contains_exterior_struct_lit(&*exprs[0])
}
_ => false
@ -1220,7 +1220,7 @@ impl UnusedMut {
let used_mutables = cx.tcx.used_mut_nodes.borrow();
for (_, v) in mutables.iter() {
if !v.iter().any(|e| used_mutables.contains(e)) {
cx.span_lint(UNUSED_MUT, cx.tcx.map.span(*v.get(0)),
cx.span_lint(UNUSED_MUT, cx.tcx.map.span(v[0]),
"variable does not need to be mutable");
}
}

View File

@ -141,7 +141,7 @@ impl LintStore {
self.levels.insert(id, (lint.default_level, Default));
}
}
self.passes.get_mut_ref().push(pass);
self.passes.as_mut().unwrap().push(pass);
}
pub fn register_group(&mut self, sess: Option<&Session>,

View File

@ -93,8 +93,9 @@ pub fn get_item_path(tcx: &ty::ctxt, def: ast::DefId) -> Vec<ast_map::PathElem>
// FIXME #1920: This path is not always correct if the crate is not linked
// into the root namespace.
(vec!(ast_map::PathMod(token::intern(cdata.name.as_slice())))).append(
path.as_slice())
let mut r = vec![ast_map::PathMod(token::intern(cdata.name.as_slice()))];
r.push_all(path.as_slice());
r
}
pub enum found_ast<'ast> {

View File

@ -95,7 +95,7 @@ impl CStore {
}
pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc<crate_metadata> {
self.metas.borrow().get(&cnum).clone()
(*self.metas.borrow())[cnum].clone()
}
pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh {

View File

@ -643,7 +643,7 @@ pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeI
-> csearch::found_ast<'tcx> {
debug!("Looking up item: {}", id);
let item_doc = lookup_item(id, cdata.data());
let path = Vec::from_slice(item_path(item_doc).init());
let path = item_path(item_doc).init().to_vec();
match decode_inlined_item(cdata, tcx, path, item_doc) {
Ok(ii) => csearch::found(ii),
Err(path) => {

View File

@ -347,9 +347,9 @@ fn encode_enum_variant_info(ecx: &EncodeContext,
encode_index(rbml_w, idx, write_i64);
}
}
if vi.get(i).disr_val != disr_val {
encode_disr_val(ecx, rbml_w, vi.get(i).disr_val);
disr_val = vi.get(i).disr_val;
if (*vi)[i].disr_val != disr_val {
encode_disr_val(ecx, rbml_w, (*vi)[i].disr_val);
disr_val = (*vi)[i].disr_val;
}
encode_bounds_and_type(rbml_w, ecx,
&lookup_item_type(ecx.tcx, def_id));
@ -401,7 +401,7 @@ fn encode_reexported_static_base_methods(ecx: &EncodeContext,
match ecx.tcx.inherent_impls.borrow().find(&exp.def_id) {
Some(implementations) => {
for base_impl_did in implementations.iter() {
for &method_did in impl_items.get(base_impl_did).iter() {
for &method_did in (*impl_items)[*base_impl_did].iter() {
let impl_item = ty::impl_or_trait_item(
ecx.tcx,
method_did.def_id());
@ -515,7 +515,7 @@ fn each_auxiliary_node_id(item: &Item, callback: |NodeId| -> bool) -> bool {
// If this is a newtype struct, return the constructor.
match struct_def.ctor_id {
Some(ctor_id) if struct_def.fields.len() > 0 &&
struct_def.fields.get(0).node.kind.is_unnamed() => {
struct_def.fields[0].node.kind.is_unnamed() => {
continue_ = callback(ctor_id);
}
_ => {}
@ -912,7 +912,7 @@ fn encode_info_for_associated_type(ecx: &EncodeContext,
encode_stability(rbml_w, stab);
let elem = ast_map::PathName(associated_type.ident.name);
encode_path(rbml_w, impl_path.chain(Some(elem).move_iter()));
encode_path(rbml_w, impl_path.chain(Some(elem).into_iter()));
match typedef_opt {
None => {}
@ -1229,7 +1229,7 @@ fn encode_info_for_item(ecx: &EncodeContext,
// We need to encode information about the default methods we
// have inherited, so we drive this based on the impl structure.
let impl_items = tcx.impl_items.borrow();
let items = impl_items.get(&def_id);
let items = &(*impl_items)[def_id];
add_to_index(item, rbml_w, index);
rbml_w.start_tag(tag_items_data_item);
@ -1277,7 +1277,7 @@ fn encode_info_for_item(ecx: &EncodeContext,
let num_implemented_methods = ast_items.len();
for (i, &trait_item_def_id) in items.iter().enumerate() {
let ast_item = if i < num_implemented_methods {
Some(ast_items.get(i))
Some(&ast_items[i])
} else {
None
};
@ -1421,7 +1421,7 @@ fn encode_info_for_item(ecx: &EncodeContext,
ty::TypeTraitItem(associated_type) => {
let elem = ast_map::PathName(associated_type.ident.name);
encode_path(rbml_w,
path.clone().chain(Some(elem).move_iter()));
path.clone().chain(Some(elem).into_iter()));
encode_family(rbml_w, 'y');
@ -1431,8 +1431,8 @@ fn encode_info_for_item(ecx: &EncodeContext,
encode_parent_sort(rbml_w, 't');
let trait_item = ms.get(i);
match ms.get(i) {
let trait_item = &ms[i];
match &ms[i] {
&RequiredMethod(ref tm) => {
encode_attributes(rbml_w, tm.attrs.as_slice());
encode_item_sort(rbml_w, 'r');

View File

@ -418,11 +418,11 @@ impl<'a> Context<'a> {
(file.slice(rlib_prefix.len(), file.len() - ".rlib".len()),
true)
} else if dypair.map_or(false, |(_, suffix)| {
file.starts_with(dylib_prefix.get_ref().as_slice()) &&
file.starts_with(dylib_prefix.as_ref().unwrap().as_slice()) &&
file.ends_with(suffix)
}) {
let (_, suffix) = dypair.unwrap();
let dylib_prefix = dylib_prefix.get_ref().as_slice();
let dylib_prefix = dylib_prefix.as_ref().unwrap().as_slice();
(file.slice(dylib_prefix.len(), file.len() - suffix.len()),
false)
} else {
@ -553,7 +553,7 @@ impl<'a> Context<'a> {
self.crate_name).as_slice());
self.sess.span_note(self.span,
format!(r"candidate #1: {}",
ret.get_ref()
ret.as_ref().unwrap()
.display()).as_slice());
error = 1;
ret = None;

View File

@ -123,9 +123,9 @@ fn data_log_string(data: &[u8], pos: uint) -> String {
for i in range(pos, data.len()) {
let c = data[i];
if c > 0x20 && c <= 0x7F {
buf.push_char(c as char);
buf.push(c as char);
} else {
buf.push_char('.');
buf.push('.');
}
}
buf.push_str(">>");
@ -339,7 +339,7 @@ fn parse_str(st: &mut PState, term: char) -> String {
let mut result = String::new();
while peek(st) != term {
unsafe {
result.push_bytes([next_byte(st)])
result.as_mut_vec().push_all([next_byte(st)])
}
}
next(st);

View File

@ -1517,7 +1517,7 @@ impl<'a> rbml_decoder_decoder_helpers for reader::Decoder<'a> {
fn type_string(doc: rbml::Doc) -> String {
let mut str = String::new();
for i in range(doc.start, doc.end) {
str.push_char(doc.data[i] as char);
str.push(doc.data[i] as char);
}
str
}

View File

@ -98,7 +98,7 @@ fn group_errors_with_same_origin(errors: &Vec<MoveError>)
for ge in grouped_errors.iter_mut() {
if move_from_id == ge.move_from.id && error.move_to.is_some() {
debug!("appending move_to to list");
ge.move_to_places.push_all_move(move_to);
ge.move_to_places.extend(move_to.into_iter());
return
}
}

View File

@ -91,14 +91,15 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> {
saw_some = true;
true
});
set.append("}")
set.push_str("}");
set
}
fn dataflow_loans_for(&self, e: EntryOrExit, cfgidx: CFGIndex) -> String {
let dfcx = &self.analysis_data.loans;
let loan_index_to_path = |loan_index| {
let all_loans = &self.analysis_data.all_loans;
all_loans.get(loan_index).loan_path()
all_loans[loan_index].loan_path()
};
self.build_set(e, cfgidx, dfcx, loan_index_to_path)
}
@ -108,7 +109,7 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> {
let move_index_to_path = |move_index| {
let move_data = &self.analysis_data.move_data.move_data;
let moves = move_data.moves.borrow();
let the_move = moves.get(move_index);
let the_move = &(*moves)[move_index];
move_data.path_loan_path(the_move.path)
};
self.build_set(e, cfgidx, dfcx, move_index_to_path)
@ -119,7 +120,7 @@ impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> {
let assign_index_to_path = |assign_index| {
let move_data = &self.analysis_data.move_data.move_data;
let assignments = move_data.var_assignments.borrow();
let assignment = assignments.get(assign_index);
let assignment = &(*assignments)[assign_index];
move_data.path_loan_path(assignment.path)
};
self.build_set(e, cfgidx, dfcx, assign_index_to_path)

View File

@ -825,11 +825,11 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
self.append_autoderefd_loan_path_to_string(&**lp_base, out);
match fname {
mc::NamedField(fname) => {
out.push_char('.');
out.push('.');
out.push_str(token::get_name(fname).get());
}
mc::PositionalField(idx) => {
out.push_char('.');
out.push('.');
out.push_str(idx.to_string().as_slice());
}
}
@ -841,7 +841,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
}
LpExtend(ref lp_base, _, LpDeref(_)) => {
out.push_char('*');
out.push('*');
self.append_loan_path_to_string(&**lp_base, out);
}
}

View File

@ -192,23 +192,23 @@ impl MoveData {
}
pub fn path_loan_path(&self, index: MovePathIndex) -> Rc<LoanPath> {
self.paths.borrow().get(index.get()).loan_path.clone()
(*self.paths.borrow())[index.get()].loan_path.clone()
}
fn path_parent(&self, index: MovePathIndex) -> MovePathIndex {
self.paths.borrow().get(index.get()).parent
(*self.paths.borrow())[index.get()].parent
}
fn path_first_move(&self, index: MovePathIndex) -> MoveIndex {
self.paths.borrow().get(index.get()).first_move
(*self.paths.borrow())[index.get()].first_move
}
fn path_first_child(&self, index: MovePathIndex) -> MovePathIndex {
self.paths.borrow().get(index.get()).first_child
(*self.paths.borrow())[index.get()].first_child
}
fn path_next_sibling(&self, index: MovePathIndex) -> MovePathIndex {
self.paths.borrow().get(index.get()).next_sibling
(*self.paths.borrow())[index.get()].next_sibling
}
fn set_path_first_move(&self,
@ -225,7 +225,7 @@ impl MoveData {
fn move_next_move(&self, index: MoveIndex) -> MoveIndex {
//! Type safe indexing operator
self.moves.borrow().get(index.get()).next_move
(*self.moves.borrow())[index.get()].next_move
}
fn is_var_path(&self, index: MovePathIndex) -> bool {
@ -434,12 +434,12 @@ impl MoveData {
match *path.loan_path {
LpVar(id) => {
let kill_id = tcx.region_maps.var_scope(id);
let path = *self.path_map.borrow().get(&path.loan_path);
let path = (*self.path_map.borrow())[path.loan_path];
self.kill_moves(path, kill_id, dfcx_moves);
}
LpUpvar(ty::UpvarId { var_id: _, closure_expr_id }) => {
let kill_id = closure_to_block(closure_expr_id, tcx);
let path = *self.path_map.borrow().get(&path.loan_path);
let path = (*self.path_map.borrow())[path.loan_path];
self.kill_moves(path, kill_id, dfcx_moves);
}
LpExtend(..) => {}
@ -580,7 +580,7 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> {
for loan_path_index in self.move_data.path_map.borrow().find(&*loan_path).iter() {
self.dfcx_moves.each_gen_bit(id, |move_index| {
let the_move = self.move_data.moves.borrow();
let the_move = the_move.get(move_index);
let the_move = (*the_move)[move_index];
if the_move.path == **loan_path_index {
ret = Some(the_move.kind);
false
@ -625,7 +625,7 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> {
self.dfcx_moves.each_bit_on_entry(id, |index| {
let the_move = self.move_data.moves.borrow();
let the_move = the_move.get(index);
let the_move = &(*the_move)[index];
let moved_path = the_move.path;
if base_indices.iter().any(|x| x == &moved_path) {
// Scenario 1 or 2: `loan_path` or some base path of
@ -675,7 +675,7 @@ impl<'a, 'tcx> FlowedMoveData<'a, 'tcx> {
self.dfcx_assign.each_bit_on_entry(id, |index| {
let assignment = self.move_data.var_assignments.borrow();
let assignment = assignment.get(index);
let assignment = &(*assignment)[index];
if assignment.path == loan_path_index && !f(assignment) {
false
} else {

View File

@ -424,7 +424,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
}
ast::ExprMethodCall(_, _, ref args) => {
self.call(expr, pred, &**args.get(0), args.slice_from(1).iter().map(|e| &**e))
self.call(expr, pred, &*args[0], args.slice_from(1).iter().map(|e| &**e))
}
ast::ExprIndex(ref l, ref r) |

View File

@ -41,9 +41,9 @@ fn replace_newline_with_backslash_l(s: String) -> String {
s.as_slice().chars().rev().take(2).collect();
last_two.reverse();
if last_two.as_slice() != ['\\', 'l'] {
s = s.append("\\l");
s.push_str("\\l");
}
s.to_string()
s
} else {
s
}
@ -76,16 +76,15 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> {
let mut put_one = false;
for (i, &node_id) in e.data.exiting_scopes.iter().enumerate() {
if put_one {
label = label.append(",\\l");
label.push_str(",\\l");
} else {
put_one = true;
}
let s = self.ast_map.node_to_string(node_id);
// left-aligns the lines
let s = replace_newline_with_backslash_l(s);
label = label.append(format!("exiting scope_{} {}",
i,
s.as_slice()).as_slice());
label.push_str(format!("exiting scope_{} {}", i,
s.as_slice()).as_slice());
}
dot::EscStr(label.into_maybe_owned())
}

View File

@ -66,7 +66,7 @@ impl<'a> fmt::Show for Matrix<'a> {
let column_count = m.iter().map(|row| row.len()).max().unwrap_or(0u);
assert!(m.iter().all(|row| row.len() == column_count));
let column_widths: Vec<uint> = range(0, column_count).map(|col| {
pretty_printed_matrix.iter().map(|row| row.get(col).len()).max().unwrap_or(0u)
pretty_printed_matrix.iter().map(|row| row[col].len()).max().unwrap_or(0u)
}).collect();
let total_width = column_widths.iter().map(|n| *n).sum() + column_count * 3 + 1;
@ -76,7 +76,7 @@ impl<'a> fmt::Show for Matrix<'a> {
try!(write!(f, "+"));
for (column, pat_str) in row.into_iter().enumerate() {
try!(write!(f, " "));
f.width = Some(*column_widths.get(column));
f.width = Some(column_widths[column]);
try!(f.pad(pat_str.as_slice()));
try!(write!(f, " +"));
}
@ -269,7 +269,7 @@ fn check_arms(cx: &MatchCheckCtxt, arms: &[(Vec<P<Pat>>, Option<&Expr>)], source
} else {
// find the first arm pattern so we can use its span
let &(ref first_arm_pats, _) = &arms[0];
let first_pat = first_arm_pats.get(0);
let first_pat = &first_arm_pats[0];
let span = first_pat.span;
span_err!(cx.tcx.sess, span, E0162, "irrefutable if-let pattern");
printed_if_let_err = true;
@ -279,7 +279,7 @@ fn check_arms(cx: &MatchCheckCtxt, arms: &[(Vec<P<Pat>>, Option<&Expr>)], source
MatchWhileLetDesugar => {
// find the first arm pattern so we can use its span
let &(ref first_arm_pats, _) = &arms[0];
let first_pat = first_arm_pats.get(0);
let first_pat = &first_arm_pats[0];
let span = first_pat.span;
span_err!(cx.tcx.sess, span, E0165, "irrefutable while-let pattern");
},
@ -475,7 +475,7 @@ fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
fn missing_constructor(cx: &MatchCheckCtxt, &Matrix(ref rows): &Matrix,
left_ty: ty::t, max_slice_length: uint) -> Option<Constructor> {
let used_constructors: Vec<Constructor> = rows.iter()
.flat_map(|row| pat_constructors(cx, *row.get(0), left_ty, max_slice_length).into_iter())
.flat_map(|row| pat_constructors(cx, row[0], left_ty, max_slice_length).into_iter())
.collect();
all_constructors(cx, left_ty, max_slice_length)
.into_iter()
@ -538,11 +538,11 @@ fn is_useful(cx: &MatchCheckCtxt,
LeaveOutWitness => Useful
};
}
if rows.get(0).len() == 0u {
if rows[0].len() == 0u {
return NotUseful;
}
let real_pat = match rows.iter().find(|r| r.get(0).id != DUMMY_NODE_ID) {
Some(r) => raw_pat(*r.get(0)),
let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
Some(r) => raw_pat(r[0]),
None if v.len() == 0 => return NotUseful,
None => v[0]
};
@ -552,7 +552,7 @@ fn is_useful(cx: &MatchCheckCtxt,
ty::pat_ty(cx.tcx, &*real_pat)
};
let max_slice_length = rows.iter().filter_map(|row| match row.get(0).node {
let max_slice_length = rows.iter().filter_map(|row| match row[0].node {
PatVec(ref before, _, ref after) => Some(before.len() + after.len()),
_ => None
}).max().map_or(0, |v| v + 1);
@ -583,7 +583,7 @@ fn is_useful(cx: &MatchCheckCtxt,
Some(constructor) => {
let matrix = rows.iter().filter_map(|r| {
if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
Some(Vec::from_slice(r.tail()))
Some(r.tail().to_vec())
} else {
None
}
@ -883,7 +883,11 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat],
None
}
};
head.map(|head| head.append(r[..col]).append(r[col + 1..]))
head.map(|mut head| {
head.push_all(r[..col]);
head.push_all(r[col + 1..]);
head
})
}
fn check_local(cx: &mut MatchCheckCtxt, loc: &Local) {

View File

@ -418,7 +418,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> {
let bits = self.kills.slice_mut(start, end);
debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [before]",
self.analysis_name, flow_exit, mut_bits_to_string(bits));
bits.copy_from(orig_kills.as_slice());
bits.clone_from_slice(orig_kills.as_slice());
debug!("{:s} add_kills_from_flow_exits flow_exit={} bits={} [after]",
self.analysis_name, flow_exit, mut_bits_to_string(bits));
}
@ -484,7 +484,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> {
let (start, end) = self.dfcx.compute_id_range(node_index);
// Initialize local bitvector with state on-entry.
in_out.copy_from(self.dfcx.on_entry.slice(start, end));
in_out.clone_from_slice(self.dfcx.on_entry.slice(start, end));
// Compute state on-exit by applying transfer function to
// state on-entry.
@ -550,13 +550,13 @@ fn bits_to_string(words: &[uint]) -> String {
for &word in words.iter() {
let mut v = word;
for _ in range(0u, uint::BYTES) {
result.push_char(sep);
result.push(sep);
result.push_str(format!("{:02x}", v & 0xFF).as_slice());
v >>= 8;
sep = '-';
}
}
result.push_char(']');
result.push(']');
return result
}

View File

@ -157,8 +157,8 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
}
fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[ast::FieldPat]) {
let id = match self.tcx.def_map.borrow().get(&lhs.id) {
&def::DefVariant(_, id, _) => id,
let id = match (*self.tcx.def_map.borrow())[lhs.id] {
def::DefVariant(_, id, _) => id,
_ => {
match ty::ty_to_def_id(ty::node_id_to_type(self.tcx,
lhs.id)) {
@ -494,7 +494,7 @@ impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
None => (),
Some(impl_list) => {
for impl_did in impl_list.iter() {
for item_did in impl_items.get(impl_did).iter() {
for item_did in (*impl_items)[*impl_did].iter() {
if self.live_symbols.contains(&item_did.def_id()
.node) {
return true;

View File

@ -145,7 +145,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> {
match expr.node {
ast::ExprMethodCall(_, _, _) => {
let method_call = MethodCall::expr(expr.id);
let base_type = self.tcx.method_map.borrow().get(&method_call).ty;
let base_type = (*self.tcx.method_map.borrow())[method_call].ty;
debug!("effect: method call case, base type is {}",
ppaux::ty_to_string(self.tcx, base_type));
if type_is_unsafe_function(base_type) {

View File

@ -738,7 +738,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,TYPER> {
None => {}
Some(method_ty) => {
let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
let self_ty = *ty::ty_fn_args(method_ty).get(0);
let self_ty = ty::ty_fn_args(method_ty)[0];
let (m, r) = match ty::get(self_ty).sty {
ty::ty_rptr(r, ref m) => (m.mutbl, r),
_ => self.tcx().sess.span_bug(expr.span,

View File

@ -146,11 +146,11 @@ impl<N,E> Graph<N,E> {
}
pub fn node_data<'a>(&'a self, idx: NodeIndex) -> &'a N {
&self.nodes.get(idx.get()).data
&self.nodes[idx.get()].data
}
pub fn node<'a>(&'a self, idx: NodeIndex) -> &'a Node<N> {
self.nodes.get(idx.get())
&self.nodes[idx.get()]
}
///////////////////////////////////////////////////////////////////////////
@ -167,9 +167,9 @@ impl<N,E> Graph<N,E> {
let idx = self.next_edge_index();
// read current first of the list of edges from each node
let source_first = self.nodes.get(source.get())
let source_first = self.nodes[source.get()]
.first_edge[Outgoing.repr];
let target_first = self.nodes.get(target.get())
let target_first = self.nodes[target.get()]
.first_edge[Incoming.repr];
// create the new edge, with the previous firsts from each node
@ -193,11 +193,11 @@ impl<N,E> Graph<N,E> {
}
pub fn edge_data<'a>(&'a self, idx: EdgeIndex) -> &'a E {
&self.edges.get(idx.get()).data
&self.edges[idx.get()].data
}
pub fn edge<'a>(&'a self, idx: EdgeIndex) -> &'a Edge<E> {
self.edges.get(idx.get())
&self.edges[idx.get()]
}
pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex {
@ -205,7 +205,7 @@ impl<N,E> Graph<N,E> {
//! This is useful if you wish to modify the graph while walking
//! the linked list of edges.
self.nodes.get(node.get()).first_edge[dir.repr]
self.nodes[node.get()].first_edge[dir.repr]
}
pub fn next_adjacent(&self, edge: EdgeIndex, dir: Direction) -> EdgeIndex {
@ -213,7 +213,7 @@ impl<N,E> Graph<N,E> {
//! This is useful if you wish to modify the graph while walking
//! the linked list of edges.
self.edges.get(edge.get()).next_edge[dir.repr]
self.edges[edge.get()].next_edge[dir.repr]
}
///////////////////////////////////////////////////////////////////////////
@ -257,7 +257,7 @@ impl<N,E> Graph<N,E> {
let mut edge_idx = self.first_adjacent(node, dir);
while edge_idx != InvalidEdgeIndex {
let edge = self.edges.get(edge_idx.get());
let edge = &self.edges[edge_idx.get()];
if !f(edge_idx, edge) {
return false;
}

View File

@ -126,7 +126,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> {
match ty::get(typ).sty {
ty_bare_fn(ref bare_fn_ty)
if bare_fn_ty.abi == RustIntrinsic => {
let from = *bare_fn_ty.sig.inputs.get(0);
let from = bare_fn_ty.sig.inputs[0];
let to = bare_fn_ty.sig.output;
self.check_transmute(expr.span, from, to, expr.id);
}

View File

@ -76,9 +76,9 @@ impl LanguageItems {
}
pub fn require(&self, it: LangItem) -> Result<ast::DefId, String> {
match self.items.get(it as uint) {
&Some(id) => Ok(id),
&None => {
match self.items[it as uint] {
Some(id) => Ok(id),
None => {
Err(format!("requires `{}` lang_item",
LanguageItems::item_name(it as uint)))
}
@ -113,7 +113,7 @@ impl LanguageItems {
$(
#[allow(dead_code)]
pub fn $method(&self) -> Option<ast::DefId> {
*self.items.get($variant as uint)
self.items[$variant as uint]
}
)*
}
@ -162,12 +162,12 @@ impl<'a> LanguageItemCollector<'a> {
pub fn collect_item(&mut self, item_index: uint,
item_def_id: ast::DefId, span: Span) {
// Check for duplicates.
match self.items.items.get(item_index) {
&Some(original_def_id) if original_def_id != item_def_id => {
match self.items.items[item_index] {
Some(original_def_id) if original_def_id != item_def_id => {
span_err!(self.session, span, E0152,
"duplicate entry for `{}`", LanguageItems::item_name(item_index));
}
&Some(_) | &None => {
Some(_) | None => {
// OK.
}
}

View File

@ -327,11 +327,11 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> {
}
fn variable_name(&self, var: Variable) -> String {
match self.var_kinds.get(var.get()) {
&Local(LocalInfo { ident: nm, .. }) | &Arg(_, nm) => {
match self.var_kinds[var.get()] {
Local(LocalInfo { ident: nm, .. }) | Arg(_, nm) => {
token::get_ident(nm).get().to_string()
},
&ImplicitRet => "<implicit-ret>".to_string()
ImplicitRet => "<implicit-ret>".to_string()
}
}
@ -340,7 +340,7 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> {
}
fn lnk(&self, ln: LiveNode) -> LiveNodeKind {
*self.lnks.get(ln.get())
self.lnks[ln.get()]
}
}
@ -647,7 +647,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
fn live_on_entry(&self, ln: LiveNode, var: Variable)
-> Option<LiveNodeKind> {
assert!(ln.is_valid());
let reader = self.users.get(self.idx(ln, var)).reader;
let reader = self.users[self.idx(ln, var)].reader;
if reader.is_valid() {Some(self.ir.lnk(reader))} else {None}
}
@ -656,25 +656,25 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
*/
fn live_on_exit(&self, ln: LiveNode, var: Variable)
-> Option<LiveNodeKind> {
let successor = *self.successors.get(ln.get());
let successor = self.successors[ln.get()];
self.live_on_entry(successor, var)
}
fn used_on_entry(&self, ln: LiveNode, var: Variable) -> bool {
assert!(ln.is_valid());
self.users.get(self.idx(ln, var)).used
self.users[self.idx(ln, var)].used
}
fn assigned_on_entry(&self, ln: LiveNode, var: Variable)
-> Option<LiveNodeKind> {
assert!(ln.is_valid());
let writer = self.users.get(self.idx(ln, var)).writer;
let writer = self.users[self.idx(ln, var)].writer;
if writer.is_valid() {Some(self.ir.lnk(writer))} else {None}
}
fn assigned_on_exit(&self, ln: LiveNode, var: Variable)
-> Option<LiveNodeKind> {
let successor = *self.successors.get(ln.get());
let successor = self.successors[ln.get()];
self.assigned_on_entry(successor, var)
}
@ -736,10 +736,10 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
{
let wr = &mut wr as &mut io::Writer;
write!(wr, "[ln({}) of kind {} reads", ln.get(), self.ir.lnk(ln));
self.write_vars(wr, ln, |idx| self.users.get(idx).reader);
self.write_vars(wr, ln, |idx| self.users[idx].reader);
write!(wr, " writes");
self.write_vars(wr, ln, |idx| self.users.get(idx).writer);
write!(wr, " precedes {}]", self.successors.get(ln.get()).to_string());
self.write_vars(wr, ln, |idx| self.users[idx].writer);
write!(wr, " precedes {}]", self.successors[ln.get()].to_string());
}
str::from_utf8(wr.unwrap().as_slice()).unwrap().to_string()
}
@ -762,7 +762,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
*self.successors.get_mut(ln.get()) = succ_ln;
self.indices2(ln, succ_ln, |this, idx, succ_idx| {
*this.users.get_mut(idx) = *this.users.get(succ_idx)
*this.users.get_mut(idx) = this.users[succ_idx]
});
debug!("init_from_succ(ln={}, succ={})",
self.ln_str(ln), self.ln_str(succ_ln));
@ -777,11 +777,11 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
let mut changed = false;
self.indices2(ln, succ_ln, |this, idx, succ_idx| {
changed |= copy_if_invalid(this.users.get(succ_idx).reader,
changed |= copy_if_invalid(this.users[succ_idx].reader,
&mut this.users.get_mut(idx).reader);
changed |= copy_if_invalid(this.users.get(succ_idx).writer,
changed |= copy_if_invalid(this.users[succ_idx].writer,
&mut this.users.get_mut(idx).writer);
if this.users.get(succ_idx).used && !this.users.get(idx).used {
if this.users[succ_idx].used && !this.users[idx].used {
this.users.get_mut(idx).used = true;
changed = true;
}

View File

@ -500,7 +500,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
}
ast::ExprPath(_) => {
let def = *self.tcx().def_map.borrow().get(&expr.id);
let def = (*self.tcx().def_map.borrow())[expr.id];
self.cat_def(expr.id, expr.span, expr_ty, def)
}
@ -597,7 +597,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
}
ty::ty_unboxed_closure(closure_id, _) => {
let unboxed_closures = self.typer.unboxed_closures().borrow();
let kind = unboxed_closures.get(&closure_id).kind;
let kind = (*unboxed_closures)[closure_id].kind;
let mode = self.typer.capture_mode(fn_node_id);
self.cat_upvar(id, span, var_id, fn_node_id, kind, mode, true)
}
@ -953,7 +953,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
Some(method_ty) => {
let ref_ty = ty::ty_fn_ret(method_ty);
base_cmt = self.cat_rvalue_node(elt.id(), elt.span(), ref_ty);
*ty::ty_fn_args(method_ty).get(0)
ty::ty_fn_args(method_ty)[0]
}
None => {
match ty::array_element_ty(base_cmt.ty) {

View File

@ -348,7 +348,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> {
// crate module gets processed as well.
if self.prev_exported {
assert!(self.exp_map2.contains_key(&id), "wut {}", id);
for export in self.exp_map2.get(&id).iter() {
for export in self.exp_map2[id].iter() {
if is_local(export.def_id) {
self.reexports.insert(export.def_id.node);
}
@ -524,7 +524,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
// if we've reached the root, then everything was allowable and this
// access is public.
if closest_private_id == ast::CRATE_NODE_ID { return Allowable }
closest_private_id = *self.parents.get(&closest_private_id);
closest_private_id = self.parents[closest_private_id];
// If we reached the top, then we were public all the way down and
// we can allow this access.
@ -542,7 +542,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
/// whether the node is accessible by the current module that iteration is
/// inside.
fn private_accessible(&self, id: ast::NodeId) -> bool {
let parent = *self.parents.get(&id);
let parent = self.parents[id];
debug!("privacy - accessible parent {}", self.nodestr(parent));
// After finding `did`'s closest private member, we roll ourselves back
@ -566,7 +566,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
_ => {}
}
cur = *self.parents.get(&cur);
cur = self.parents[cur];
}
}
@ -658,7 +658,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
debug!("privacy - check named field {} in struct {}", ident.name, id);
fields.iter().find(|f| f.name == ident.name).unwrap()
}
UnnamedField(idx) => fields.get(idx)
UnnamedField(idx) => &fields[idx]
};
if field.vis == ast::Public ||
(is_local(field.id) && self.private_accessible(field.id.node)) {
@ -734,7 +734,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> {
name).as_slice())
};
match *self.last_private_map.get(&path_id) {
match self.last_private_map[path_id] {
resolve::LastMod(resolve::AllPublic) => {},
resolve::LastMod(resolve::DependsOn(def)) => {
self.report_error(ck_public(def));

View File

@ -138,7 +138,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> {
}
ast::ExprMethodCall(..) => {
let method_call = typeck::MethodCall::expr(expr.id);
match self.tcx.method_map.borrow().get(&method_call).origin {
match (*self.tcx.method_map.borrow())[method_call].origin {
typeck::MethodStatic(def_id) => {
if is_local(def_id) {
if self.def_id_represents_local_inlined_item(def_id) {

View File

@ -334,7 +334,7 @@ impl RegionMaps {
// where they diverge. If one vector is a suffix of the other,
// then the corresponding scope is a superscope of the other.
if *a_ancestors.get(a_index) != *b_ancestors.get(b_index) {
if a_ancestors[a_index] != b_ancestors[b_index] {
return None;
}
@ -345,8 +345,8 @@ impl RegionMaps {
if b_index == 0u { return Some(scope_b); }
a_index -= 1u;
b_index -= 1u;
if *a_ancestors.get(a_index) != *b_ancestors.get(b_index) {
return Some(*a_ancestors.get(a_index + 1u));
if a_ancestors[a_index] != b_ancestors[b_index] {
return Some(a_ancestors[a_index + 1]);
}
}

View File

@ -1307,11 +1307,13 @@ impl<'a> Resolver<'a> {
// If this is a newtype or unit-like struct, define a name
// in the value namespace as well
ctor_id.while_some(|cid| {
name_bindings.define_value(DefStruct(local_def(cid)), sp,
is_public);
None
});
match ctor_id {
Some(cid) => {
name_bindings.define_value(DefStruct(local_def(cid)),
sp, is_public);
}
None => {}
}
// Record the def ID and fields of this struct.
let named_fields = struct_def.fields.iter().filter_map(|f| {
@ -1644,7 +1646,7 @@ impl<'a> Resolver<'a> {
}
};
let module_path = module_path.as_slice().init();
(Vec::from_slice(module_path), name)
(module_path.to_vec(), name)
}
};
self.build_import_directive(
@ -2232,7 +2234,7 @@ impl<'a> Resolver<'a> {
let import_count = imports.len();
while module.resolved_import_count.get() < import_count {
let import_index = module.resolved_import_count.get();
let import_directive = imports.get(import_index);
let import_directive = &(*imports)[import_index];
match self.resolve_import_for_module(module.clone(),
import_directive) {
Failed(err) => {
@ -3669,15 +3671,15 @@ impl<'a> Resolver<'a> {
if index != import_count {
let sn = self.session
.codemap()
.span_to_snippet(imports.get(index).span)
.span_to_snippet((*imports)[index].span)
.unwrap();
if sn.as_slice().contains("::") {
self.resolve_error(imports.get(index).span,
self.resolve_error((*imports)[index].span,
"unresolved import");
} else {
let err = format!("unresolved import (maybe you meant `{}::*`?)",
sn.as_slice().slice(0, sn.len()));
self.resolve_error(imports.get(index).span, err.as_slice());
self.resolve_error((*imports)[index].span, err.as_slice());
}
}
@ -3905,12 +3907,17 @@ impl<'a> Resolver<'a> {
def = DefUpvar(node_id, function_id, last_proc_body_id);
let mut seen = self.freevars_seen.borrow_mut();
let seen = seen.find_or_insert(function_id, NodeSet::new());
let seen = match seen.entry(function_id) {
Occupied(v) => v.into_mut(),
Vacant(v) => v.set(NodeSet::new()),
};
if seen.contains(&node_id) {
continue;
}
self.freevars.borrow_mut().find_or_insert(function_id, vec![])
.push(Freevar { def: prev_def, span: span });
match self.freevars.borrow_mut().entry(function_id) {
Occupied(v) => v.into_mut(),
Vacant(v) => v.set(vec![]),
}.push(Freevar { def: prev_def, span: span });
seen.insert(node_id);
}
MethodRibKind(item_id, _) => {
@ -4714,7 +4721,7 @@ impl<'a> Resolver<'a> {
if arm.pats.len() == 0 {
return
}
let map_0 = self.binding_mode_map(&**arm.pats.get(0));
let map_0 = self.binding_mode_map(&*arm.pats[0]);
for (i, p) in arm.pats.iter().enumerate() {
let map_i = self.binding_mode_map(&**p);
@ -5695,18 +5702,18 @@ impl<'a> Resolver<'a> {
for (i, other) in maybes.iter().enumerate() {
*values.get_mut(i) = name.lev_distance(other.get());
if *values.get(i) <= *values.get(smallest) {
if values[i] <= values[smallest] {
smallest = i;
}
}
if values.len() > 0 &&
*values.get(smallest) != uint::MAX &&
*values.get(smallest) < name.len() + 2 &&
*values.get(smallest) <= max_distance &&
name != maybes.get(smallest).get() {
values[smallest] != uint::MAX &&
values[smallest] < name.len() + 2 &&
values[smallest] <= max_distance &&
name != maybes[smallest].get() {
Some(maybes.get(smallest).get().to_string())
Some(maybes[smallest].get().to_string())
} else {
None

View File

@ -399,7 +399,7 @@ impl<'a> LifetimeContext<'a> {
fn check_lifetime_defs(&mut self, lifetimes: &Vec<ast::LifetimeDef>) {
for i in range(0, lifetimes.len()) {
let lifetime_i = lifetimes.get(i);
let lifetime_i = &lifetimes[i];
let special_idents = [special_idents::static_lifetime];
for lifetime in lifetimes.iter() {
@ -413,7 +413,7 @@ impl<'a> LifetimeContext<'a> {
}
for j in range(i + 1, lifetimes.len()) {
let lifetime_j = lifetimes.get(j);
let lifetime_j = &lifetimes[j];
if lifetime_i.lifetime.name == lifetime_j.lifetime.name {
self.sess.span_err(

View File

@ -208,7 +208,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
self.sess.bug(format!("def_map has no key for {} in lookup_type_ref",
ref_id).as_slice());
}
let def = *self.analysis.ty_cx.def_map.borrow().get(&ref_id);
let def = (*self.analysis.ty_cx.def_map.borrow())[ref_id];
match def {
def::DefPrimTy(_) => None,
_ => Some(def.def_id()),
@ -221,7 +221,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
self.sess.span_bug(span, format!("def_map has no key for {} in lookup_def_kind",
ref_id).as_slice());
}
let def = *def_map.get(&ref_id);
let def = (*def_map)[ref_id];
match def {
def::DefMod(_) |
def::DefForeignMod(_) => Some(recorder::ModRef),
@ -261,7 +261,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
let span_utils = self.span;
for &(id, ref p, _, _) in self.collected_paths.iter() {
let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
*self.analysis.ty_cx.node_types.borrow().get(&(id as uint)));
(*self.analysis.ty_cx.node_types.borrow())[id as uint]);
// get the span only for the name of the variable (I hope the path is only ever a
// variable name, but who knows?)
self.fmt.formal_str(p.span,
@ -302,7 +302,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
},
None => {}
}
result.append(">::")
result.push_str(">::");
result
}
_ => {
self.sess.span_bug(method.span,
@ -326,8 +327,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
scope_id = def_id.node;
match self.analysis.ty_cx.map.get(def_id.node) {
NodeItem(_) => {
let result = ty::item_path_str(&self.analysis.ty_cx, def_id);
result.append("::")
let mut result = ty::item_path_str(&self.analysis.ty_cx, def_id);
result.push_str("::");
result
}
_ => {
self.sess.span_bug(method.span,
@ -350,12 +352,16 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
// record the decl for this def (if it has one)
let decl_id = ty::trait_item_of_item(&self.analysis.ty_cx,
ast_util::local_def(method.id))
.filtered(|def_id| {
match *def_id {
.and_then(|def_id| {
if match def_id {
ty::MethodTraitItemId(def_id) => {
method.id != 0 && def_id.node == 0
}
ty::TypeTraitItemId(_) => false,
} {
Some(def_id)
} else {
None
}
});
let decl_id = match decl_id {
@ -421,7 +427,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
let name = get_ident(ident);
let qualname = format!("{}::{}", qualname, name);
let typ = ppaux::ty_to_string(&self.analysis.ty_cx,
*self.analysis.ty_cx.node_types.borrow().get(&(field.node.id as uint)));
(*self.analysis.ty_cx.node_types.borrow())[field.node.id as uint]);
match self.span.sub_span_before_token(field.span, token::COLON) {
Some(sub_span) => self.fmt.field_str(field.span,
Some(sub_span),
@ -590,7 +596,9 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
for variant in enum_definition.variants.iter() {
let name = get_ident(variant.node.name);
let name = name.get();
let qualname = qualname.clone().append("::").append(name);
let mut qualname = qualname.clone();
qualname.push_str("::");
qualname.push_str(name);
let val = self.span.snippet(variant.span);
match variant.node.kind {
ast::TupleVariantKind(ref args) => {
@ -758,7 +766,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
format!("def_map has no key for {} in visit_expr",
ex.id).as_slice());
}
let def = def_map.get(&ex.id);
let def = &(*def_map)[ex.id];
let sub_span = self.span.span_for_last_ident(ex.span);
match *def {
def::DefUpvar(..) |
@ -796,7 +804,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
.ty_cx
.impl_items
.borrow();
Some(impl_items.get(&def_id)
Some((*impl_items)[def_id]
.iter()
.find(|mr| {
ty::impl_or_trait_item(
@ -897,7 +905,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
ex: &ast::Expr,
args: &Vec<P<ast::Expr>>) {
let method_map = self.analysis.ty_cx.method_map.borrow();
let method_callee = method_map.get(&typeck::MethodCall::expr(ex.id));
let method_callee = &(*method_map)[typeck::MethodCall::expr(ex.id)];
let (def_id, decl_id) = match method_callee.origin {
typeck::MethodStatic(def_id) |
typeck::MethodStaticUnboxedClosure(def_id) => {
@ -1116,7 +1124,9 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
ast_util::local_def(method_type.id)) {
Some(def_id) => {
scope_id = def_id.node;
ty::item_path_str(&self.analysis.ty_cx, def_id).append("::")
let mut s = ty::item_path_str(&self.analysis.ty_cx, def_id);
s.push_str("::");
s
},
None => {
self.sess.span_bug(method_type.span,
@ -1347,7 +1357,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
return
}
let id = String::from_str("$").append(ex.id.to_string().as_slice());
let mut id = String::from_str("$");
id.push_str(ex.id.to_string().as_slice());
self.process_formals(&decl.inputs, id.as_slice());
// walk arg and return types
@ -1399,7 +1410,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
format!("def_map has no key for {} in visit_arm",
id).as_slice());
}
let def = def_map.get(&id);
let def = &(*def_map)[id];
match *def {
def::DefLocal(id) => self.fmt.variable_str(p.span,
sub_span,
@ -1449,7 +1460,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
for &(id, ref p, ref immut, _) in self.collected_paths.iter() {
let value = if *immut { value.to_string() } else { "<mutable>".to_string() };
let types = self.analysis.ty_cx.node_types.borrow();
let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&(id as uint)));
let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*types)[id as uint]);
// Get the span only for the name of the variable (I hope the path
// is only ever a variable name, but who knows?).
let sub_span = self.span.span_for_last_ident(p.span);

View File

@ -165,12 +165,18 @@ impl<'a> FmtStrs<'a> {
let pairs = fields.iter().zip(values);
let mut strs = pairs.map(|(f, v)| format!(",{},\"{}\"", f, escape(
if *f == "qualname" {
self.krate.clone().append("::").append(v)
let mut n = self.krate.clone();
n.push_str("::");
n.push_str(v);
n
} else {
String::from_str(v)
}
)));
Some(strs.fold(String::new(), |s, ss| s.append(ss.as_slice())))
Some(strs.fold(String::new(), |mut s, ss| {
s.push_str(ss.as_slice());
s
}))
}
pub fn record_without_span(&mut self,
@ -195,8 +201,10 @@ impl<'a> FmtStrs<'a> {
None => return,
};
let result = String::from_str(label);
self.recorder.record(result.append(values_str.as_slice()).append("\n").as_slice());
let mut result = String::from_str(label);
result.push_str(values_str.as_slice());
result.push_str("\n");
self.recorder.record(result.as_slice());
}
pub fn record_with_span(&mut self,
@ -252,7 +260,9 @@ impl<'a> FmtStrs<'a> {
// the local case they can be overridden in one block and there is no nice way
// to refer to such a scope in english, so we just hack it by appending the
// variable def's node id
let qualname = String::from_str(name).append("$").append(id.to_string().as_slice());
let mut qualname = String::from_str(name);
qualname.push_str("$");
qualname.push_str(id.to_string().as_slice());
self.check_and_record(Variable,
span,
sub_span,
@ -267,7 +277,9 @@ impl<'a> FmtStrs<'a> {
fn_name: &str,
name: &str,
typ: &str) {
let qualname = String::from_str(fn_name).append("::").append(name);
let mut qualname = String::from_str(fn_name);
qualname.push_str("::");
qualname.push_str(name);
self.check_and_record(Variable,
span,
sub_span,

View File

@ -315,8 +315,8 @@ impl<T> VecPerParamSpace<T> {
let type_limit = t.len();
let self_limit = t.len() + s.len();
let mut content = t;
content.push_all_move(s);
content.push_all_move(f);
content.extend(s.into_iter());
content.extend(f.into_iter());
VecPerParamSpace {
type_limit: type_limit,
self_limit: self_limit,

View File

@ -31,7 +31,6 @@ use middle::ty_fold::TypeFoldable;
use std::cell::RefCell;
use std::collections::hashmap::HashMap;
use std::rc::Rc;
use std::result;
use syntax::ast;
use util::ppaux::Repr;
@ -1221,18 +1220,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
nested: Vec<ty::t>)
-> VtableBuiltinData<Obligation>
{
let obligations =
result::collect(
nested
.iter()
.map(|&t| {
util::obligation_for_builtin_bound(
self.tcx(),
obligation.cause,
bound,
obligation.recursion_depth + 1,
t)
}));
let obligations = nested.iter().map(|&t| {
util::obligation_for_builtin_bound(
self.tcx(),
obligation.cause,
bound,
obligation.recursion_depth + 1,
t)
}).collect::<Result<_, _>>();
let obligations = match obligations {
Ok(o) => o,
Err(ErrorReported) => Vec::new()
@ -1302,7 +1297,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
|br| self.infcx.next_region_var(
infer::LateBoundRegion(obligation.cause.span, br)));
let arguments_tuple = *new_signature.inputs.get(0);
let arguments_tuple = new_signature.inputs[0];
let trait_ref = Rc::new(ty::TraitRef {
def_id: obligation.trait_ref.def_id,
substs: Substs::new_trait(

View File

@ -110,7 +110,7 @@ impl<'cx, 'tcx> Iterator<Rc<ty::TraitRef>> for Supertraits<'cx, 'tcx> {
fn next(&mut self) -> Option<Rc<ty::TraitRef>> {
loop {
// Extract next item from top-most stack frame, if any.
let next_trait = match self.stack.mut_last() {
let next_trait = match self.stack.last_mut() {
None => {
// No more stack frames. Done.
return None;
@ -121,8 +121,7 @@ impl<'cx, 'tcx> Iterator<Rc<ty::TraitRef>> for Supertraits<'cx, 'tcx> {
// Still more supertraits left in the top stack frame.
entry.position += 1;
let next_trait =
(*entry.supertraits.get(p)).clone();
let next_trait = entry.supertraits[p].clone();
Some(next_trait)
} else {
None

View File

@ -369,7 +369,7 @@ impl<'a, 'p, 'blk, 'tcx> Repr for Match<'a, 'p, 'blk, 'tcx> {
fn has_nested_bindings(m: &[Match], col: uint) -> bool {
for br in m.iter() {
match br.pats.get(col).node {
match br.pats[col].node {
ast::PatIdent(_, _, Some(_)) => return true,
_ => ()
}
@ -391,7 +391,7 @@ fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m.iter().map(|br| {
let mut bound_ptrs = br.bound_ptrs.clone();
let mut pat = *br.pats.get(col);
let mut pat = br.pats[col];
loop {
pat = match pat.node {
ast::PatIdent(_, ref path, Some(ref inner)) => {
@ -430,7 +430,7 @@ fn enter_match<'a, 'b, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
m.iter().filter_map(|br| {
e(br.pats.as_slice()).map(|pats| {
let this = *br.pats.get(col);
let this = br.pats[col];
let mut bound_ptrs = br.bound_ptrs.clone();
match this.node {
ast::PatIdent(_, ref path, None) => {
@ -476,7 +476,9 @@ fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
// Collect all of the matches that can match against anything.
enter_match(bcx, dm, m, col, val, |pats| {
if pat_is_binding_or_wild(dm, &*pats[col]) {
Some(Vec::from_slice(pats[..col]).append(pats[col + 1..]))
let mut r = pats[..col].to_vec();
r.push_all(pats[col + 1..]);
Some(r)
} else {
None
}
@ -561,7 +563,7 @@ fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
let mut found: Vec<Opt> = vec![];
for br in m.iter() {
let cur = *br.pats.get(col);
let cur = br.pats[col];
let opt = match cur.node {
ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)),
ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
@ -672,7 +674,7 @@ fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
macro_rules! any_pat (
($m:expr, $col:expr, $pattern:pat) => (
($m).iter().any(|br| {
match br.pats.get($col).node {
match br.pats[$col].node {
$pattern => true,
_ => false
}
@ -690,7 +692,7 @@ fn any_region_pat(m: &[Match], col: uint) -> bool {
fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
m.iter().any(|br| {
let pat = *br.pats.get(col);
let pat = br.pats[col];
match pat.node {
ast::PatTup(_) => true,
ast::PatStruct(..) => {
@ -967,7 +969,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
None => {
let data = &m[0].data;
for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
let llmatch = data.bindings_map.get(ident).llmatch;
let llmatch = data.bindings_map[*ident].llmatch;
call_lifetime_start(bcx, llmatch);
Store(bcx, *value_ptr, llmatch);
}
@ -999,12 +1001,13 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
let tcx = bcx.tcx();
let dm = &tcx.def_map;
let vals_left = Vec::from_slice(vals[0u..col]).append(vals[col + 1u..vals.len()]);
let mut vals_left = vals[0u..col].to_vec();
vals_left.push_all(vals[col + 1u..]);
let ccx = bcx.fcx.ccx;
// Find a real id (we're adding placeholder wildcard patterns, but
// each column is guaranteed to have at least one real pattern)
let pat_id = m.iter().map(|br| br.pats.get(col).id)
let pat_id = m.iter().map(|br| br.pats[col].id)
.find(|&id| id != DUMMY_NODE_ID)
.unwrap_or(DUMMY_NODE_ID);
@ -1041,7 +1044,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
&check_match::Single, col,
field_vals.len())
);
let vals = field_vals.append(vals_left.as_slice());
let mut vals = field_vals;
vals.push_all(vals_left.as_slice());
compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
return;
}
@ -1055,7 +1059,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
let mut test_val = val;
debug!("test_val={}", bcx.val_to_string(test_val));
if opts.len() > 0u {
match *opts.get(0) {
match opts[0] {
ConstantValue(_) | ConstantRange(_, _) => {
test_val = load_if_immediate(bcx, val, left_ty);
kind = if ty::type_is_integral(left_ty) {
@ -1194,7 +1198,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
ConstantValue(_) | ConstantRange(_, _) => ()
}
let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
let opt_vals = unpacked.append(vals_left.as_slice());
let mut opt_vals = unpacked;
opt_vals.push_all(vals_left.as_slice());
compile_submatch(opt_cx,
opt_ms.as_slice(),
opt_vals.as_slice(),
@ -1358,7 +1363,7 @@ fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
bodycx: fcx.new_id_block("case_body", arm.body.id),
arm: arm,
bindings_map: create_bindings_map(bcx, &**arm.pats.get(0), discr_expr, &*arm.body)
bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
}).collect();
let mut static_inliner = StaticInliner::new(scope_cx.tcx());
@ -1654,7 +1659,7 @@ fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
val);
for sub_pat in sub_pats.iter() {
for (i, &argval) in args.vals.iter().enumerate() {
bcx = bind_irrefutable_pat(bcx, &**sub_pat.get(i),
bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
argval, cleanup_scope);
}
}

View File

@ -224,7 +224,7 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
// Equivalent to a struct/tuple/newtype.
// (Typechecking will reject discriminant-sizing attrs.)
assert_eq!(hint, attr::ReprAny);
let mut ftys = cases.get(0).tys.clone();
let mut ftys = cases[0].tys.clone();
if dtor { ftys.push(ty::mk_bool()); }
return Univariant(mk_struct(cx, ftys.as_slice(), false, t),
dtor);
@ -234,15 +234,15 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
// Nullable pointer optimization
let mut discr = 0;
while discr < 2 {
if cases.get(1 - discr).is_zerolen(cx, t) {
let st = mk_struct(cx, cases.get(discr).tys.as_slice(),
if cases[1 - discr].is_zerolen(cx, t) {
let st = mk_struct(cx, cases[discr].tys.as_slice(),
false, t);
match cases.get(discr).find_ptr() {
match cases[discr].find_ptr() {
Some(ThinPointer(_)) if st.fields.len() == 1 => {
return RawNullablePointer {
nndiscr: discr as Disr,
nnty: *st.fields.get(0),
nullfields: cases.get(1 - discr).tys.clone()
nnty: st.fields[0],
nullfields: cases[1 - discr].tys.clone()
};
}
Some(ptrfield) => {
@ -250,7 +250,7 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
nndiscr: discr as Disr,
nonnull: st,
ptrfield: ptrfield,
nullfields: cases.get(1 - discr).tys.clone()
nullfields: cases[1 - discr].tys.clone()
};
}
None => { }
@ -267,7 +267,8 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
let ity = range_to_inttype(cx, hint, &bounds);
let fields : Vec<_> = cases.iter().map(|c| {
let mut ftys = vec!(ty_of_inttype(ity)).append(c.tys.as_slice());
let mut ftys = vec!(ty_of_inttype(ity));
ftys.push_all(c.tys.as_slice());
if dtor { ftys.push(ty::mk_bool()); }
mk_struct(cx, ftys.as_slice(), false, t)
}).collect();
@ -369,7 +370,7 @@ fn mk_struct(cx: &CrateContext, tys: &[ty::t], packed: bool, scapegoat: ty::t) -
align: machine::llalign_of_min(cx, llty_rec),
sized: sized,
packed: packed,
fields: Vec::from_slice(tys),
fields: tys.to_vec(),
}
}
@ -745,7 +746,7 @@ pub fn trans_set_discr(bcx: Block, r: &Repr, val: ValueRef, discr: Disr) {
General(ity, ref cases, dtor) => {
if dtor {
let ptr = trans_field_ptr(bcx, r, val, discr,
cases.get(discr as uint).fields.len() - 2);
cases[discr as uint].fields.len() - 2);
Store(bcx, C_u8(bcx.ccx(), 1), ptr);
}
Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
@ -769,7 +770,7 @@ pub fn trans_set_discr(bcx: Block, r: &Repr, val: ValueRef, discr: Disr) {
let (llptrptr, llptrty) = match ptrfield {
ThinPointer(field) =>
(GEPi(bcx, val, [0, field]),
type_of::type_of(bcx.ccx(), *nonnull.fields.get(field))),
type_of::type_of(bcx.ccx(), nonnull.fields[field])),
FatPointer(field, pair) => {
let v = GEPi(bcx, val, [0, field, pair]);
(v, val_ty(v).element_type())
@ -800,7 +801,7 @@ pub fn num_args(r: &Repr, discr: Disr) -> uint {
st.fields.len() - (if dtor { 1 } else { 0 })
}
General(_, ref cases, dtor) => {
cases.get(discr as uint).fields.len() - 1 - (if dtor { 1 } else { 0 })
cases[discr as uint].fields.len() - 1 - (if dtor { 1 } else { 0 })
}
RawNullablePointer { nndiscr, ref nullfields, .. } => {
if discr == nndiscr { 1 } else { nullfields.len() }
@ -827,13 +828,13 @@ pub fn trans_field_ptr(bcx: Block, r: &Repr, val: ValueRef, discr: Disr,
struct_field_ptr(bcx, st, val, ix, false)
}
General(_, ref cases, _) => {
struct_field_ptr(bcx, cases.get(discr as uint), val, ix + 1, true)
struct_field_ptr(bcx, &cases[discr as uint], val, ix + 1, true)
}
RawNullablePointer { nndiscr, ref nullfields, .. } |
StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
// The unit-like case might have a nonzero number of unit-like fields.
// (e.d., Result of Either with (), as one side.)
let ty = type_of::type_of(bcx.ccx(), *nullfields.get(ix));
let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
// The contents of memory at this pointer can't matter, but use
// the value that's "reasonable" in case of pointer comparison.
@ -965,14 +966,14 @@ pub fn trans_const(ccx: &CrateContext, r: &Repr, discr: Disr,
C_integral(ll_inttype(ccx, ity), discr as u64, true)
}
General(ity, ref cases, _) => {
let case = cases.get(discr as uint);
let case = &cases[discr as uint];
let max_sz = cases.iter().map(|x| x.size).max().unwrap();
let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
let contents = build_const_struct(ccx,
case,
(vec!(lldiscr)).append(vals).as_slice());
C_struct(ccx, contents.append([padding(ccx, max_sz - case.size)]).as_slice(),
false)
let mut f = vec![lldiscr];
f.push_all(vals);
let mut contents = build_const_struct(ccx, case, f.as_slice());
contents.push_all([padding(ccx, max_sz - case.size)]);
C_struct(ccx, contents.as_slice(), false)
}
Univariant(ref st, _dro) => {
assert!(discr == 0);

View File

@ -62,7 +62,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
}).collect::<Vec<_>>();
// Now the input operands
let inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
constraints.push((*c).clone());
let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
@ -73,7 +73,8 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
})
}).collect::<Vec<_>>().append(ext_inputs.as_slice());
}).collect::<Vec<_>>();
inputs.push_all(ext_inputs.as_slice());
// no failure occurred preparing operands, no need to cleanup
fcx.pop_custom_cleanup_scope(temp_scope);
@ -95,7 +96,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
// Add the clobbers to our constraints list
if clobbers.len() != 0 && constraints.len() != 0 {
constraints.push_char(',');
constraints.push(',');
constraints.push_str(clobbers.as_slice());
} else {
constraints.push_str(clobbers.as_slice());
@ -109,7 +110,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
let output_type = if num_outputs == 0 {
Type::void(bcx.ccx())
} else if num_outputs == 1 {
*output_types.get(0)
output_types[0]
} else {
Type::struct_(bcx.ccx(), output_types.as_slice(), false)
};
@ -134,7 +135,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
// Again, based on how many outputs we have
if num_outputs == 1 {
Store(bcx, r, *outputs.get(0));
Store(bcx, r, outputs[0]);
} else {
for (i, o) in outputs.iter().enumerate() {
let v = ExtractValue(bcx, r, i);

View File

@ -259,7 +259,7 @@ pub fn self_type_for_unboxed_closure(ccx: &CrateContext,
closure_id,
ty::ReStatic);
let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
let unboxed_closure = unboxed_closures.get(&closure_id);
let unboxed_closure = &(*unboxed_closures)[closure_id];
match unboxed_closure.kind {
ty::FnUnboxedClosureKind => {
ty::mk_imm_rptr(ccx.tcx(), ty::ReStatic, unboxed_closure_type)
@ -274,7 +274,7 @@ pub fn self_type_for_unboxed_closure(ccx: &CrateContext,
pub fn kind_for_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId)
-> ty::UnboxedClosureKind {
let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
unboxed_closures.get(&closure_id).kind
(*unboxed_closures)[closure_id].kind
}
pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
@ -287,7 +287,7 @@ pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
}
ty::ty_unboxed_closure(closure_did, _) => {
let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
let unboxed_closure = unboxed_closures.get(&closure_did);
let unboxed_closure = &(*unboxed_closures)[closure_did];
let function_type = unboxed_closure.closure_type.clone();
let self_type = self_type_for_unboxed_closure(ccx, closure_did);
let llenvironment_type = type_of_explicit_arg(ccx, self_type);
@ -771,7 +771,7 @@ pub fn iter_structural_ty<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
match adt::trans_switch(cx, &*repr, av) {
(_match::Single, None) => {
cx = iter_variant(cx, &*repr, av, &**variants.get(0),
cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
substs, f);
}
(_match::Switch, Some(lldiscrim_a)) => {
@ -2121,7 +2121,7 @@ fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span,
({} bytes) than the next largest (ignoring padding)",
largest).as_slice());
ccx.sess().span_note(enum_def.variants.get(largest_index).span,
ccx.sess().span_note(enum_def.variants[largest_index].span,
"this variant is the largest");
}
}
@ -2353,7 +2353,7 @@ pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
ty::ty_unboxed_closure(closure_did, _) => {
let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
let ref function_type = unboxed_closures.get(&closure_did)
let ref function_type = (*unboxed_closures)[closure_did]
.closure_type;
(function_type.sig.clone(), RustCall, true)
@ -2381,11 +2381,14 @@ pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
}
},
ty::ty_bare_fn(_) if abi == RustCall => {
let inputs = vec![fn_sig.inputs[0]];
let mut inputs = vec![fn_sig.inputs[0]];
match ty::get(fn_sig.inputs[1]).sty {
ty::ty_nil => inputs,
ty::ty_tup(ref t_in) => inputs.append(t_in.as_slice()),
ty::ty_tup(ref t_in) => {
inputs.push_all(t_in.as_slice());
inputs
}
_ => ccx.sess().bug("expected tuple'd inputs")
}
}
@ -2904,13 +2907,11 @@ pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
let metadata = encoder::encode_metadata(encode_parms, krate);
let compressed = Vec::from_slice(encoder::metadata_encoding_version)
.append(match flate::deflate_bytes(metadata.as_slice()) {
Some(compressed) => compressed,
None => {
cx.sess().fatal("failed to compress metadata")
}
}.as_slice());
let mut compressed = encoder::metadata_encoding_version.to_vec();
compressed.push_all(match flate::deflate_bytes(metadata.as_slice()) {
Some(compressed) => compressed,
None => cx.sess().fatal("failed to compress metadata"),
}.as_slice());
let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.as_slice());
let llconst = C_struct_in_context(cx.metadata_llcx(), [llmeta], false);
let name = format!("rust_metadata_{}_{}",

View File

@ -72,13 +72,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let mut s = String::from_str(".");
i = 0u;
while i < len {
i = *mm.get(&v[i]);
s.push_char('/');
i = mm[v[i]];
s.push('/');
s.push_str(v[i]);
i += 1u;
}
s.push_char('/');
s.push('/');
s.push_str(category);
let n = match h.find(&s) {

View File

@ -316,7 +316,7 @@ fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
tys.push(Type::i64(ccx));
}
SSEFv => {
let vec_len = llvec_len(cls.tailn(i + 1u));
let vec_len = llvec_len(cls[i + 1u..]);
let vec_ty = Type::vector(&Type::f32(ccx), (vec_len * 2u) as u64);
tys.push(vec_ty);
i += vec_len;

View File

@ -260,7 +260,7 @@ pub fn trans_unboxing_shim(bcx: Block,
let tcx = bcx.tcx();
// Transform the self type to `Box<self_type>`.
let self_type = *fty.sig.inputs.get(0);
let self_type = fty.sig.inputs[0];
let boxed_self_type = ty::mk_uniq(tcx, self_type);
let boxed_function_type = ty::FnSig {
binder_id: fty.sig.binder_id,
@ -332,9 +332,9 @@ pub fn trans_unboxing_shim(bcx: Block,
let arg_scope = fcx.push_custom_cleanup_scope();
let arg_scope_id = cleanup::CustomScope(arg_scope);
let boxed_arg_types = ty::ty_fn_args(boxed_function_type);
let boxed_self_type = *boxed_arg_types.get(0);
let boxed_self_type = boxed_arg_types[0];
let arg_types = ty::ty_fn_args(function_type);
let self_type = *arg_types.get(0);
let self_type = arg_types[0];
let boxed_self_kind = arg_kind(&fcx, boxed_self_type);
// Create a datum for self.
@ -541,7 +541,7 @@ pub fn trans_fn_ref_with_substs(
let ref_ty = match node {
ExprId(id) => node_id_type(bcx, id),
MethodCall(method_call) => {
let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
let t = (*bcx.tcx().method_map.borrow())[method_call].ty;
monomorphize_type(bcx, t)
}
};
@ -628,7 +628,7 @@ pub fn trans_method_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
let _icx = push_ctxt("trans_method_call");
debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
let method_call = MethodCall::expr(call_ex.id);
let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty;
trans_call_inner(
bcx,
Some(common::expr_info(call_ex)),
@ -915,7 +915,7 @@ fn trans_args_under_call_abi<'blk, 'tcx>(
let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx,
*arg_tys.get(0),
arg_tys[0],
arg_datum,
arg_cleanup_scope,
DontAutorefArg)
@ -940,7 +940,7 @@ fn trans_args_under_call_abi<'blk, 'tcx>(
for i in range(0, field_types.len()) {
let arg_datum = tuple_lvalue_datum.get_element(
bcx,
*field_types.get(i),
field_types[i],
|srcval| {
adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
});
@ -976,7 +976,7 @@ fn trans_overloaded_call_args<'blk, 'tcx>(
let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx,
*arg_tys.get(0),
arg_tys[0],
arg_datum,
arg_cleanup_scope,
DontAutorefArg)
@ -984,7 +984,7 @@ fn trans_overloaded_call_args<'blk, 'tcx>(
}
// Now untuple the rest of the arguments.
let tuple_type = *arg_tys.get(1);
let tuple_type = arg_tys[1];
match ty::get(tuple_type).sty {
ty::ty_tup(ref field_types) => {
for (i, &field_type) in field_types.iter().enumerate() {
@ -1050,7 +1050,7 @@ pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
assert!(variadic);
expr_ty_adjusted(cx, &**arg_expr)
} else {
*arg_tys.get(i)
arg_tys[i]
};
let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
@ -1073,15 +1073,15 @@ pub fn trans_args<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
assert!(!variadic);
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx, *arg_tys.get(0), lhs,
trans_arg_datum(bcx, arg_tys[0], lhs,
arg_cleanup_scope,
DontAutorefArg)
}));
assert_eq!(arg_tys.len(), 1 + rhs.len());
for (rhs, rhs_id) in rhs.move_iter() {
for (rhs, rhs_id) in rhs.into_iter() {
llargs.push(unpack_result!(bcx, {
trans_arg_datum(bcx, *arg_tys.get(1), rhs,
trans_arg_datum(bcx, arg_tys[1], rhs,
arg_cleanup_scope,
DoAutorefArg(rhs_id))
}));

View File

@ -549,7 +549,7 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx
fn is_valid_custom_scope(&self, custom_scope: CustomScopeIndex) -> bool {
let scopes = self.scopes.borrow();
custom_scope.index < scopes.len() &&
scopes.get(custom_scope.index).kind.is_temp()
(*scopes)[custom_scope.index].kind.is_temp()
}
fn trans_scope_cleanups(&self, // cannot borrow self, will recurse

View File

@ -473,7 +473,7 @@ pub fn trans_unboxed_closure<'blk, 'tcx>(
closure_id).unwrap();
let unboxed_closures = bcx.tcx().unboxed_closures.borrow();
let function_type = unboxed_closures.get(&closure_id)
let function_type = (*unboxed_closures)[closure_id]
.closure_type
.clone();
let function_type = ty::mk_closure(bcx.tcx(), function_type);

Some files were not shown because too many files have changed in this diff Show More