diff --git a/mk/crates.mk b/mk/crates.mk index fd41666275b..00c00b3d359 100644 --- a/mk/crates.mk +++ b/mk/crates.mk @@ -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 diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 088784070e7..e751084addd 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -475,12 +475,6 @@ impl DList { 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 DList { } } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> MoveItems { - self.into_iter() - } - /// Consumes the list into an iterator yielding elements by value. #[inline] pub fn into_iter(self) -> MoveItems { @@ -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)) diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 40c5f184fbb..e1806dae31d 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -502,40 +502,6 @@ pub trait Deque : MutableSeq { /// ``` 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 { self.pop() } - /// Removes the first element and returns it, or `None` if the sequence is /// empty. /// diff --git a/src/libcollections/priority_queue.rs b/src/libcollections/priority_queue.rs index 68e2086d042..16e04b93777 100644 --- a/src/libcollections/priority_queue.rs +++ b/src/libcollections/priority_queue.rs @@ -269,9 +269,6 @@ impl PriorityQueue { 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 PriorityQueue { } } - #[deprecated="renamed to `pop`"] - pub fn maybe_pop(&mut self) -> Option { self.pop() } - /// Pushes an item onto the queue. /// /// # Example @@ -417,14 +411,6 @@ impl PriorityQueue { } } - #[allow(dead_code)] - #[deprecated="renamed to `into_vec`"] - fn to_vec(self) -> Vec { self.into_vec() } - - #[allow(dead_code)] - #[deprecated="renamed to `into_sorted_vec`"] - fn to_sorted_vec(self) -> Vec { self.into_sorted_vec() } - /// Consumes the `PriorityQueue` and returns the underlying vector /// in arbitrary order. /// diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs index 1ae63d11fbe..e32e8145d17 100644 --- a/src/libcollections/ringbuf.rs +++ b/src/libcollections/ringbuf.rs @@ -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 RingBuf { 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 RingBuf { 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 RingBuf { // 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], - remaining2: &'a mut [Option], + remaining1: slice::MutItems<'a, Option>, + remaining2: slice::MutItems<'a, Option>, 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> Hash for RingBuf { impl Index for RingBuf { #[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)] diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 049bc231be3..d061e60a422 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -270,23 +270,6 @@ impl Iterator> for Permutations { pub trait CloneableVector { /// Copies `self` into a new `Vec`. fn to_vec(&self) -> Vec; - - /// Deprecated. Use `to_vec`. - #[deprecated = "Replaced by `to_vec`"] - fn to_owned(&self) -> Vec { - 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; - - /// Deprecated. Use `to_vec` - #[deprecated = "Replaced by `to_vec`"] - fn into_owned(self) -> Vec { - self.to_vec() - } } impl<'a, T: Clone> CloneableVector for &'a [T] { @@ -297,9 +280,6 @@ impl<'a, T: Clone> CloneableVector for &'a [T] { vector.push_all(*self); vector } - - #[inline(always)] - fn into_vec(self) -> Vec { 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 = 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 = 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]; diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/smallintmap.rs index 94dbf84a4b4..498f86a8bf1 100644 --- a/src/libcollections/smallintmap.rs +++ b/src/libcollections/smallintmap.rs @@ -199,29 +199,6 @@ impl SmallIntMap { 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 SmallIntMap { } } - /// 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 SmallIntMap { } } - /// Deprecated: use `into_iter` instead. - #[deprecated = "use into_iter"] - pub fn move_iter(&mut self) - -> FilterMap<(uint, Option), (uint, V), - Enumerate>>> { - 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 Extendable<(uint, V)> for SmallIntMap { impl Index for SmallIntMap { #[inline] - #[allow(deprecated)] fn index<'a>(&'a self, i: &uint) -> &'a V { - self.get(i) + self.find(i).expect("key not present") } } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index f49371b8e88..901f8add73c 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -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) -> Result> { - 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::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) -> 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 { - self.as_slice().utf16_units().collect::>() - } - /// Given a string, makes a new string with repeated copies of it. fn repeat(&self, nn: uint) -> String { let me = self.as_slice(); diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 061064ff803..fa45dee7cde 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -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 { - 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 { 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 { - self.vec.remove(0) - } - - /// Deprecated, call `remove(0)` instead - #[deprecated = "call .remove(0) instead"] - pub fn shift_char(&mut self) -> Option { - 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"); diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs index a86e7386edd..39362bf1fdc 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/treemap.rs @@ -361,12 +361,6 @@ impl TreeMap { 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 TreeMap { } } - /// 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 TreeMap { RevMutEntries{iter: self.iter_mut()} } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> MoveEntries { - self.into_iter() - } - /// Gets a lazy iterator that consumes the treemap. /// /// # Example @@ -494,12 +476,6 @@ impl TreeMap { 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 TreeMap { } } - /// 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 TreeMap { 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 TreeSet { RevSetItems{iter: self.map.rev_iter()} } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> MoveSetItems { - 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. /// diff --git a/src/libcollections/trie.rs b/src/libcollections/trie.rs index 2e388a92a59..1b5c5dbc0a2 100644 --- a/src/libcollections/trie.rs +++ b/src/libcollections/trie.rs @@ -268,12 +268,6 @@ impl TrieMap { 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 TrieMap { 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 TrieMap { 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. /// diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 0bfdcee7f76..e608a7d22dc 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -275,19 +275,6 @@ impl Vec { } impl Vec { - /// Deprecated, call `extend` instead. - #[inline] - #[deprecated = "this function has been deprecated in favor of extend()"] - pub fn append(mut self, second: &[T]) -> Vec { - 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 { values.to_vec() } - /// Constructs a `Vec` with copies of a value. /// /// Creates a `Vec` with `length` copies of `value`. @@ -366,31 +353,6 @@ impl Vec { } } - /// 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 Clone for Vec { #[experimental = "waiting on Index stability"] impl Index for Vec { #[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 Vec { } } - /// Deprecated, call `push` instead - #[inline] - #[deprecated = "call .push() instead"] - pub fn append_one(mut self, x: T) -> Vec { - 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 Vec { } } + /// Deprecated, use `.extend(other.into_iter())` + #[inline] + #[deprecated = "use .extend(other.into_iter())"] + #[cfg(stage0)] + pub fn push_all_move(&mut self, other: Vec) { + self.extend(other.into_iter()); + } + /// Returns a mutable slice of the elements of `self`. /// /// # Example @@ -775,12 +736,6 @@ impl Vec { } } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> MoveItems { - 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 Vec { 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 Vec { 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 Vec { 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 Vec { 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 Vec { 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 { - 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 Vec { } } - /// 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) { - 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 Vec { 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 Vec { 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 Vec { 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 diff --git a/src/libcore/any.rs b/src/libcore/any.rs index c4b07d42e69..021f575b0ac 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -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(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(self) -> Option<&'a T> { - self.downcast_ref::() - } } #[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(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(self) -> Option<&'a mut T> { - self.downcast_mut::() - } } #[stable] diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 9542b28e981..505dc183480 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -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, diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index 4b970dc3d25..e2a4fdfe79b 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -428,27 +428,6 @@ pub trait Iterator { 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`. /// diff --git a/src/libcore/kinds.rs b/src/libcore/kinds.rs index b0206e73e47..677bc91d9dd 100644 --- a/src/libcore/kinds.rs +++ b/src/libcore/kinds.rs @@ -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? { diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 8134f521024..62a4fbd2e08 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -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; diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 947fa2ec92e..97b3554b1e1 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -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(_val: &T) -> uint { size_of::() } -/// Deprecated, this function will be removed soon -#[inline] -#[deprecated = "this function will be removed soon"] -pub fn nonzero_size_of() -> uint { - match size_of::() { - 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(val: &T) -> uint { - match size_of_val::(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(_val: &T) -> uint { align_of::() } -/// Deprecated, this function has been renamed to align_of -#[inline] -#[deprecated = "use mem::align_of instead"] -pub fn pref_align_of() -> uint { align_of::() } - -/// Deprecated, this function has been renamed to align_of_val -#[inline] -#[deprecated = "use mem::align_of_val instead"] -pub fn pref_align_of_val(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 { intrinsics::init() } -/// Deprecated, use zeroed() instead -#[inline] -#[deprecated = "this function has been renamed to zeroed()"] -pub unsafe fn init() -> 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 { intrinsics::uninit() } -/// Deprecated, use `uninitialized` instead. -#[inline] -#[deprecated = "this function has been renamed to `uninitialized`"] -pub unsafe fn uninit() -> 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(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(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] diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 9b66f900d9c..5b34cab611a 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -482,33 +482,6 @@ impl Option { } } - /// 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 Option { 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 Option { Item{opt: self.as_mut()} } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> Item { - self.into_iter() - } - /// Returns a consuming iterator over the possibly contained value. /// /// # Example @@ -713,100 +674,6 @@ impl Option { pub fn take(&mut self) -> Option { 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 { - 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) { - 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 Option { @@ -908,13 +775,6 @@ impl ExactSize for Item {} // Free functions ///////////////////////////////////////////////////////////////////////////// -/// Deprecated: use `Iterator::collect` instead. -#[inline] -#[deprecated = "use Iterator::collect instead"] -pub fn collect>, V: FromIterator>(mut iter: Iter) -> Option { - iter.collect() -} - impl> FromIterator> for Option { /// 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 diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index b76c92140fd..f0cd8402b14 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -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() -> *const T { 0 as *const T } -/// Deprecated: use `null_mut`. -#[deprecated = "use null_mut"] -pub fn mut_null() -> *mut T { null_mut() } - /// Create an unsafe mutable null pointer. /// /// # Example @@ -203,59 +198,6 @@ pub unsafe fn write(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(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(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(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(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 { /// Returns the null pointer. @@ -280,12 +222,6 @@ pub trait RawPtr { /// 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::()` bytes. diff --git a/src/libcore/result.rs b/src/libcore/result.rs index caede952e2f..27bb649d1d9 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -566,12 +566,6 @@ impl Result { 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 Result { Item{opt: self.as_mut().ok()} } - /// Deprecated: `use into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> Item { - self.into_iter() - } - /// Returns a consuming iterator over the possibly contained value. /// /// # Example @@ -771,13 +759,6 @@ impl Result { 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 Result { @@ -902,14 +883,6 @@ impl ExactSize for Item {} // Free functions ///////////////////////////////////////////////////////////////////////////// -/// Deprecated: use `Iterator::collect`. -#[inline] -#[deprecated = "use Iterator::collect instead"] -pub fn collect>, V: FromIterator>(mut iter: Iter) - -> Result { - iter.collect() -} - impl> FromIterator> for Result { /// 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>>(iterator: Iter) -> Result<(),E> { - fold(iterator, (), |_, _| ()) -} diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 5847a6177d7..6b24592b17f 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -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; - /// 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 { - 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 = 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 = 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>; - /// 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 = 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 = 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 for &'a [T] { /// Extension methods for slices containing `Ord` elements. #[unstable = "may merge with other traits"] pub trait ImmutableOrdSlice { - /// Deprecated: use `binary_search_elem`. - #[deprecated = "use binary_search_elem"] - fn bsearch_elem(&self, x: &T) -> Option; - /// 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 { #[unstable = "trait is unstable"] impl<'a, T: Ord> ImmutableOrdSlice for &'a [T] { - #[deprecated = "use binary_search_elem"] - #[allow(deprecated)] - fn bsearch_elem(&self, x: &T) -> Option { - 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 for &'a [T] { /// Trait for &[T] where T is Cloneable #[unstable = "may merge with other traits"] pub trait MutableCloneableSlice { - /// 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); + } } } diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs index 4ac3f7e9310..59ce73fe40d 100644 --- a/src/libcoretest/cmp.rs +++ b/src/libcoretest/cmp.rs @@ -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; diff --git a/src/libcoretest/option.rs b/src/libcoretest/option.rs index 3f150b3d136..71e9270fe4b 100644 --- a/src/libcoretest/option.rs +++ b/src/libcoretest/option.rs @@ -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> = collect(range(0i, 0) - .map(|_| Some(0i))); + let v: Option> = range(0i, 0).map(|_| Some(0i)).collect(); assert!(v == Some(vec![])); - let v: Option> = collect(range(0i, 3) - .map(|x| Some(x))); + let v: Option> = range(0i, 3).map(|x| Some(x)).collect(); assert!(v == Some(vec![0, 1, 2])); - let v: Option> = collect(range(0i, 3) - .map(|x| if x > 1 { None } else { Some(x) })); + let v: Option> = 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> = collect(functions.iter_mut().map(|f| (*f)())); + let v: Option> = functions.iter_mut().map(|f| (*f)()).collect(); assert!(v == None); } diff --git a/src/libcoretest/ptr.rs b/src/libcoretest/ptr.rs index 754391a284d..db3580e5d0c 100644 --- a/src/libcoretest/ptr.rs +++ b/src/libcoretest/ptr.rs @@ -7,12 +7,9 @@ // , 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]; diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index b023833f394..1cb72bd9eac 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -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 { Ok(666) } @@ -69,47 +68,25 @@ pub fn test_impl_map_err() { } #[test] -#[allow(deprecated)] fn test_collect() { - let v: Result, ()> = collect(range(0i, 0).map(|_| Ok::(0))); + let v: Result, ()> = range(0i, 0).map(|_| Ok::(0)).collect(); assert!(v == Ok(vec![])); - let v: Result, ()> = collect(range(0i, 3).map(|x| Ok::(x))); + let v: Result, ()> = range(0i, 3).map(|x| Ok::(x)).collect(); assert!(v == Ok(vec![0, 1, 2])); - let v: Result, int> = collect(range(0i, 3) - .map(|x| if x > 1 { Err(x) } else { Ok(x) })); + let v: Result, 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, int> = collect(functions.iter_mut().map(|f| (*f)())); + let v: Result, 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::(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 = Ok(100); diff --git a/src/libfourcc/lib.rs b/src/libfourcc/lib.rs deleted file mode 100644 index ffa72e6d795..00000000000 --- a/src/libfourcc/lib.rs +++ /dev/null @@ -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 or the MIT license -// , 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 { - 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, Option) { - 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() { } diff --git a/src/libglob/lib.rs b/src/libglob/lib.rs deleted file mode 100644 index 0313c22933c..00000000000 --- a/src/libglob/lib.rs +++ /dev/null @@ -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 or the MIT license -// , 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, - 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::>(); - 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 for Paths { - - fn next(&mut self) -> Option { - 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> { - 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, -} - -#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -enum PatternToken { - Char(char), - AnyChar, - AnySequence, - AnyWithin(Vec ), - AnyExcept(Vec ) -} - -#[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::>(); - 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, - 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 { - 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 { - 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"))); - } -} diff --git a/src/libgraphviz/maybe_owned_vec.rs b/src/libgraphviz/maybe_owned_vec.rs index f67a9c2c84c..c7659dc1b9f 100644 --- a/src/libgraphviz/maybe_owned_vec.rs +++ b/src/libgraphviz/maybe_owned_vec.rs @@ -127,14 +127,6 @@ impl<'a,T:Clone> CloneableVector for MaybeOwnedVector<'a,T> { fn to_vec(&self) -> Vec { self.as_slice().to_vec() } - - /// Convert `self` into an owned slice, not making a copy if possible. - fn into_vec(self) -> Vec { - match self { - Growable(v) => v.as_slice().to_vec(), - Borrowed(v) => v.to_vec(), - } - } } impl<'a, T: Clone> Clone for MaybeOwnedVector<'a, T> { diff --git a/src/libgreen/basic.rs b/src/libgreen/basic.rs index 4bb4eeb4950..b592ba477c2 100644 --- a/src/libgreen/basic.rs +++ b/src/libgreen/basic.rs @@ -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) } } diff --git a/src/libgreen/sched.rs b/src/libgreen/sched.rs index f46d96ffe4a..6ba29cf5a3d 100644 --- a/src/libgreen/sched.rs +++ b/src/libgreen/sched.rs @@ -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 = 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::); match task.maybe_take_runtime::() { 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 diff --git a/src/libgreen/task.rs b/src/libgreen/task.rs index 3b751a5a28d..b6bd8c3cec4 100644 --- a/src/libgreen/task.rs +++ b/src/libgreen/task.rs @@ -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) { 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> { - 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, } diff --git a/src/libhexfloat/lib.rs b/src/libhexfloat/lib.rs deleted file mode 100644 index 8335cc16d64..00000000000 --- a/src/libhexfloat/lib.rs +++ /dev/null @@ -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 or the MIT license -// , 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 { - 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, Option) { - 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() { } diff --git a/src/libnative/io/addrinfo.rs b/src/libnative/io/addrinfo.rs index 7a07b622127..d40438e4272 100644 --- a/src/libnative/io/addrinfo.rs +++ b/src/libnative/io/addrinfo.rs @@ -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 { diff --git a/src/libnative/io/c_windows.rs b/src/libnative/io/c_windows.rs index 067a31166a5..eed3df28b8f 100644 --- a/src/libnative/io/c_windows.rs +++ b/src/libnative/io/c_windows.rs @@ -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 = module.utf16_units().collect(); - let module = module.append_one(0); + let mut module: Vec = 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)); diff --git a/src/libnative/io/file_windows.rs b/src/libnative/io/file_windows.rs index 6aa965948fd..eb4d4f22132 100644 --- a/src/libnative/io/file_windows.rs +++ b/src/libnative/io/file_windows.rs @@ -253,7 +253,11 @@ impl Drop for Inner { pub fn to_utf16(s: &CString) -> IoResult> { match s.as_str() { - Some(s) => Ok(s.utf16_units().collect::>().append_one(0)), + Some(s) => Ok({ + let mut s = s.utf16_units().collect::>(); + s.push(0); + s + }), None => Err(IoError { code: libc::ERROR_INVALID_NAME as uint, extra: 0, diff --git a/src/libnative/io/helper_thread.rs b/src/libnative/io/helper_thread.rs index 8aff1732a41..d1368ad31f4 100644 --- a/src/libnative/io/helper_thread.rs +++ b/src/libnative/io/helper_thread.rs @@ -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 Helper { *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() diff --git a/src/libnative/io/pipe_windows.rs b/src/libnative/io/pipe_windows.rs index 5475de6d7e1..bc08ede39f7 100644 --- a/src/libnative/io/pipe_windows.rs +++ b/src/libnative/io/pipe_windows.rs @@ -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; diff --git a/src/libnative/io/process.rs b/src/libnative/io/process.rs index 2ca25f1eeb9..d69042175f7 100644 --- a/src/libnative/io/process.rs +++ b/src/libnative/io/process.rs @@ -350,8 +350,8 @@ fn spawn_process_os(cfg: ProcessConfig, lpSecurityDescriptor: ptr::null_mut(), bInheritHandle: 1, }; - let filename: Vec = "NUL".utf16_units().collect(); - let filename = filename.append_one(0); + let mut filename: Vec = "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 = 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 = 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, 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, 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(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 = dir_str.utf16_units().collect(); - let dir_str = dir_str.append_one(0); - + let mut dir_str: Vec = dir_str.utf16_units().collect(); + dir_str.push(0); cb(dir_str.as_ptr()) }, None => cb(ptr::null()) diff --git a/src/libnative/io/timer_unix.rs b/src/libnative/io/timer_unix.rs index 4d4ba33aec4..6f57a5e88ba 100644 --- a/src/libnative/io/timer_unix.rs +++ b/src/libnative/io/timer_unix.rs @@ -115,7 +115,7 @@ fn helper(input: libc::c_int, messages: Receiver, _: ()) { // signals the first requests in the queue, possible re-enqueueing it. fn signal(active: &mut Vec>, dead: &mut Vec<(uint, Box)>) { - 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, _: ()) { 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, _: ()) { // 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 diff --git a/src/libnative/io/tty_windows.rs b/src/libnative/io/tty_windows.rs index 1c3904a8943..cf2a0f9dda4 100644 --- a/src/libnative/io/tty_windows.rs +++ b/src/libnative/io/tty_windows.rs @@ -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::>() + } None => return Err(invalid_encoding()), }; let mut num: DWORD = 0; diff --git a/src/libnative/lib.rs b/src/libnative/lib.rs index 71a1645f9ff..656c7e4103c 100644 --- a/src/libnative/lib.rs +++ b/src/libnative/lib.rs @@ -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)] diff --git a/src/libnative/task.rs b/src/libnative/task.rs index ba3f101720f..d90535428da 100644 --- a/src/libnative/task.rs +++ b/src/libnative/task.rs @@ -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 { } } -/// 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> { @@ -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 = Local::take(); match task.maybe_take_runtime::() { diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs deleted file mode 100644 index e52d62a040b..00000000000 --- a/src/libnum/bigint.rs +++ /dev/null @@ -1,2961 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! A Big integer (signed version: `BigInt`, unsigned version: `BigUint`). -//! -//! A `BigUint` is represented as an array of `BigDigit`s. -//! A `BigInt` is a combination of `BigUint` and `Sign`. -//! -//! Common numerical operations are overloaded, so we can treat them -//! the same way we treat other numbers. -//! -//! ## Example -//! -//! ```rust -//! # #![allow(deprecated)] -//! use num::bigint::BigUint; -//! use std::num::{Zero, One}; -//! use std::mem::replace; -//! -//! // Calculate large fibonacci numbers. -//! fn fib(n: uint) -> BigUint { -//! let mut f0: BigUint = Zero::zero(); -//! let mut f1: BigUint = One::one(); -//! for _ in range(0, n) { -//! let f2 = f0 + f1; -//! // This is a low cost way of swapping f0 with f1 and f1 with f2. -//! f0 = replace(&mut f1, f2); -//! } -//! f0 -//! } -//! -//! // This is a very large number. -//! println!("fib(1000) = {}", fib(1000)); -//! ``` -//! -//! It's easy to generate large random numbers: -//! -//! ```rust -//! # #![allow(deprecated)] -//! use num::bigint::{ToBigInt, RandBigInt}; -//! use std::rand; -//! -//! let mut rng = rand::task_rng(); -//! let a = rng.gen_bigint(1000u); -//! -//! let low = -10000i.to_bigint().unwrap(); -//! let high = 10000i.to_bigint().unwrap(); -//! let b = rng.gen_bigint_range(&low, &high); -//! -//! // Probably an even larger number. -//! println!("{}", a * b); -//! ``` - -use Integer; -use rand::Rng; - -use std::{cmp, fmt, hash}; -use std::default::Default; -use std::from_str::FromStr; -use std::num::CheckedDiv; -use std::num::{ToPrimitive, FromPrimitive}; -use std::num::{Zero, One, ToStrRadix, FromStrRadix}; -use std::string::String; -use std::{uint, i64, u64}; - -/// A `BigDigit` is a `BigUint`'s composing element. -pub type BigDigit = u32; - -/// A `DoubleBigDigit` is the internal type used to do the computations. Its -/// size is the double of the size of `BigDigit`. -pub type DoubleBigDigit = u64; - -pub const ZERO_BIG_DIGIT: BigDigit = 0; -static ZERO_VEC: [BigDigit, ..1] = [ZERO_BIG_DIGIT]; - -#[allow(non_snake_case)] -pub mod BigDigit { - use super::BigDigit; - use super::DoubleBigDigit; - - // `DoubleBigDigit` size dependent - #[allow(non_uppercase_statics)] - pub const bits: uint = 32; - - #[allow(non_uppercase_statics)] - pub const base: DoubleBigDigit = 1 << bits; - #[allow(non_uppercase_statics)] - static lo_mask: DoubleBigDigit = (-1 as DoubleBigDigit) >> bits; - - #[inline] - fn get_hi(n: DoubleBigDigit) -> BigDigit { (n >> bits) as BigDigit } - #[inline] - fn get_lo(n: DoubleBigDigit) -> BigDigit { (n & lo_mask) as BigDigit } - - /// Split one `DoubleBigDigit` into two `BigDigit`s. - #[inline] - pub fn from_doublebigdigit(n: DoubleBigDigit) -> (BigDigit, BigDigit) { - (get_hi(n), get_lo(n)) - } - - /// Join two `BigDigit`s into one `DoubleBigDigit` - #[inline] - pub fn to_doublebigdigit(hi: BigDigit, lo: BigDigit) -> DoubleBigDigit { - (lo as DoubleBigDigit) | ((hi as DoubleBigDigit) << bits) - } -} - -/// A big unsigned integer type. -/// -/// A `BigUint`-typed value `BigUint { data: vec!(a, b, c) }` represents a number -/// `(a + b * BigDigit::base + c * BigDigit::base^2)`. -#[deriving(Clone)] -pub struct BigUint { - data: Vec -} - -impl PartialEq for BigUint { - #[inline] - fn eq(&self, other: &BigUint) -> bool { - match self.cmp(other) { Equal => true, _ => false } - } -} -impl Eq for BigUint {} - -impl PartialOrd for BigUint { - #[inline] - fn partial_cmp(&self, other: &BigUint) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for BigUint { - #[inline] - fn cmp(&self, other: &BigUint) -> Ordering { - let (s_len, o_len) = (self.data.len(), other.data.len()); - if s_len < o_len { return Less; } - if s_len > o_len { return Greater; } - - for (&self_i, &other_i) in self.data.iter().rev().zip(other.data.iter().rev()) { - if self_i < other_i { return Less; } - if self_i > other_i { return Greater; } - } - return Equal; - } -} - -impl Default for BigUint { - #[inline] - fn default() -> BigUint { Zero::zero() } -} - -impl hash::Hash for BigUint { - fn hash(&self, state: &mut S) { - // hash 0 in case it's all 0's - 0u32.hash(state); - - let mut found_first_value = false; - for elem in self.data.iter().rev() { - // don't hash any leading 0's, they shouldn't affect the hash - if found_first_value || *elem != 0 { - found_first_value = true; - elem.hash(state); - } - } - } -} - -impl fmt::Show for BigUint { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_str_radix(10)) - } -} - -impl FromStr for BigUint { - #[inline] - fn from_str(s: &str) -> Option { - FromStrRadix::from_str_radix(s, 10) - } -} - -impl Num for BigUint {} - -impl BitAnd for BigUint { - fn bitand(&self, other: &BigUint) -> BigUint { - BigUint::new(self.data.iter().zip(other.data.iter()).map(|(ai, bi)| *ai & *bi).collect()) - } -} - -impl BitOr for BigUint { - fn bitor(&self, other: &BigUint) -> BigUint { - let zeros = ZERO_VEC.iter().cycle(); - let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) }; - let ored = a.data.iter().zip(b.data.iter().chain(zeros)).map( - |(ai, bi)| *ai | *bi - ).collect(); - return BigUint::new(ored); - } -} - -impl BitXor for BigUint { - fn bitxor(&self, other: &BigUint) -> BigUint { - let zeros = ZERO_VEC.iter().cycle(); - let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) }; - let xored = a.data.iter().zip(b.data.iter().chain(zeros)).map( - |(ai, bi)| *ai ^ *bi - ).collect(); - return BigUint::new(xored); - } -} - -impl Shl for BigUint { - #[inline] - fn shl(&self, rhs: &uint) -> BigUint { - let n_unit = *rhs / BigDigit::bits; - let n_bits = *rhs % BigDigit::bits; - return self.shl_unit(n_unit).shl_bits(n_bits); - } -} - -impl Shr for BigUint { - #[inline] - fn shr(&self, rhs: &uint) -> BigUint { - let n_unit = *rhs / BigDigit::bits; - let n_bits = *rhs % BigDigit::bits; - return self.shr_unit(n_unit).shr_bits(n_bits); - } -} - -impl Zero for BigUint { - #[inline] - fn zero() -> BigUint { BigUint::new(Vec::new()) } - - #[inline] - fn is_zero(&self) -> bool { self.data.is_empty() } -} - -impl One for BigUint { - #[inline] - fn one() -> BigUint { BigUint::new(vec!(1)) } -} - -impl Unsigned for BigUint {} - -impl Add for BigUint { - fn add(&self, other: &BigUint) -> BigUint { - let zeros = ZERO_VEC.iter().cycle(); - let (a, b) = if self.data.len() > other.data.len() { (self, other) } else { (other, self) }; - - let mut carry = 0; - let mut sum: Vec = a.data.iter().zip(b.data.iter().chain(zeros)).map(|(ai, bi)| { - let (hi, lo) = BigDigit::from_doublebigdigit( - (*ai as DoubleBigDigit) + (*bi as DoubleBigDigit) + (carry as DoubleBigDigit)); - carry = hi; - lo - }).collect(); - if carry != 0 { sum.push(carry); } - return BigUint::new(sum); - } -} - -impl Sub for BigUint { - fn sub(&self, other: &BigUint) -> BigUint { - let new_len = cmp::max(self.data.len(), other.data.len()); - let zeros = ZERO_VEC.iter().cycle(); - let (a, b) = (self.data.iter().chain(zeros.clone()), other.data.iter().chain(zeros)); - - let mut borrow = 0i; - let diff: Vec = a.take(new_len).zip(b).map(|(ai, bi)| { - let (hi, lo) = BigDigit::from_doublebigdigit( - BigDigit::base - + (*ai as DoubleBigDigit) - - (*bi as DoubleBigDigit) - - (borrow as DoubleBigDigit) - ); - /* - hi * (base) + lo == 1*(base) + ai - bi - borrow - => ai - bi - borrow < 0 <=> hi == 0 - */ - borrow = if hi == 0 { 1 } else { 0 }; - lo - }).collect(); - - assert!(borrow == 0, - "Cannot subtract other from self because other is larger than self."); - return BigUint::new(diff); - } -} - -impl Mul for BigUint { - fn mul(&self, other: &BigUint) -> BigUint { - if self.is_zero() || other.is_zero() { return Zero::zero(); } - - let (s_len, o_len) = (self.data.len(), other.data.len()); - if s_len == 1 { return mul_digit(other, self.data.as_slice()[0]); } - if o_len == 1 { return mul_digit(self, other.data.as_slice()[0]); } - - // Using Karatsuba multiplication - // (a1 * base + a0) * (b1 * base + b0) - // = a1*b1 * base^2 + - // (a1*b1 + a0*b0 - (a1-b0)*(b1-a0)) * base + - // a0*b0 - let half_len = cmp::max(s_len, o_len) / 2; - let (s_hi, s_lo) = cut_at(self, half_len); - let (o_hi, o_lo) = cut_at(other, half_len); - - let ll = s_lo * o_lo; - let hh = s_hi * o_hi; - let mm = { - let (s1, n1) = sub_sign(s_hi, s_lo); - let (s2, n2) = sub_sign(o_hi, o_lo); - match (s1, s2) { - (Equal, _) | (_, Equal) => hh + ll, - (Less, Greater) | (Greater, Less) => hh + ll + (n1 * n2), - (Less, Less) | (Greater, Greater) => hh + ll - (n1 * n2) - } - }; - - return ll + mm.shl_unit(half_len) + hh.shl_unit(half_len * 2); - - - fn mul_digit(a: &BigUint, n: BigDigit) -> BigUint { - if n == 0 { return Zero::zero(); } - if n == 1 { return (*a).clone(); } - - let mut carry = 0; - let mut prod: Vec = a.data.iter().map(|ai| { - let (hi, lo) = BigDigit::from_doublebigdigit( - (*ai as DoubleBigDigit) * (n as DoubleBigDigit) + (carry as DoubleBigDigit) - ); - carry = hi; - lo - }).collect(); - if carry != 0 { prod.push(carry); } - return BigUint::new(prod); - } - - #[inline] - fn cut_at(a: &BigUint, n: uint) -> (BigUint, BigUint) { - let mid = cmp::min(a.data.len(), n); - return (BigUint::from_slice(a.data.slice(mid, a.data.len())), - BigUint::from_slice(a.data.slice(0, mid))); - } - - #[inline] - fn sub_sign(a: BigUint, b: BigUint) -> (Ordering, BigUint) { - match a.cmp(&b) { - Less => (Less, b - a), - Greater => (Greater, a - b), - _ => (Equal, Zero::zero()) - } - } - } -} - -impl Div for BigUint { - #[inline] - fn div(&self, other: &BigUint) -> BigUint { - let (q, _) = self.div_rem(other); - return q; - } -} - -impl Rem for BigUint { - #[inline] - fn rem(&self, other: &BigUint) -> BigUint { - let (_, r) = self.div_rem(other); - return r; - } -} - -impl Neg for BigUint { - #[inline] - fn neg(&self) -> BigUint { fail!() } -} - -impl CheckedAdd for BigUint { - #[inline] - fn checked_add(&self, v: &BigUint) -> Option { - return Some(self.add(v)); - } -} - -impl CheckedSub for BigUint { - #[inline] - fn checked_sub(&self, v: &BigUint) -> Option { - if *self < *v { - return None; - } - return Some(self.sub(v)); - } -} - -impl CheckedMul for BigUint { - #[inline] - fn checked_mul(&self, v: &BigUint) -> Option { - return Some(self.mul(v)); - } -} - -impl CheckedDiv for BigUint { - #[inline] - fn checked_div(&self, v: &BigUint) -> Option { - if v.is_zero() { - return None; - } - return Some(self.div(v)); - } -} - -impl Integer for BigUint { - #[inline] - fn div_rem(&self, other: &BigUint) -> (BigUint, BigUint) { - self.div_mod_floor(other) - } - - #[inline] - fn div_floor(&self, other: &BigUint) -> BigUint { - let (d, _) = self.div_mod_floor(other); - return d; - } - - #[inline] - fn mod_floor(&self, other: &BigUint) -> BigUint { - let (_, m) = self.div_mod_floor(other); - return m; - } - - fn div_mod_floor(&self, other: &BigUint) -> (BigUint, BigUint) { - if other.is_zero() { fail!() } - if self.is_zero() { return (Zero::zero(), Zero::zero()); } - if *other == One::one() { return ((*self).clone(), Zero::zero()); } - - match self.cmp(other) { - Less => return (Zero::zero(), (*self).clone()), - Equal => return (One::one(), Zero::zero()), - Greater => {} // Do nothing - } - - let mut shift = 0; - let mut n = *other.data.last().unwrap(); - while n < (1 << BigDigit::bits - 2) { - n <<= 1; - shift += 1; - } - assert!(shift < BigDigit::bits); - let (d, m) = div_mod_floor_inner(self << shift, other << shift); - return (d, m >> shift); - - - fn div_mod_floor_inner(a: BigUint, b: BigUint) -> (BigUint, BigUint) { - let mut m = a; - let mut d: BigUint = Zero::zero(); - let mut n = 1; - while m >= b { - let (d0, d_unit, b_unit) = div_estimate(&m, &b, n); - let mut d0 = d0; - let mut prod = b * d0; - while prod > m { - // FIXME(#5992): assignment operator overloads - // d0 -= d_unit - d0 = d0 - d_unit; - // FIXME(#5992): assignment operator overloads - // prod -= b_unit; - prod = prod - b_unit - } - if d0.is_zero() { - n = 2; - continue; - } - n = 1; - // FIXME(#5992): assignment operator overloads - // d += d0; - d = d + d0; - // FIXME(#5992): assignment operator overloads - // m -= prod; - m = m - prod; - } - return (d, m); - } - - - fn div_estimate(a: &BigUint, b: &BigUint, n: uint) - -> (BigUint, BigUint, BigUint) { - if a.data.len() < n { - return (Zero::zero(), Zero::zero(), (*a).clone()); - } - - let an = a.data.tailn(a.data.len() - n); - let bn = *b.data.last().unwrap(); - let mut d = Vec::with_capacity(an.len()); - let mut carry = 0; - for elt in an.iter().rev() { - let ai = BigDigit::to_doublebigdigit(carry, *elt); - let di = ai / (bn as DoubleBigDigit); - assert!(di < BigDigit::base); - carry = (ai % (bn as DoubleBigDigit)) as BigDigit; - d.push(di as BigDigit) - } - d.reverse(); - - let shift = (a.data.len() - an.len()) - (b.data.len() - 1); - if shift == 0 { - return (BigUint::new(d), One::one(), (*b).clone()); - } - let one: BigUint = One::one(); - return (BigUint::new(d).shl_unit(shift), - one.shl_unit(shift), - b.shl_unit(shift)); - } - } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. - /// - /// The result is always positive. - #[inline] - fn gcd(&self, other: &BigUint) -> BigUint { - // Use Euclid's algorithm - let mut m = (*self).clone(); - let mut n = (*other).clone(); - while !m.is_zero() { - let temp = m; - m = n % temp; - n = temp; - } - return n; - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. - #[inline] - fn lcm(&self, other: &BigUint) -> BigUint { ((*self * *other) / self.gcd(other)) } - - /// Deprecated, use `is_multiple_of` instead. - #[deprecated = "function renamed to `is_multiple_of`"] - #[inline] - fn divides(&self, other: &BigUint) -> bool { return self.is_multiple_of(other); } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &BigUint) -> bool { (*self % *other).is_zero() } - - /// Returns `true` if the number is divisible by `2`. - #[inline] - fn is_even(&self) -> bool { - // Considering only the last digit. - match self.data.as_slice().head() { - Some(x) => x.is_even(), - None => true - } - } - - /// Returns `true` if the number is not divisible by `2`. - #[inline] - fn is_odd(&self) -> bool { !self.is_even() } -} - -impl ToPrimitive for BigUint { - #[inline] - fn to_i64(&self) -> Option { - self.to_u64().and_then(|n| { - // If top bit of u64 is set, it's too large to convert to i64. - if n >> 63 == 0 { - Some(n as i64) - } else { - None - } - }) - } - - // `DoubleBigDigit` size dependent - #[inline] - fn to_u64(&self) -> Option { - match self.data.len() { - 0 => Some(0), - 1 => Some(self.data.as_slice()[0] as u64), - 2 => Some(BigDigit::to_doublebigdigit(self.data.as_slice()[1], self.data.as_slice()[0]) - as u64), - _ => None - } - } -} - -impl FromPrimitive for BigUint { - #[inline] - fn from_i64(n: i64) -> Option { - if n > 0 { - FromPrimitive::from_u64(n as u64) - } else if n == 0 { - Some(Zero::zero()) - } else { - None - } - } - - // `DoubleBigDigit` size dependent - #[inline] - fn from_u64(n: u64) -> Option { - let n = match BigDigit::from_doublebigdigit(n) { - (0, 0) => Zero::zero(), - (0, n0) => BigUint::new(vec!(n0)), - (n1, n0) => BigUint::new(vec!(n0, n1)) - }; - Some(n) - } -} - -/// A generic trait for converting a value to a `BigUint`. -pub trait ToBigUint { - /// Converts the value of `self` to a `BigUint`. - fn to_biguint(&self) -> Option; -} - -impl ToBigUint for BigInt { - #[inline] - fn to_biguint(&self) -> Option { - if self.sign == Plus { - Some(self.data.clone()) - } else if self.sign == NoSign { - Some(Zero::zero()) - } else { - None - } - } -} - -impl ToBigUint for BigUint { - #[inline] - fn to_biguint(&self) -> Option { - Some(self.clone()) - } -} - -macro_rules! impl_to_biguint( - ($T:ty, $from_ty:path) => { - impl ToBigUint for $T { - #[inline] - fn to_biguint(&self) -> Option { - $from_ty(*self) - } - } - } -) - -impl_to_biguint!(int, FromPrimitive::from_int) -impl_to_biguint!(i8, FromPrimitive::from_i8) -impl_to_biguint!(i16, FromPrimitive::from_i16) -impl_to_biguint!(i32, FromPrimitive::from_i32) -impl_to_biguint!(i64, FromPrimitive::from_i64) -impl_to_biguint!(uint, FromPrimitive::from_uint) -impl_to_biguint!(u8, FromPrimitive::from_u8) -impl_to_biguint!(u16, FromPrimitive::from_u16) -impl_to_biguint!(u32, FromPrimitive::from_u32) -impl_to_biguint!(u64, FromPrimitive::from_u64) - -impl ToStrRadix for BigUint { - fn to_str_radix(&self, radix: uint) -> String { - assert!(1 < radix && radix <= 16, "The radix must be within (1, 16]"); - let (base, max_len) = get_radix_base(radix); - if base == BigDigit::base { - return fill_concat(self.data.as_slice(), radix, max_len) - } - return fill_concat(convert_base(self, base).as_slice(), radix, max_len); - - fn convert_base(n: &BigUint, base: DoubleBigDigit) -> Vec { - let divider = base.to_biguint().unwrap(); - let mut result = Vec::new(); - let mut m = n.clone(); - while m >= divider { - let (d, m0) = m.div_mod_floor(÷r); - result.push(m0.to_uint().unwrap() as BigDigit); - m = d; - } - if !m.is_zero() { - result.push(m.to_uint().unwrap() as BigDigit); - } - return result; - } - - fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> String { - if v.is_empty() { - return "0".to_string() - } - let mut s = String::with_capacity(v.len() * l); - for n in v.iter().rev() { - let ss = (*n as uint).to_str_radix(radix); - s.push_str("0".repeat(l - ss.len()).as_slice()); - s.push_str(ss.as_slice()); - } - s.as_slice().trim_left_chars('0').to_string() - } - } -} - -impl FromStrRadix for BigUint { - /// Creates and initializes a `BigUint`. - #[inline] - fn from_str_radix(s: &str, radix: uint) -> Option { - BigUint::parse_bytes(s.as_bytes(), radix) - } -} - -impl BigUint { - /// Creates and initializes a `BigUint`. - /// - /// The digits are be in base 2^32. - #[inline] - pub fn new(mut digits: Vec) -> BigUint { - // omit trailing zeros - let new_len = digits.iter().rposition(|n| *n != 0).map_or(0, |p| p + 1); - digits.truncate(new_len); - BigUint { data: digits } - } - - /// Creates and initializes a `BigUint`. - /// - /// The digits are be in base 2^32. - #[inline] - pub fn from_slice(slice: &[BigDigit]) -> BigUint { - BigUint::new(Vec::from_slice(slice)) - } - - /// Creates and initializes a `BigUint`. - pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { - let (base, unit_len) = get_radix_base(radix); - let base_num = match base.to_biguint() { - Some(base_num) => base_num, - None => { return None; } - }; - - let mut end = buf.len(); - let mut n: BigUint = Zero::zero(); - let mut power: BigUint = One::one(); - loop { - let start = cmp::max(end, unit_len) - unit_len; - match uint::parse_bytes(buf[start..end], radix) { - Some(d) => { - let d: Option = FromPrimitive::from_uint(d); - match d { - Some(d) => { - // FIXME(#5992): assignment operator overloads - // n += d * power; - n = n + d * power; - } - None => { return None; } - } - } - None => { return None; } - } - if end <= unit_len { - return Some(n); - } - end -= unit_len; - // FIXME(#5992): assignment operator overloads - // power *= base_num; - power = power * base_num; - } - } - - #[inline] - fn shl_unit(&self, n_unit: uint) -> BigUint { - if n_unit == 0 || self.is_zero() { return (*self).clone(); } - - BigUint::new(Vec::from_elem(n_unit, ZERO_BIG_DIGIT).append(self.data.as_slice())) - } - - #[inline] - fn shl_bits(&self, n_bits: uint) -> BigUint { - if n_bits == 0 || self.is_zero() { return (*self).clone(); } - - let mut carry = 0; - let mut shifted: Vec = self.data.iter().map(|elem| { - let (hi, lo) = BigDigit::from_doublebigdigit( - (*elem as DoubleBigDigit) << n_bits | (carry as DoubleBigDigit) - ); - carry = hi; - lo - }).collect(); - if carry != 0 { shifted.push(carry); } - return BigUint::new(shifted); - } - - #[inline] - fn shr_unit(&self, n_unit: uint) -> BigUint { - if n_unit == 0 { return (*self).clone(); } - if self.data.len() < n_unit { return Zero::zero(); } - return BigUint::from_slice( - self.data.slice(n_unit, self.data.len()) - ); - } - - #[inline] - fn shr_bits(&self, n_bits: uint) -> BigUint { - if n_bits == 0 || self.data.is_empty() { return (*self).clone(); } - - let mut borrow = 0; - let mut shifted_rev = Vec::with_capacity(self.data.len()); - for elem in self.data.iter().rev() { - shifted_rev.push((*elem >> n_bits) | borrow); - borrow = *elem << (BigDigit::bits - n_bits); - } - let shifted = { shifted_rev.reverse(); shifted_rev }; - return BigUint::new(shifted); - } - - /// Determines the fewest bits necessary to express the `BigUint`. - pub fn bits(&self) -> uint { - if self.is_zero() { return 0; } - let zeros = self.data.last().unwrap().leading_zeros(); - return self.data.len()*BigDigit::bits - zeros; - } -} - -// `DoubleBigDigit` size dependent -#[inline] -fn get_radix_base(radix: uint) -> (DoubleBigDigit, uint) { - match radix { - 2 => (4294967296, 32), - 3 => (3486784401, 20), - 4 => (4294967296, 16), - 5 => (1220703125, 13), - 6 => (2176782336, 12), - 7 => (1977326743, 11), - 8 => (1073741824, 10), - 9 => (3486784401, 10), - 10 => (1000000000, 9), - 11 => (2357947691, 9), - 12 => (429981696, 8), - 13 => (815730721, 8), - 14 => (1475789056, 8), - 15 => (2562890625, 8), - 16 => (4294967296, 8), - _ => fail!("The radix must be within (1, 16]") - } -} - -/// A Sign is a `BigInt`'s composing element. -#[deriving(PartialEq, PartialOrd, Eq, Ord, Clone, Show)] -pub enum Sign { Minus, NoSign, Plus } - -impl Neg for Sign { - /// Negate Sign value. - #[inline] - fn neg(&self) -> Sign { - match *self { - Minus => Plus, - NoSign => NoSign, - Plus => Minus - } - } -} - -/// A big signed integer type. -#[deriving(Clone)] -pub struct BigInt { - sign: Sign, - data: BigUint -} - -impl PartialEq for BigInt { - #[inline] - fn eq(&self, other: &BigInt) -> bool { - self.cmp(other) == Equal - } -} - -impl Eq for BigInt {} - -impl PartialOrd for BigInt { - #[inline] - fn partial_cmp(&self, other: &BigInt) -> Option { - Some(self.cmp(other)) - } -} - -impl Ord for BigInt { - #[inline] - fn cmp(&self, other: &BigInt) -> Ordering { - let scmp = self.sign.cmp(&other.sign); - if scmp != Equal { return scmp; } - - match self.sign { - NoSign => Equal, - Plus => self.data.cmp(&other.data), - Minus => other.data.cmp(&self.data), - } - } -} - -impl Default for BigInt { - #[inline] - fn default() -> BigInt { Zero::zero() } -} - -impl fmt::Show for BigInt { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_str_radix(10)) - } -} - -impl hash::Hash for BigInt { - fn hash(&self, state: &mut S) { - (self.sign == Plus).hash(state); - self.data.hash(state); - } -} - -impl FromStr for BigInt { - #[inline] - fn from_str(s: &str) -> Option { - FromStrRadix::from_str_radix(s, 10) - } -} - -impl Num for BigInt {} - -impl Shl for BigInt { - #[inline] - fn shl(&self, rhs: &uint) -> BigInt { - BigInt::from_biguint(self.sign, self.data << *rhs) - } -} - -impl Shr for BigInt { - #[inline] - fn shr(&self, rhs: &uint) -> BigInt { - BigInt::from_biguint(self.sign, self.data >> *rhs) - } -} - -impl Zero for BigInt { - #[inline] - fn zero() -> BigInt { - BigInt::from_biguint(NoSign, Zero::zero()) - } - - #[inline] - fn is_zero(&self) -> bool { self.sign == NoSign } -} - -impl One for BigInt { - #[inline] - fn one() -> BigInt { - BigInt::from_biguint(Plus, One::one()) - } -} - -impl Signed for BigInt { - #[inline] - fn abs(&self) -> BigInt { - match self.sign { - Plus | NoSign => self.clone(), - Minus => BigInt::from_biguint(Plus, self.data.clone()) - } - } - - #[inline] - fn abs_sub(&self, other: &BigInt) -> BigInt { - if *self <= *other { Zero::zero() } else { *self - *other } - } - - #[inline] - fn signum(&self) -> BigInt { - match self.sign { - Plus => BigInt::from_biguint(Plus, One::one()), - Minus => BigInt::from_biguint(Minus, One::one()), - NoSign => Zero::zero(), - } - } - - #[inline] - fn is_positive(&self) -> bool { self.sign == Plus } - - #[inline] - fn is_negative(&self) -> bool { self.sign == Minus } -} - -impl Add for BigInt { - #[inline] - fn add(&self, other: &BigInt) -> BigInt { - match (self.sign, other.sign) { - (NoSign, _) => other.clone(), - (_, NoSign) => self.clone(), - (Plus, Plus) => BigInt::from_biguint(Plus, self.data + other.data), - (Plus, Minus) => self - (-*other), - (Minus, Plus) => other - (-*self), - (Minus, Minus) => -((-self) + (-*other)) - } - } -} - -impl Sub for BigInt { - #[inline] - fn sub(&self, other: &BigInt) -> BigInt { - match (self.sign, other.sign) { - (NoSign, _) => -other, - (_, NoSign) => self.clone(), - (Plus, Plus) => match self.data.cmp(&other.data) { - Less => BigInt::from_biguint(Minus, other.data - self.data), - Greater => BigInt::from_biguint(Plus, self.data - other.data), - Equal => Zero::zero() - }, - (Plus, Minus) => self + (-*other), - (Minus, Plus) => -((-self) + *other), - (Minus, Minus) => (-other) - (-*self) - } - } -} - -impl Mul for BigInt { - #[inline] - fn mul(&self, other: &BigInt) -> BigInt { - match (self.sign, other.sign) { - (NoSign, _) | (_, NoSign) => Zero::zero(), - (Plus, Plus) | (Minus, Minus) => { - BigInt::from_biguint(Plus, self.data * other.data) - }, - (Plus, Minus) | (Minus, Plus) => { - BigInt::from_biguint(Minus, self.data * other.data) - } - } - } -} - -impl Div for BigInt { - #[inline] - fn div(&self, other: &BigInt) -> BigInt { - let (q, _) = self.div_rem(other); - q - } -} - -impl Rem for BigInt { - #[inline] - fn rem(&self, other: &BigInt) -> BigInt { - let (_, r) = self.div_rem(other); - r - } -} - -impl Neg for BigInt { - #[inline] - fn neg(&self) -> BigInt { - BigInt::from_biguint(self.sign.neg(), self.data.clone()) - } -} - -impl CheckedAdd for BigInt { - #[inline] - fn checked_add(&self, v: &BigInt) -> Option { - return Some(self.add(v)); - } -} - -impl CheckedSub for BigInt { - #[inline] - fn checked_sub(&self, v: &BigInt) -> Option { - return Some(self.sub(v)); - } -} - -impl CheckedMul for BigInt { - #[inline] - fn checked_mul(&self, v: &BigInt) -> Option { - return Some(self.mul(v)); - } -} - -impl CheckedDiv for BigInt { - #[inline] - fn checked_div(&self, v: &BigInt) -> Option { - if v.is_zero() { - return None; - } - return Some(self.div(v)); - } -} - - -impl Integer for BigInt { - #[inline] - fn div_rem(&self, other: &BigInt) -> (BigInt, BigInt) { - // r.sign == self.sign - let (d_ui, r_ui) = self.data.div_mod_floor(&other.data); - let d = BigInt::from_biguint(Plus, d_ui); - let r = BigInt::from_biguint(Plus, r_ui); - match (self.sign, other.sign) { - (_, NoSign) => fail!(), - (Plus, Plus) | (NoSign, Plus) => ( d, r), - (Plus, Minus) | (NoSign, Minus) => (-d, r), - (Minus, Plus) => (-d, -r), - (Minus, Minus) => ( d, -r) - } - } - - #[inline] - fn div_floor(&self, other: &BigInt) -> BigInt { - let (d, _) = self.div_mod_floor(other); - d - } - - #[inline] - fn mod_floor(&self, other: &BigInt) -> BigInt { - let (_, m) = self.div_mod_floor(other); - m - } - - fn div_mod_floor(&self, other: &BigInt) -> (BigInt, BigInt) { - // m.sign == other.sign - let (d_ui, m_ui) = self.data.div_rem(&other.data); - let d = BigInt::from_biguint(Plus, d_ui); - let m = BigInt::from_biguint(Plus, m_ui); - match (self.sign, other.sign) { - (_, NoSign) => fail!(), - (Plus, Plus) | (NoSign, Plus) => (d, m), - (Plus, Minus) | (NoSign, Minus) => if m.is_zero() { - (-d, Zero::zero()) - } else { - (-d - One::one(), m + *other) - }, - (Minus, Plus) => if m.is_zero() { - (-d, Zero::zero()) - } else { - (-d - One::one(), other - m) - }, - (Minus, Minus) => (d, -m) - } - } - - /// Calculates the Greatest Common Divisor (GCD) of the number and `other`. - /// - /// The result is always positive. - #[inline] - fn gcd(&self, other: &BigInt) -> BigInt { - BigInt::from_biguint(Plus, self.data.gcd(&other.data)) - } - - /// Calculates the Lowest Common Multiple (LCM) of the number and `other`. - #[inline] - fn lcm(&self, other: &BigInt) -> BigInt { - BigInt::from_biguint(Plus, self.data.lcm(&other.data)) - } - - /// Deprecated, use `is_multiple_of` instead. - #[deprecated = "function renamed to `is_multiple_of`"] - #[inline] - fn divides(&self, other: &BigInt) -> bool { return self.is_multiple_of(other); } - - /// Returns `true` if the number is a multiple of `other`. - #[inline] - fn is_multiple_of(&self, other: &BigInt) -> bool { self.data.is_multiple_of(&other.data) } - - /// Returns `true` if the number is divisible by `2`. - #[inline] - fn is_even(&self) -> bool { self.data.is_even() } - - /// Returns `true` if the number is not divisible by `2`. - #[inline] - fn is_odd(&self) -> bool { self.data.is_odd() } -} - -impl ToPrimitive for BigInt { - #[inline] - fn to_i64(&self) -> Option { - match self.sign { - Plus => self.data.to_i64(), - NoSign => Some(0), - Minus => { - self.data.to_u64().and_then(|n| { - let m: u64 = 1 << 63; - if n < m { - Some(-(n as i64)) - } else if n == m { - Some(i64::MIN) - } else { - None - } - }) - } - } - } - - #[inline] - fn to_u64(&self) -> Option { - match self.sign { - Plus => self.data.to_u64(), - NoSign => Some(0), - Minus => None - } - } -} - -impl FromPrimitive for BigInt { - #[inline] - fn from_i64(n: i64) -> Option { - if n > 0 { - FromPrimitive::from_u64(n as u64).and_then(|n| { - Some(BigInt::from_biguint(Plus, n)) - }) - } else if n < 0 { - FromPrimitive::from_u64(u64::MAX - (n as u64) + 1).and_then( - |n| { - Some(BigInt::from_biguint(Minus, n)) - }) - } else { - Some(Zero::zero()) - } - } - - #[inline] - fn from_u64(n: u64) -> Option { - if n == 0 { - Some(Zero::zero()) - } else { - FromPrimitive::from_u64(n).and_then(|n| { - Some(BigInt::from_biguint(Plus, n)) - }) - } - } -} - -/// A generic trait for converting a value to a `BigInt`. -pub trait ToBigInt { - /// Converts the value of `self` to a `BigInt`. - fn to_bigint(&self) -> Option; -} - -impl ToBigInt for BigInt { - #[inline] - fn to_bigint(&self) -> Option { - Some(self.clone()) - } -} - -impl ToBigInt for BigUint { - #[inline] - fn to_bigint(&self) -> Option { - if self.is_zero() { - Some(Zero::zero()) - } else { - Some(BigInt { sign: Plus, data: self.clone() }) - } - } -} - -macro_rules! impl_to_bigint( - ($T:ty, $from_ty:path) => { - impl ToBigInt for $T { - #[inline] - fn to_bigint(&self) -> Option { - $from_ty(*self) - } - } - } -) - -impl_to_bigint!(int, FromPrimitive::from_int) -impl_to_bigint!(i8, FromPrimitive::from_i8) -impl_to_bigint!(i16, FromPrimitive::from_i16) -impl_to_bigint!(i32, FromPrimitive::from_i32) -impl_to_bigint!(i64, FromPrimitive::from_i64) -impl_to_bigint!(uint, FromPrimitive::from_uint) -impl_to_bigint!(u8, FromPrimitive::from_u8) -impl_to_bigint!(u16, FromPrimitive::from_u16) -impl_to_bigint!(u32, FromPrimitive::from_u32) -impl_to_bigint!(u64, FromPrimitive::from_u64) - -impl ToStrRadix for BigInt { - #[inline] - fn to_str_radix(&self, radix: uint) -> String { - match self.sign { - Plus => self.data.to_str_radix(radix), - NoSign => "0".to_string(), - Minus => format!("-{}", self.data.to_str_radix(radix)), - } - } -} - -impl FromStrRadix for BigInt { - /// Creates and initializes a BigInt. - #[inline] - fn from_str_radix(s: &str, radix: uint) -> Option { - BigInt::parse_bytes(s.as_bytes(), radix) - } -} - -pub trait RandBigInt { - /// Generate a random `BigUint` of the given bit size. - fn gen_biguint(&mut self, bit_size: uint) -> BigUint; - - /// Generate a random BigInt of the given bit size. - fn gen_bigint(&mut self, bit_size: uint) -> BigInt; - - /// Generate a random `BigUint` less than the given bound. Fails - /// when the bound is zero. - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint; - - /// Generate a random `BigUint` within the given range. The lower - /// bound is inclusive; the upper bound is exclusive. Fails when - /// the upper bound is not greater than the lower bound. - fn gen_biguint_range(&mut self, lbound: &BigUint, ubound: &BigUint) -> BigUint; - - /// Generate a random `BigInt` within the given range. The lower - /// bound is inclusive; the upper bound is exclusive. Fails when - /// the upper bound is not greater than the lower bound. - fn gen_bigint_range(&mut self, lbound: &BigInt, ubound: &BigInt) -> BigInt; -} - -impl RandBigInt for R { - fn gen_biguint(&mut self, bit_size: uint) -> BigUint { - let (digits, rem) = bit_size.div_rem(&BigDigit::bits); - let mut data = Vec::with_capacity(digits+1); - for _ in range(0, digits) { - data.push(self.gen()); - } - if rem > 0 { - let final_digit: BigDigit = self.gen(); - data.push(final_digit >> (BigDigit::bits - rem)); - } - BigUint::new(data) - } - - fn gen_bigint(&mut self, bit_size: uint) -> BigInt { - // Generate a random BigUint... - let biguint = self.gen_biguint(bit_size); - // ...and then randomly assign it a Sign... - let sign = if biguint.is_zero() { - // ...except that if the BigUint is zero, we need to try - // again with probability 0.5. This is because otherwise, - // the probability of generating a zero BigInt would be - // double that of any other number. - if self.gen() { - return self.gen_bigint(bit_size); - } else { - NoSign - } - } else if self.gen() { - Plus - } else { - Minus - }; - BigInt::from_biguint(sign, biguint) - } - - fn gen_biguint_below(&mut self, bound: &BigUint) -> BigUint { - assert!(!bound.is_zero()); - let bits = bound.bits(); - loop { - let n = self.gen_biguint(bits); - if n < *bound { return n; } - } - } - - fn gen_biguint_range(&mut self, - lbound: &BigUint, - ubound: &BigUint) - -> BigUint { - assert!(*lbound < *ubound); - return *lbound + self.gen_biguint_below(&(*ubound - *lbound)); - } - - fn gen_bigint_range(&mut self, - lbound: &BigInt, - ubound: &BigInt) - -> BigInt { - assert!(*lbound < *ubound); - let delta = (*ubound - *lbound).to_biguint().unwrap(); - return *lbound + self.gen_biguint_below(&delta).to_bigint().unwrap(); - } -} - -impl BigInt { - /// Creates and initializes a BigInt. - /// - /// The digits are be in base 2^32. - #[inline] - pub fn new(sign: Sign, digits: Vec) -> BigInt { - BigInt::from_biguint(sign, BigUint::new(digits)) - } - - /// Creates and initializes a `BigInt`. - /// - /// The digits are be in base 2^32. - #[inline] - pub fn from_biguint(sign: Sign, data: BigUint) -> BigInt { - if sign == NoSign || data.is_zero() { - return BigInt { sign: NoSign, data: Zero::zero() }; - } - BigInt { sign: sign, data: data } - } - - /// Creates and initializes a `BigInt`. - #[inline] - pub fn from_slice(sign: Sign, slice: &[BigDigit]) -> BigInt { - BigInt::from_biguint(sign, BigUint::from_slice(slice)) - } - - /// Creates and initializes a `BigInt`. - pub fn parse_bytes(buf: &[u8], radix: uint) -> Option { - if buf.is_empty() { return None; } - let mut sign = Plus; - let mut start = 0; - if buf[0] == b'-' { - sign = Minus; - start = 1; - } - return BigUint::parse_bytes(buf[start..], radix) - .map(|bu| BigInt::from_biguint(sign, bu)); - } - - /// Converts this `BigInt` into a `BigUint`, if it's not negative. - #[inline] - pub fn to_biguint(&self) -> Option { - match self.sign { - Plus => Some(self.data.clone()), - NoSign => Some(Zero::zero()), - Minus => None - } - } -} - -#[cfg(test)] -mod biguint_tests { - use Integer; - use super::{BigDigit, BigUint, ToBigUint}; - use super::{Plus, BigInt, RandBigInt, ToBigInt}; - - use std::cmp::{Less, Equal, Greater}; - use std::from_str::FromStr; - use std::i64; - use std::num::{Zero, One, FromStrRadix, ToStrRadix}; - use std::num::{ToPrimitive, FromPrimitive}; - use std::num::CheckedDiv; - use std::rand::task_rng; - use std::u64; - use std::hash::hash; - - #[test] - fn test_from_slice() { - fn check(slice: &[BigDigit], data: &[BigDigit]) { - assert!(data == BigUint::from_slice(slice).data.as_slice()); - } - check([1], [1]); - check([0, 0, 0], []); - check([1, 2, 0, 0], [1, 2]); - check([0, 0, 1, 2], [0, 0, 1, 2]); - check([0, 0, 1, 2, 0, 0], [0, 0, 1, 2]); - check([-1], [-1]); - } - - #[test] - fn test_cmp() { - let data: [&[_], ..7] = [ &[], &[1], &[2], &[-1], &[0, 1], &[2, 1], &[1, 1, 1] ]; - let data: Vec = data.iter().map(|v| BigUint::from_slice(*v)).collect(); - for (i, ni) in data.iter().enumerate() { - for (j0, nj) in data.slice(i, data.len()).iter().enumerate() { - let j = j0 + i; - if i == j { - assert_eq!(ni.cmp(nj), Equal); - assert_eq!(nj.cmp(ni), Equal); - assert_eq!(ni, nj); - assert!(!(ni != nj)); - assert!(ni <= nj); - assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); - } else { - assert_eq!(ni.cmp(nj), Less); - assert_eq!(nj.cmp(ni), Greater); - - assert!(!(ni == nj)); - assert!(ni != nj); - - assert!(ni <= nj); - assert!(!(ni >= nj)); - assert!(ni < nj); - assert!(!(ni > nj)); - - assert!(!(nj <= ni)); - assert!(nj >= ni); - assert!(!(nj < ni)); - assert!(nj > ni); - } - } - } - } - - #[test] - fn test_hash() { - let a = BigUint::new(vec!()); - let b = BigUint::new(vec!(0)); - let c = BigUint::new(vec!(1)); - let d = BigUint::new(vec!(1,0,0,0,0,0)); - let e = BigUint::new(vec!(0,0,0,0,0,1)); - assert!(hash(&a) == hash(&b)); - assert!(hash(&b) != hash(&c)); - assert!(hash(&c) == hash(&d)); - assert!(hash(&d) != hash(&e)); - } - - #[test] - fn test_bitand() { - fn check(left: &[BigDigit], - right: &[BigDigit], - expected: &[BigDigit]) { - assert_eq!(BigUint::from_slice(left) & BigUint::from_slice(right), - BigUint::from_slice(expected)); - } - check([], [], []); - check([268, 482, 17], - [964, 54], - [260, 34]); - } - - #[test] - fn test_bitor() { - fn check(left: &[BigDigit], - right: &[BigDigit], - expected: &[BigDigit]) { - assert_eq!(BigUint::from_slice(left) | BigUint::from_slice(right), - BigUint::from_slice(expected)); - } - check([], [], []); - check([268, 482, 17], - [964, 54], - [972, 502, 17]); - } - - #[test] - fn test_bitxor() { - fn check(left: &[BigDigit], - right: &[BigDigit], - expected: &[BigDigit]) { - assert_eq!(BigUint::from_slice(left) ^ BigUint::from_slice(right), - BigUint::from_slice(expected)); - } - check([], [], []); - check([268, 482, 17], - [964, 54], - [712, 468, 17]); - } - - #[test] - fn test_shl() { - fn check(s: &str, shift: uint, ans: &str) { - let opt_biguint: Option = FromStrRadix::from_str_radix(s, 16); - let bu = (opt_biguint.unwrap() << shift).to_str_radix(16); - assert_eq!(bu.as_slice(), ans); - } - - check("0", 3, "0"); - check("1", 3, "8"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 3, - "8\ - 0000\ - 0000\ - 0000\ - 0008\ - 0000\ - 0000\ - 0000\ - 0008"); - check("1\ - 0000\ - 0001\ - 0000\ - 0001", - 2, - "4\ - 0000\ - 0004\ - 0000\ - 0004"); - check("1\ - 0001\ - 0001", - 1, - "2\ - 0002\ - 0002"); - - check("\ - 4000\ - 0000\ - 0000\ - 0000", - 3, - "2\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000\ - 0000", - 2, - "1\ - 0000\ - 0000"); - check("4000", - 2, - "1\ - 0000"); - - check("4000\ - 0000\ - 0000\ - 0000", - 67, - "2\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000\ - 0000", - 35, - "2\ - 0000\ - 0000\ - 0000\ - 0000"); - check("4000", - 19, - "2\ - 0000\ - 0000"); - - check("fedc\ - ba98\ - 7654\ - 3210\ - fedc\ - ba98\ - 7654\ - 3210", - 4, - "f\ - edcb\ - a987\ - 6543\ - 210f\ - edcb\ - a987\ - 6543\ - 2100"); - check("88887777666655554444333322221111", 16, - "888877776666555544443333222211110000"); - } - - #[test] - fn test_shr() { - fn check(s: &str, shift: uint, ans: &str) { - let opt_biguint: Option = - FromStrRadix::from_str_radix(s, 16); - let bu = (opt_biguint.unwrap() >> shift).to_str_radix(16); - assert_eq!(bu.as_slice(), ans); - } - - check("0", 3, "0"); - check("f", 3, "1"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 3, - "2000\ - 0000\ - 0000\ - 0000\ - 2000\ - 0000\ - 0000\ - 0000"); - check("1\ - 0000\ - 0001\ - 0000\ - 0001", - 2, - "4000\ - 0000\ - 4000\ - 0000"); - check("1\ - 0001\ - 0001", - 1, - "8000\ - 8000"); - - check("2\ - 0000\ - 0000\ - 0000\ - 0001\ - 0000\ - 0000\ - 0000\ - 0001", - 67, - "4000\ - 0000\ - 0000\ - 0000"); - check("2\ - 0000\ - 0001\ - 0000\ - 0001", - 35, - "4000\ - 0000"); - check("2\ - 0001\ - 0001", - 19, - "4000"); - - check("1\ - 0000\ - 0000\ - 0000\ - 0000", - 1, - "8000\ - 0000\ - 0000\ - 0000"); - check("1\ - 0000\ - 0000", - 1, - "8000\ - 0000"); - check("1\ - 0000", - 1, - "8000"); - check("f\ - edcb\ - a987\ - 6543\ - 210f\ - edcb\ - a987\ - 6543\ - 2100", - 4, - "fedc\ - ba98\ - 7654\ - 3210\ - fedc\ - ba98\ - 7654\ - 3210"); - - check("888877776666555544443333222211110000", 16, - "88887777666655554444333322221111"); - } - - // `DoubleBigDigit` size dependent - #[test] - fn test_convert_i64() { - fn check(b1: BigUint, i: i64) { - let b2: BigUint = FromPrimitive::from_i64(i).unwrap(); - assert!(b1 == b2); - assert!(b1.to_i64().unwrap() == i); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(i64::MAX.to_biguint().unwrap(), i64::MAX); - - check(BigUint::new(vec!( )), 0); - check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits))); - check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1); - check(BigUint::new(vec!( 0, 1 )), (1 << (1*BigDigit::bits))); - check(BigUint::new(vec!(-1, -1 >> 1)), i64::MAX); - - assert_eq!(i64::MIN.to_biguint(), None); - assert_eq!(BigUint::new(vec!(-1, -1 )).to_i64(), None); - assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_i64(), None); - assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_i64(), None); - } - - // `DoubleBigDigit` size dependent - #[test] - fn test_convert_u64() { - fn check(b1: BigUint, u: u64) { - let b2: BigUint = FromPrimitive::from_u64(u).unwrap(); - assert!(b1 == b2); - assert!(b1.to_u64().unwrap() == u); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(u64::MIN.to_biguint().unwrap(), u64::MIN); - check(u64::MAX.to_biguint().unwrap(), u64::MAX); - - check(BigUint::new(vec!( )), 0); - check(BigUint::new(vec!( 1 )), (1 << (0*BigDigit::bits))); - check(BigUint::new(vec!(-1 )), (1 << (1*BigDigit::bits)) - 1); - check(BigUint::new(vec!( 0, 1)), (1 << (1*BigDigit::bits))); - check(BigUint::new(vec!(-1, -1)), u64::MAX); - - assert_eq!(BigUint::new(vec!( 0, 0, 1)).to_u64(), None); - assert_eq!(BigUint::new(vec!(-1, -1, -1)).to_u64(), None); - } - - #[test] - fn test_convert_to_bigint() { - fn check(n: BigUint, ans: BigInt) { - assert_eq!(n.to_bigint().unwrap(), ans); - assert_eq!(n.to_bigint().unwrap().to_biguint().unwrap(), n); - } - check(Zero::zero(), Zero::zero()); - check(BigUint::new(vec!(1,2,3)), - BigInt::from_biguint(Plus, BigUint::new(vec!(1,2,3)))); - } - - static SUM_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[ 1]), - (&[ 1], &[ 1], &[ 2]), - (&[ 1], &[ 1, 1], &[ 2, 1]), - (&[ 1], &[-1], &[ 0, 1]), - (&[ 1], &[-1, -1], &[ 0, 0, 1]), - (&[-1, -1], &[-1, -1], &[-2, -1, 1]), - (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]), - (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2]) - ]; - - #[test] - fn test_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a + b == c); - assert!(b + a == c); - } - } - - #[test] - fn test_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(c - a == b); - assert!(c - b == a); - } - } - - #[test] - #[should_fail] - fn test_sub_fail_on_underflow() { - let (a, b) : (BigUint, BigUint) = (Zero::zero(), One::one()); - a - b; - } - - static MUL_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[]), - (&[ 2], &[], &[]), - (&[ 1], &[ 1], &[1]), - (&[ 2], &[ 3], &[ 6]), - (&[ 1], &[ 1, 1, 1], &[1, 1, 1]), - (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]), - (&[ 1, 1, 1], &[-1], &[-1, -1, -1]), - (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]), - (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]), - (&[-1], &[-1], &[ 1, -2]), - (&[-1, -1], &[-1], &[ 1, -1, -2]), - (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]), - (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]), - (&[-1/2 + 1], &[ 2], &[ 0, 1]), - (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]), - (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]), - (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]), - (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]), - (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]), - (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]) - ]; - - static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] - = &[ - (&[ 1], &[ 2], &[], &[1]), - (&[ 1, 1], &[ 2], &[-1/2+1], &[1]), - (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]), - (&[ 0, 1], &[-1], &[1], &[1]), - (&[-1, -1], &[-2], &[2, 1], &[3]) - ]; - - #[test] - fn test_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a * b == c); - assert!(b * a == c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - assert!(a == b * c + d); - assert!(a == c * b + d); - } - } - - #[test] - fn test_div_rem() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - if !a.is_zero() { - assert_eq!(c.div_rem(&a), (b.clone(), Zero::zero())); - } - if !b.is_zero() { - assert_eq!(c.div_rem(&b), (a.clone(), Zero::zero())); - } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - if !b.is_zero() { assert!(a.div_rem(&b) == (c, d)); } - } - } - - #[test] - fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a.checked_add(&b).unwrap() == c); - assert!(b.checked_add(&a).unwrap() == c); - } - } - - #[test] - fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(c.checked_sub(&a).unwrap() == b); - assert!(c.checked_sub(&b).unwrap() == a); - - if a > c { - assert!(a.checked_sub(&c).is_none()); - } - if b > c { - assert!(b.checked_sub(&c).is_none()); - } - } - } - - #[test] - fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - assert!(a.checked_mul(&b).unwrap() == c); - assert!(b.checked_mul(&a).unwrap() == c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - let d = BigUint::from_slice(d_vec); - - assert!(a == b.checked_mul(&c).unwrap() + d); - assert!(a == c.checked_mul(&b).unwrap() + d); - } - } - - #[test] - fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigUint::from_slice(a_vec); - let b = BigUint::from_slice(b_vec); - let c = BigUint::from_slice(c_vec); - - if !a.is_zero() { - assert!(c.checked_div(&a).unwrap() == b); - } - if !b.is_zero() { - assert!(c.checked_div(&b).unwrap() == a); - } - - assert!(c.checked_div(&Zero::zero()).is_none()); - } - } - - #[test] - fn test_gcd() { - fn check(a: uint, b: uint, c: uint) { - let big_a: BigUint = FromPrimitive::from_uint(a).unwrap(); - let big_b: BigUint = FromPrimitive::from_uint(b).unwrap(); - let big_c: BigUint = FromPrimitive::from_uint(c).unwrap(); - - assert_eq!(big_a.gcd(&big_b), big_c); - } - - check(10, 2, 2); - check(10, 3, 1); - check(0, 3, 3); - check(3, 3, 3); - check(56, 42, 14); - } - - #[test] - fn test_lcm() { - fn check(a: uint, b: uint, c: uint) { - let big_a: BigUint = FromPrimitive::from_uint(a).unwrap(); - let big_b: BigUint = FromPrimitive::from_uint(b).unwrap(); - let big_c: BigUint = FromPrimitive::from_uint(c).unwrap(); - - assert_eq!(big_a.lcm(&big_b), big_c); - } - - check(1, 0, 0); - check(0, 1, 0); - check(1, 1, 1); - check(8, 9, 72); - check(11, 5, 55); - check(99, 17, 1683); - } - - #[test] - fn test_is_even() { - let one: BigUint = FromStr::from_str("1").unwrap(); - let two: BigUint = FromStr::from_str("2").unwrap(); - let thousand: BigUint = FromStr::from_str("1000").unwrap(); - let big: BigUint = FromStr::from_str("1000000000000000000000").unwrap(); - let bigger: BigUint = FromStr::from_str("1000000000000000000001").unwrap(); - assert!(one.is_odd()); - assert!(two.is_even()); - assert!(thousand.is_even()); - assert!(big.is_even()); - assert!(bigger.is_odd()); - assert!((one << 64).is_even()); - assert!(((one << 64) + one).is_odd()); - } - - fn to_str_pairs() -> Vec<(BigUint, Vec<(uint, String)>)> { - let bits = BigDigit::bits; - vec!(( Zero::zero(), vec!( - (2, "0".to_string()), (3, "0".to_string()) - )), ( BigUint::from_slice([ 0xff ]), vec!( - (2, "11111111".to_string()), - (3, "100110".to_string()), - (4, "3333".to_string()), - (5, "2010".to_string()), - (6, "1103".to_string()), - (7, "513".to_string()), - (8, "377".to_string()), - (9, "313".to_string()), - (10, "255".to_string()), - (11, "212".to_string()), - (12, "193".to_string()), - (13, "168".to_string()), - (14, "143".to_string()), - (15, "120".to_string()), - (16, "ff".to_string()) - )), ( BigUint::from_slice([ 0xfff ]), vec!( - (2, "111111111111".to_string()), - (4, "333333".to_string()), - (16, "fff".to_string()) - )), ( BigUint::from_slice([ 1, 2 ]), vec!( - (2, - format!("10{}1", "0".repeat(bits - 1))), - (4, - format!("2{}1", "0".repeat(bits / 2 - 1))), - (10, match bits { - 32 => "8589934593".to_string(), - 16 => "131073".to_string(), - _ => fail!() - }), - (16, - format!("2{}1", "0".repeat(bits / 4 - 1))) - )), ( BigUint::from_slice([ 1, 2, 3 ]), vec!( - (2, - format!("11{}10{}1", - "0".repeat(bits - 2), - "0".repeat(bits - 1))), - (4, - format!("3{}2{}1", - "0".repeat(bits / 2 - 1), - "0".repeat(bits / 2 - 1))), - (10, match bits { - 32 => "55340232229718589441".to_string(), - 16 => "12885032961".to_string(), - _ => fail!() - }), - (16, - format!("3{}2{}1", - "0".repeat(bits / 4 - 1), - "0".repeat(bits / 4 - 1))) - )) ) - } - - #[test] - fn test_to_str_radix() { - let r = to_str_pairs(); - for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; - for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; - assert_eq!(n.to_str_radix(*radix).as_slice(), - str.as_slice()); - } - } - } - - #[test] - fn test_from_str_radix() { - let r = to_str_pairs(); - for num_pair in r.iter() { - let &(ref n, ref rs) = num_pair; - for str_pair in rs.iter() { - let &(ref radix, ref str) = str_pair; - assert_eq!(n, - &FromStrRadix::from_str_radix(str.as_slice(), - *radix).unwrap()); - } - } - - let zed: Option = FromStrRadix::from_str_radix("Z", 10); - assert_eq!(zed, None); - let blank: Option = FromStrRadix::from_str_radix("_", 2); - assert_eq!(blank, None); - let minus_one: Option = FromStrRadix::from_str_radix("-1", - 10); - assert_eq!(minus_one, None); - } - - #[test] - fn test_factor() { - fn factor(n: uint) -> BigUint { - let mut f: BigUint = One::one(); - for i in range(2, n + 1) { - // FIXME(#5992): assignment operator overloads - // f *= FromPrimitive::from_uint(i); - f = f * FromPrimitive::from_uint(i).unwrap(); - } - return f; - } - - fn check(n: uint, s: &str) { - let n = factor(n); - let ans = match FromStrRadix::from_str_radix(s, 10) { - Some(x) => x, None => fail!() - }; - assert_eq!(n, ans); - } - - check(3, "6"); - check(10, "3628800"); - check(20, "2432902008176640000"); - check(30, "265252859812191058636308480000000"); - } - - #[test] - fn test_bits() { - assert_eq!(BigUint::new(vec!(0,0,0,0)).bits(), 0); - let n: BigUint = FromPrimitive::from_uint(0).unwrap(); - assert_eq!(n.bits(), 0); - let n: BigUint = FromPrimitive::from_uint(1).unwrap(); - assert_eq!(n.bits(), 1); - let n: BigUint = FromPrimitive::from_uint(3).unwrap(); - assert_eq!(n.bits(), 2); - let n: BigUint = FromStrRadix::from_str_radix("4000000000", 16).unwrap(); - assert_eq!(n.bits(), 39); - let one: BigUint = One::one(); - assert_eq!((one << 426).bits(), 427); - } - - #[test] - fn test_rand() { - let mut rng = task_rng(); - let _n: BigUint = rng.gen_biguint(137); - assert!(rng.gen_biguint(0).is_zero()); - } - - #[test] - fn test_rand_range() { - let mut rng = task_rng(); - - for _ in range(0u, 10) { - assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(), - &FromPrimitive::from_uint(237).unwrap()), - FromPrimitive::from_uint(236).unwrap()); - } - - let l = FromPrimitive::from_uint(403469000 + 2352).unwrap(); - let u = FromPrimitive::from_uint(403469000 + 3513).unwrap(); - for _ in range(0u, 1000) { - let n: BigUint = rng.gen_biguint_below(&u); - assert!(n < u); - - let n: BigUint = rng.gen_biguint_range(&l, &u); - assert!(n >= l); - assert!(n < u); - } - } - - #[test] - #[should_fail] - fn test_zero_rand_range() { - task_rng().gen_biguint_range(&FromPrimitive::from_uint(54).unwrap(), - &FromPrimitive::from_uint(54).unwrap()); - } - - #[test] - #[should_fail] - fn test_negative_rand_range() { - let mut rng = task_rng(); - let l = FromPrimitive::from_uint(2352).unwrap(); - let u = FromPrimitive::from_uint(3513).unwrap(); - // Switching u and l should fail: - let _n: BigUint = rng.gen_biguint_range(&u, &l); - } -} - -#[cfg(test)] -mod bigint_tests { - use Integer; - use super::{BigDigit, BigUint, ToBigUint}; - use super::{Sign, Minus, NoSign, Plus, BigInt, RandBigInt, ToBigInt}; - - use std::cmp::{Less, Equal, Greater}; - use std::i64; - use std::num::CheckedDiv; - use std::num::{Zero, One, FromStrRadix, ToStrRadix}; - use std::num::{ToPrimitive, FromPrimitive}; - use std::rand::task_rng; - use std::u64; - use std::hash::hash; - - #[test] - fn test_from_biguint() { - fn check(inp_s: Sign, inp_n: uint, ans_s: Sign, ans_n: uint) { - let inp = BigInt::from_biguint(inp_s, FromPrimitive::from_uint(inp_n).unwrap()); - let ans = BigInt { sign: ans_s, data: FromPrimitive::from_uint(ans_n).unwrap()}; - assert_eq!(inp, ans); - } - check(Plus, 1, Plus, 1); - check(Plus, 0, NoSign, 0); - check(Minus, 1, Minus, 1); - check(NoSign, 1, NoSign, 0); - } - - #[test] - fn test_cmp() { - let vs: [&[BigDigit], ..4] = [ &[2 as BigDigit], &[1, 1], &[2, 1], &[1, 1, 1] ]; - let mut nums = Vec::new(); - for s in vs.iter().rev() { - nums.push(BigInt::from_slice(Minus, *s)); - } - nums.push(Zero::zero()); - nums.extend(vs.iter().map(|s| BigInt::from_slice(Plus, *s))); - - for (i, ni) in nums.iter().enumerate() { - for (j0, nj) in nums.slice(i, nums.len()).iter().enumerate() { - let j = i + j0; - if i == j { - assert_eq!(ni.cmp(nj), Equal); - assert_eq!(nj.cmp(ni), Equal); - assert_eq!(ni, nj); - assert!(!(ni != nj)); - assert!(ni <= nj); - assert!(ni >= nj); - assert!(!(ni < nj)); - assert!(!(ni > nj)); - } else { - assert_eq!(ni.cmp(nj), Less); - assert_eq!(nj.cmp(ni), Greater); - - assert!(!(ni == nj)); - assert!(ni != nj); - - assert!(ni <= nj); - assert!(!(ni >= nj)); - assert!(ni < nj); - assert!(!(ni > nj)); - - assert!(!(nj <= ni)); - assert!(nj >= ni); - assert!(!(nj < ni)); - assert!(nj > ni); - } - } - } - } - - #[test] - fn test_hash() { - let a = BigInt::new(NoSign, vec!()); - let b = BigInt::new(NoSign, vec!(0)); - let c = BigInt::new(Plus, vec!(1)); - let d = BigInt::new(Plus, vec!(1,0,0,0,0,0)); - let e = BigInt::new(Plus, vec!(0,0,0,0,0,1)); - let f = BigInt::new(Minus, vec!(1)); - assert!(hash(&a) == hash(&b)); - assert!(hash(&b) != hash(&c)); - assert!(hash(&c) == hash(&d)); - assert!(hash(&d) != hash(&e)); - assert!(hash(&c) != hash(&f)); - } - - #[test] - fn test_convert_i64() { - fn check(b1: BigInt, i: i64) { - let b2: BigInt = FromPrimitive::from_i64(i).unwrap(); - assert!(b1 == b2); - assert!(b1.to_i64().unwrap() == i); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(i64::MIN.to_bigint().unwrap(), i64::MIN); - check(i64::MAX.to_bigint().unwrap(), i64::MAX); - - assert_eq!( - (i64::MAX as u64 + 1).to_bigint().unwrap().to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Minus, BigUint::new(vec!(1,0,0,1<<(BigDigit::bits-1)))).to_i64(), - None); - - assert_eq!( - BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_i64(), - None); - } - - #[test] - fn test_convert_u64() { - fn check(b1: BigInt, u: u64) { - let b2: BigInt = FromPrimitive::from_u64(u).unwrap(); - assert!(b1 == b2); - assert!(b1.to_u64().unwrap() == u); - } - - check(Zero::zero(), 0); - check(One::one(), 1); - check(u64::MIN.to_bigint().unwrap(), u64::MIN); - check(u64::MAX.to_bigint().unwrap(), u64::MAX); - - assert_eq!( - BigInt::from_biguint(Plus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), - None); - - let max_value: BigUint = FromPrimitive::from_u64(u64::MAX).unwrap(); - assert_eq!(BigInt::from_biguint(Minus, max_value).to_u64(), None); - assert_eq!(BigInt::from_biguint(Minus, BigUint::new(vec!(1, 2, 3, 4, 5))).to_u64(), None); - } - - #[test] - fn test_convert_to_biguint() { - fn check(n: BigInt, ans_1: BigUint) { - assert_eq!(n.to_biguint().unwrap(), ans_1); - assert_eq!(n.to_biguint().unwrap().to_bigint().unwrap(), n); - } - let zero: BigInt = Zero::zero(); - let unsigned_zero: BigUint = Zero::zero(); - let positive = BigInt::from_biguint( - Plus, BigUint::new(vec!(1,2,3))); - let negative = -positive; - - check(zero, unsigned_zero); - check(positive, BigUint::new(vec!(1,2,3))); - - assert_eq!(negative.to_biguint(), None); - } - - static SUM_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[ 1]), - (&[ 1], &[ 1], &[ 2]), - (&[ 1], &[ 1, 1], &[ 2, 1]), - (&[ 1], &[-1], &[ 0, 1]), - (&[ 1], &[-1, -1], &[ 0, 0, 1]), - (&[-1, -1], &[-1, -1], &[-2, -1, 1]), - (&[ 1, 1, 1], &[-1, -1], &[ 0, 1, 2]), - (&[ 2, 2, 1], &[-1, -2], &[ 1, 1, 2]) - ]; - - #[test] - fn test_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a + b == c); - assert!(b + a == c); - assert!(c + (-a) == b); - assert!(c + (-b) == a); - assert!(a + (-c) == (-b)); - assert!(b + (-c) == (-a)); - assert!((-a) + (-b) == (-c)) - assert!(a + (-a) == Zero::zero()); - } - } - - #[test] - fn test_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(c - a == b); - assert!(c - b == a); - assert!((-b) - a == (-c)) - assert!((-a) - b == (-c)) - assert!(b - (-a) == c); - assert!(a - (-b) == c); - assert!((-c) - (-a) == (-b)); - assert!(a - a == Zero::zero()); - } - } - - static MUL_TRIPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] = &[ - (&[], &[], &[]), - (&[], &[ 1], &[]), - (&[ 2], &[], &[]), - (&[ 1], &[ 1], &[1]), - (&[ 2], &[ 3], &[ 6]), - (&[ 1], &[ 1, 1, 1], &[1, 1, 1]), - (&[ 1, 2, 3], &[ 3], &[ 3, 6, 9]), - (&[ 1, 1, 1], &[-1], &[-1, -1, -1]), - (&[ 1, 2, 3], &[-1], &[-1, -2, -2, 2]), - (&[ 1, 2, 3, 4], &[-1], &[-1, -2, -2, -2, 3]), - (&[-1], &[-1], &[ 1, -2]), - (&[-1, -1], &[-1], &[ 1, -1, -2]), - (&[-1, -1, -1], &[-1], &[ 1, -1, -1, -2]), - (&[-1, -1, -1, -1], &[-1], &[ 1, -1, -1, -1, -2]), - (&[-1/2 + 1], &[ 2], &[ 0, 1]), - (&[0, -1/2 + 1], &[ 2], &[ 0, 0, 1]), - (&[ 1, 2], &[ 1, 2, 3], &[1, 4, 7, 6]), - (&[-1, -1], &[-1, -1, -1], &[1, 0, -1, -2, -1]), - (&[-1, -1, -1], &[-1, -1, -1, -1], &[1, 0, 0, -1, -2, -1, -1]), - (&[ 0, 0, 1], &[ 1, 2, 3], &[0, 0, 1, 2, 3]), - (&[ 0, 0, 1], &[ 0, 0, 0, 1], &[0, 0, 0, 0, 0, 1]) - ]; - - static DIV_REM_QUADRUPLES: &'static [(&'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit], - &'static [BigDigit])] - = &[ - (&[ 1], &[ 2], &[], &[1]), - (&[ 1, 1], &[ 2], &[-1/2+1], &[1]), - (&[ 1, 1, 1], &[ 2], &[-1/2+1, -1/2+1], &[1]), - (&[ 0, 1], &[-1], &[1], &[1]), - (&[-1, -1], &[-2], &[2, 1], &[3]) - ]; - - #[test] - fn test_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a * b == c); - assert!(b * a == c); - - assert!((-a) * b == -c); - assert!((-b) * a == -c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - assert!(a == b * c + d); - assert!(a == c * b + d); - } - } - - #[test] - fn test_div_mod_floor() { - fn check_sub(a: &BigInt, b: &BigInt, ans_d: &BigInt, ans_m: &BigInt) { - let (d, m) = a.div_mod_floor(b); - if !m.is_zero() { - assert_eq!(m.sign, b.sign); - } - assert!(m.abs() <= b.abs()); - assert!(*a == b * d + m); - assert!(d == *ans_d); - assert!(m == *ans_m); - } - - fn check(a: &BigInt, b: &BigInt, d: &BigInt, m: &BigInt) { - if m.is_zero() { - check_sub(a, b, d, m); - check_sub(a, &b.neg(), &d.neg(), m); - check_sub(&a.neg(), b, &d.neg(), m); - check_sub(&a.neg(), &b.neg(), d, m); - } else { - check_sub(a, b, d, m); - check_sub(a, &b.neg(), &(d.neg() - One::one()), &(m - *b)); - check_sub(&a.neg(), b, &(d.neg() - One::one()), &(b - *m)); - check_sub(&a.neg(), &b.neg(), d, &m.neg()); - } - } - - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } - if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - if !b.is_zero() { - check(&a, &b, &c, &d); - } - } - } - - - #[test] - fn test_div_rem() { - fn check_sub(a: &BigInt, b: &BigInt, ans_q: &BigInt, ans_r: &BigInt) { - let (q, r) = a.div_rem(b); - if !r.is_zero() { - assert_eq!(r.sign, a.sign); - } - assert!(r.abs() <= b.abs()); - assert!(*a == b * q + r); - assert!(q == *ans_q); - assert!(r == *ans_r); - } - - fn check(a: &BigInt, b: &BigInt, q: &BigInt, r: &BigInt) { - check_sub(a, b, q, r); - check_sub(a, &b.neg(), &q.neg(), r); - check_sub(&a.neg(), b, &q.neg(), &r.neg()); - check_sub(&a.neg(), &b.neg(), q, &r.neg()); - } - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { check(&c, &a, &b, &Zero::zero()); } - if !b.is_zero() { check(&c, &b, &a, &Zero::zero()); } - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - if !b.is_zero() { - check(&a, &b, &c, &d); - } - } - } - - #[test] - fn test_checked_add() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a.checked_add(&b).unwrap() == c); - assert!(b.checked_add(&a).unwrap() == c); - assert!(c.checked_add(&(-a)).unwrap() == b); - assert!(c.checked_add(&(-b)).unwrap() == a); - assert!(a.checked_add(&(-c)).unwrap() == (-b)); - assert!(b.checked_add(&(-c)).unwrap() == (-a)); - assert!((-a).checked_add(&(-b)).unwrap() == (-c)) - assert!(a.checked_add(&(-a)).unwrap() == Zero::zero()); - } - } - - #[test] - fn test_checked_sub() { - for elm in SUM_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(c.checked_sub(&a).unwrap() == b); - assert!(c.checked_sub(&b).unwrap() == a); - assert!((-b).checked_sub(&a).unwrap() == (-c)) - assert!((-a).checked_sub(&b).unwrap() == (-c)) - assert!(b.checked_sub(&(-a)).unwrap() == c); - assert!(a.checked_sub(&(-b)).unwrap() == c); - assert!((-c).checked_sub(&(-a)).unwrap() == (-b)); - assert!(a.checked_sub(&a).unwrap() == Zero::zero()); - } - } - - #[test] - fn test_checked_mul() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - assert!(a.checked_mul(&b).unwrap() == c); - assert!(b.checked_mul(&a).unwrap() == c); - - assert!((-a).checked_mul(&b).unwrap() == -c); - assert!((-b).checked_mul(&a).unwrap() == -c); - } - - for elm in DIV_REM_QUADRUPLES.iter() { - let (a_vec, b_vec, c_vec, d_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - let d = BigInt::from_slice(Plus, d_vec); - - assert!(a == b.checked_mul(&c).unwrap() + d); - assert!(a == c.checked_mul(&b).unwrap() + d); - } - } - #[test] - fn test_checked_div() { - for elm in MUL_TRIPLES.iter() { - let (a_vec, b_vec, c_vec) = *elm; - let a = BigInt::from_slice(Plus, a_vec); - let b = BigInt::from_slice(Plus, b_vec); - let c = BigInt::from_slice(Plus, c_vec); - - if !a.is_zero() { - assert!(c.checked_div(&a).unwrap() == b); - assert!((-c).checked_div(&(-a)).unwrap() == b); - assert!((-c).checked_div(&a).unwrap() == -b); - } - if !b.is_zero() { - assert!(c.checked_div(&b).unwrap() == a); - assert!((-c).checked_div(&(-b)).unwrap() == a); - assert!((-c).checked_div(&b).unwrap() == -a); - } - - assert!(c.checked_div(&Zero::zero()).is_none()); - assert!((-c).checked_div(&Zero::zero()).is_none()); - } - } - - #[test] - fn test_gcd() { - fn check(a: int, b: int, c: int) { - let big_a: BigInt = FromPrimitive::from_int(a).unwrap(); - let big_b: BigInt = FromPrimitive::from_int(b).unwrap(); - let big_c: BigInt = FromPrimitive::from_int(c).unwrap(); - - assert_eq!(big_a.gcd(&big_b), big_c); - } - - check(10, 2, 2); - check(10, 3, 1); - check(0, 3, 3); - check(3, 3, 3); - check(56, 42, 14); - check(3, -3, 3); - check(-6, 3, 3); - check(-4, -2, 2); - } - - #[test] - fn test_lcm() { - fn check(a: int, b: int, c: int) { - let big_a: BigInt = FromPrimitive::from_int(a).unwrap(); - let big_b: BigInt = FromPrimitive::from_int(b).unwrap(); - let big_c: BigInt = FromPrimitive::from_int(c).unwrap(); - - assert_eq!(big_a.lcm(&big_b), big_c); - } - - check(1, 0, 0); - check(0, 1, 0); - check(1, 1, 1); - check(-1, 1, 1); - check(1, -1, 1); - check(-1, -1, 1); - check(8, 9, 72); - check(11, 5, 55); - } - - #[test] - fn test_abs_sub() { - let zero: BigInt = Zero::zero(); - let one: BigInt = One::one(); - assert_eq!((-one).abs_sub(&one), zero); - let one: BigInt = One::one(); - let zero: BigInt = Zero::zero(); - assert_eq!(one.abs_sub(&one), zero); - let one: BigInt = One::one(); - let zero: BigInt = Zero::zero(); - assert_eq!(one.abs_sub(&zero), one); - let one: BigInt = One::one(); - let two: BigInt = FromPrimitive::from_int(2).unwrap(); - assert_eq!(one.abs_sub(&-one), two); - } - - #[test] - fn test_to_str_radix() { - fn check(n: int, ans: &str) { - let n: BigInt = FromPrimitive::from_int(n).unwrap(); - assert!(ans == n.to_str_radix(10).as_slice()); - } - check(10, "10"); - check(1, "1"); - check(0, "0"); - check(-1, "-1"); - check(-10, "-10"); - } - - - #[test] - fn test_from_str_radix() { - fn check(s: &str, ans: Option) { - let ans = ans.map(|n| { - let x: BigInt = FromPrimitive::from_int(n).unwrap(); - x - }); - assert_eq!(FromStrRadix::from_str_radix(s, 10), ans); - } - check("10", Some(10)); - check("1", Some(1)); - check("0", Some(0)); - check("-1", Some(-1)); - check("-10", Some(-10)); - check("Z", None); - check("_", None); - - // issue 10522, this hit an edge case that caused it to - // attempt to allocate a vector of size (-1u) == huge. - let x: BigInt = - from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap(); - let _y = x.to_string(); - } - - #[test] - fn test_neg() { - assert!(-BigInt::new(Plus, vec!(1, 1, 1)) == - BigInt::new(Minus, vec!(1, 1, 1))); - assert!(-BigInt::new(Minus, vec!(1, 1, 1)) == - BigInt::new(Plus, vec!(1, 1, 1))); - let zero: BigInt = Zero::zero(); - assert_eq!(-zero, zero); - } - - #[test] - fn test_rand() { - let mut rng = task_rng(); - let _n: BigInt = rng.gen_bigint(137); - assert!(rng.gen_bigint(0).is_zero()); - } - - #[test] - fn test_rand_range() { - let mut rng = task_rng(); - - for _ in range(0u, 10) { - assert_eq!(rng.gen_bigint_range(&FromPrimitive::from_uint(236).unwrap(), - &FromPrimitive::from_uint(237).unwrap()), - FromPrimitive::from_uint(236).unwrap()); - } - - fn check(l: BigInt, u: BigInt) { - let mut rng = task_rng(); - for _ in range(0u, 1000) { - let n: BigInt = rng.gen_bigint_range(&l, &u); - assert!(n >= l); - assert!(n < u); - } - } - let l: BigInt = FromPrimitive::from_uint(403469000 + 2352).unwrap(); - let u: BigInt = FromPrimitive::from_uint(403469000 + 3513).unwrap(); - check( l.clone(), u.clone()); - check(-l.clone(), u.clone()); - check(-u.clone(), -l.clone()); - } - - #[test] - #[should_fail] - fn test_zero_rand_range() { - task_rng().gen_bigint_range(&FromPrimitive::from_int(54).unwrap(), - &FromPrimitive::from_int(54).unwrap()); - } - - #[test] - #[should_fail] - fn test_negative_rand_range() { - let mut rng = task_rng(); - let l = FromPrimitive::from_uint(2352).unwrap(); - let u = FromPrimitive::from_uint(3513).unwrap(); - // Switching u and l should fail: - let _n: BigInt = rng.gen_bigint_range(&u, &l); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use super::BigUint; - use std::iter; - use std::mem::replace; - use std::num::{FromPrimitive, Zero, One}; - - fn factorial(n: uint) -> BigUint { - let mut f: BigUint = One::one(); - for i in iter::range_inclusive(1, n) { - f = f * FromPrimitive::from_uint(i).unwrap(); - } - f - } - - fn fib(n: uint) -> BigUint { - let mut f0: BigUint = Zero::zero(); - let mut f1: BigUint = One::one(); - for _ in range(0, n) { - let f2 = f0 + f1; - f0 = replace(&mut f1, f2); - } - f0 - } - - #[bench] - fn factorial_100(b: &mut Bencher) { - b.iter(|| { - factorial(100); - }); - } - - #[bench] - fn fib_100(b: &mut Bencher) { - b.iter(|| { - fib(100); - }); - } - - #[bench] - fn to_string(b: &mut Bencher) { - let fac = factorial(100); - let fib = fib(100); - b.iter(|| { - fac.to_string(); - }); - b.iter(|| { - fib.to_string(); - }); - } - - #[bench] - fn shr(b: &mut Bencher) { - let n = { let one : BigUint = One::one(); one << 1000 }; - b.iter(|| { - let mut m = n.clone(); - for _ in range(0u, 10) { - m = m >> 1; - } - }) - } -} diff --git a/src/libnum/complex.rs b/src/libnum/complex.rs deleted file mode 100644 index 6690b1d5ddc..00000000000 --- a/src/libnum/complex.rs +++ /dev/null @@ -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 or the MIT license -// , 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 { - /// Real portion of the complex number - pub re: T, - /// Imaginary portion of the complex number - pub im: T -} - -pub type Complex32 = Complex; -pub type Complex64 = Complex; - -impl Complex { - /// Create a new Complex - #[inline] - pub fn new(re: T, im: T) -> Complex { - 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 { - Complex::new(self.re.clone(), -self.im) - } - - - /// Multiplies `self` by the scalar `t`. - #[inline] - pub fn scale(&self, t: T) -> Complex { - Complex::new(self.re * t, self.im * t) - } - - /// Divides `self` by the scalar `t`. - #[inline] - pub fn unscale(&self, t: T) -> Complex { - Complex::new(self.re / t, self.im / t) - } - - /// Returns `1/self` - #[inline] - pub fn inv(&self) -> Complex { - let norm_sqr = self.norm_sqr(); - Complex::new(self.re / norm_sqr, - -self.im / norm_sqr) - } -} - -impl Complex { - /// Calculate |self| - #[inline] - pub fn norm(&self) -> T { - self.re.hypot(self.im) - } -} - -impl Complex { - /// 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 { - Complex::new(*r * theta.cos(), *r * theta.sin()) - } -} - -/* arithmetic */ -// (a + i b) + (c + i d) == (a + c) + i (b + d) -impl Add, Complex> for Complex { - #[inline] - fn add(&self, other: &Complex) -> Complex { - Complex::new(self.re + other.re, self.im + other.im) - } -} -// (a + i b) - (c + i d) == (a - c) + i (b - d) -impl Sub, Complex> for Complex { - #[inline] - fn sub(&self, other: &Complex) -> Complex { - 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 Mul, Complex> for Complex { - #[inline] - fn mul(&self, other: &Complex) -> Complex { - 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 Div, Complex> for Complex { - #[inline] - fn div(&self, other: &Complex) -> Complex { - 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 Neg> for Complex { - #[inline] - fn neg(&self) -> Complex { - Complex::new(-self.re, -self.im) - } -} - -/* constants */ -impl Zero for Complex { - #[inline] - fn zero() -> Complex { - Complex::new(Zero::zero(), Zero::zero()) - } - - #[inline] - fn is_zero(&self) -> bool { - self.re.is_zero() && self.im.is_zero() - } -} - -impl One for Complex { - #[inline] - fn one() -> Complex { - Complex::new(One::one(), Zero::zero()) - } -} - -/* string conversions */ -impl fmt::Show for Complex { - 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 ToStrRadix for Complex { - 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)); - } -} diff --git a/src/libnum/integer.rs b/src/libnum/integer.rs deleted file mode 100644 index c5d076a70b5..00000000000 --- a/src/libnum/integer.rs +++ /dev/null @@ -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 or the MIT license -// , 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 - + Rem { - /// 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(x: T, y: T) -> (T, T) { x.div_rem(&y) } -/// Floored integer division -#[inline] pub fn div_floor(x: T, y: T) -> T { x.div_floor(&y) } -/// Floored integer modulus -#[inline] pub fn mod_floor(x: T, y: T) -> T { x.mod_floor(&y) } -/// Simultaneous floored integer division and modulus -#[inline] pub fn div_mod_floor(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(x: T, y: T) -> T { x.gcd(&y) } -/// Calculates the Lowest Common Multiple (LCM) of the number and `other`. -#[inline(always)] pub fn lcm(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) diff --git a/src/libnum/lib.rs b/src/libnum/lib.rs deleted file mode 100644 index 063bb17e09a..00000000000 --- a/src/libnum/lib.rs +++ /dev/null @@ -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 or the MIT license -// , 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 = 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; diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs deleted file mode 100644 index ceaf685c19a..00000000000 --- a/src/libnum/rational.rs +++ /dev/null @@ -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 or the MIT license -// , 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 { - numer: T, - denom: T -} - -/// Alias for a `Ratio` of machine-sized integers. -pub type Rational = Ratio; -pub type Rational32 = Ratio; -pub type Rational64 = Ratio; - -/// Alias for arbitrary precision rationals. -pub type BigRational = Ratio; - -impl - Ratio { - /// Creates a ratio representing the integer `t`. - #[inline] - pub fn from_integer(t: T) -> Ratio { - 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 { - Ratio { numer: numer, denom: denom } - } - - /// Create a new Ratio. Fails if `denom == 0`. - #[inline] - pub fn new(numer: T, denom: T) -> Ratio { - 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 { - let mut ret = self.clone(); - ret.reduce(); - ret - } - - /// Returns the reciprocal. - #[inline] - pub fn recip(&self) -> Ratio { - Ratio::new_raw(self.denom.clone(), self.numer.clone()) - } - - /// Rounds towards minus infinity. - #[inline] - pub fn floor(&self) -> Ratio { - 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 { - 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 { - 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 { - Ratio::from_integer(self.numer / self.denom) - } - - /// Returns the fractional part of a number. - #[inline] - pub fn fract(&self) -> Ratio { - Ratio::new_raw(self.numer % self.denom, self.denom.clone()) - } -} - -impl Ratio { - /// Converts a float into a rational number. - pub fn from_float(f: T) -> Option { - 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 - (impl $imp:ident, $($method:ident -> $res:ty),*) => { - impl + $imp> $imp for Ratio { - $( - #[inline] - fn $method(&self, other: &Ratio) -> $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_impl!(impl Eq, ) -cmp_impl!(impl Ord, cmp -> cmp::Ordering) - -/* Arithmetic */ -// a/b * c/d = (a*c)/(b*d) -impl - Mul,Ratio> for Ratio { - #[inline] - fn mul(&self, rhs: &Ratio) -> Ratio { - Ratio::new(self.numer * rhs.numer, self.denom * rhs.denom) - } -} - -// (a/b) / (c/d) = (a*d)/(b*c) -impl - Div,Ratio> for Ratio { - #[inline] - fn div(&self, rhs: &Ratio) -> Ratio { - 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 - $imp,Ratio> for Ratio { - #[inline] - fn $method(&self, rhs: &Ratio) -> Ratio { - 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 - Neg> for Ratio { - #[inline] - fn neg(&self) -> Ratio { - Ratio::new_raw(-self.numer, self.denom.clone()) - } -} - -/* Constants */ -impl - Zero for Ratio { - #[inline] - fn zero() -> Ratio { - Ratio::new_raw(Zero::zero(), One::one()) - } - - #[inline] - fn is_zero(&self) -> bool { - *self == Zero::zero() - } -} - -impl - One for Ratio { - #[inline] - fn one() -> Ratio { - Ratio::new_raw(One::one(), One::one()) - } -} - -impl - Num for Ratio {} - -impl - num::Signed for Ratio { - #[inline] - fn abs(&self) -> Ratio { - if self.is_negative() { -self.clone() } else { self.clone() } - } - - #[inline] - fn abs_sub(&self, other: &Ratio) -> Ratio { - if *self <= *other { Zero::zero() } else { *self - *other } - } - - #[inline] - fn signum(&self) -> Ratio { - if *self > Zero::zero() { - num::one() - } else if self.is_zero() { - num::zero() - } else { - - num::one::>() - } - } - - #[inline] - fn is_positive(&self) -> bool { *self > Zero::zero() } - - #[inline] - fn is_negative(&self) -> bool { *self < Zero::zero() } -} - -/* String conversions */ -impl fmt::Show for Ratio { - /// 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 ToStrRadix for Ratio { - /// 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 - FromStr for Ratio { - /// Parses `numer/denom` or just `numer`. - fn from_str(s: &str) -> Option> { - 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 - FromStrRadix for Ratio { - /// Parses `numer/denom` where the numbers are in base `radix`. - fn from_str_radix(s: &str, radix: uint) -> Option> { - let split: Vec<&str> = s.splitn(1, '/').collect(); - if split.len() < 2 { - None - } else { - let a_option: Option = FromStrRadix::from_str_radix( - *split.get(0), - radix); - a_option.and_then(|a| { - let b_option: Option = - 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 = 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 = 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(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::>()); - 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)); - } -} diff --git a/src/librand/isaac.rs b/src/librand/isaac.rs index 9bfd9177e34..3d83012cecb 100644 --- a/src/librand/isaac.rs +++ b/src/librand/isaac.rs @@ -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; } }} ); diff --git a/src/librand/lib.rs b/src/librand/lib.rs index ff7d3c29620..ebaa0349f5b 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -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 diff --git a/src/librustc/back/link.rs b/src/librustc/back/link.rs index fc5d726bf67..d47ca892b13 100644 --- a/src/librustc/back/link.rs +++ b/src/librustc/back/link.rs @@ -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| { 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::(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>(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()); } diff --git a/src/librustc/driver/config.rs b/src/librustc/driver/config.rs index f5423b22fe2..1f44808275f 100644 --- a/src/librustc/driver/config.rs +++ b/src/librustc/driver/config.rs @@ -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::>().append(default_cfg.as_slice()) + let mut v = user_cfg.into_iter().collect::>(); + v.push_all(default_cfg.as_slice()); + v } pub fn get_os(triple: &str) -> Option { diff --git a/src/librustc/driver/driver.rs b/src/librustc/driver/driver.rs index ba9ec904bae..f6aab6ef477 100644 --- a/src/librustc/driver/driver.rs +++ b/src/librustc/driver/driver.rs @@ -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::(s.get())) - .map(|id| id.name) }).unwrap_or(input.filestem()); OutputFilenames { diff --git a/src/librustc/driver/mod.rs b/src/librustc/driver/mod.rs index cb671d6e85f..4a2e209f562 100644 --- a/src/librustc/driver/mod.rs +++ b/src/librustc/driver/mod.rs @@ -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) -> Option { // 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(); diff --git a/src/librustc/driver/pretty.rs b/src/librustc/driver/pretty.rs index 75171af7411..19cd03f10a7 100644 --- a/src/librustc/driver/pretty.rs +++ b/src/librustc/driver/pretty.rs @@ -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 { diff --git a/src/librustc/lib.rs b/src/librustc/lib.rs index eb78762906e..390648eab2e 100644 --- a/src/librustc/lib.rs +++ b/src/librustc/lib.rs @@ -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)] diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index 76234c41637..2205dc42d47 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -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"); } } diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index 0f63000bff1..1107e44be3b 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -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>, diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index b7bd97e0219..7ec74eb1c3f 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -93,8 +93,9 @@ pub fn get_item_path(tcx: &ty::ctxt, def: ast::DefId) -> Vec // 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> { diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 5dafb7a661d..1d1012d9e4f 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -95,7 +95,7 @@ impl CStore { } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc { - self.metas.borrow().get(&cnum).clone() + (*self.metas.borrow())[cnum].clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { diff --git a/src/librustc/metadata/decoder.rs b/src/librustc/metadata/decoder.rs index dcf394aa3f4..456cf93d9b5 100644 --- a/src/librustc/metadata/decoder.rs +++ b/src/librustc/metadata/decoder.rs @@ -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) => { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index b9135e974c5..9106adcd3ef 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -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'); diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index d6b02a1d063..36e04d84aa9 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -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; diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index fb2c8aace95..6fbdceea37f 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -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); diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 32fc045012d..f72d14ba68a 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -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 } diff --git a/src/librustc/middle/borrowck/gather_loans/move_error.rs b/src/librustc/middle/borrowck/gather_loans/move_error.rs index b1757a4eb2c..887c6bc3e3f 100644 --- a/src/librustc/middle/borrowck/gather_loans/move_error.rs +++ b/src/librustc/middle/borrowck/gather_loans/move_error.rs @@ -98,7 +98,7 @@ fn group_errors_with_same_origin(errors: &Vec) 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 } } diff --git a/src/librustc/middle/borrowck/graphviz.rs b/src/librustc/middle/borrowck/graphviz.rs index 63d49dcd303..aab7fe8f31e 100644 --- a/src/librustc/middle/borrowck/graphviz.rs +++ b/src/librustc/middle/borrowck/graphviz.rs @@ -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) diff --git a/src/librustc/middle/borrowck/mod.rs b/src/librustc/middle/borrowck/mod.rs index 804ed883030..850c6008706 100644 --- a/src/librustc/middle/borrowck/mod.rs +++ b/src/librustc/middle/borrowck/mod.rs @@ -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); } } diff --git a/src/librustc/middle/borrowck/move_data.rs b/src/librustc/middle/borrowck/move_data.rs index 4c2ee9fe551..5f3c46fcf4c 100644 --- a/src/librustc/middle/borrowck/move_data.rs +++ b/src/librustc/middle/borrowck/move_data.rs @@ -192,23 +192,23 @@ impl MoveData { } pub fn path_loan_path(&self, index: MovePathIndex) -> Rc { - 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 { diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index fa5a6a2e54a..4b55a0b2609 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -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) | diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 84b96edc126..bc48e476aec 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -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()) } diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index abccc7623a7..7ffe5f42a5c 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -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 = 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>, 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>, 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 { let used_constructors: Vec = 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) { diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index a8b8eb2e339..d5557dfeeff 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -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 } diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 61b013d795e..513d65c335d 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -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; diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index bde868cdf6d..d4c8335d8e5 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -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) { diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 65633cfb34c..c413eb67a73 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -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, diff --git a/src/librustc/middle/graph.rs b/src/librustc/middle/graph.rs index 463eaa40ae0..4775f945f5c 100644 --- a/src/librustc/middle/graph.rs +++ b/src/librustc/middle/graph.rs @@ -146,11 +146,11 @@ impl Graph { } 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 { - self.nodes.get(idx.get()) + &self.nodes[idx.get()] } /////////////////////////////////////////////////////////////////////////// @@ -167,9 +167,9 @@ impl Graph { 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 Graph { } 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 { - self.edges.get(idx.get()) + &self.edges[idx.get()] } pub fn first_adjacent(&self, node: NodeIndex, dir: Direction) -> EdgeIndex { @@ -205,7 +205,7 @@ impl Graph { //! 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 Graph { //! 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 Graph { 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; } diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs index de291595ccc..d7707be58bb 100644 --- a/src/librustc/middle/intrinsicck.rs +++ b/src/librustc/middle/intrinsicck.rs @@ -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); } diff --git a/src/librustc/middle/lang_items.rs b/src/librustc/middle/lang_items.rs index 68411549c3c..f2d1a5e1d92 100644 --- a/src/librustc/middle/lang_items.rs +++ b/src/librustc/middle/lang_items.rs @@ -76,9 +76,9 @@ impl LanguageItems { } pub fn require(&self, it: LangItem) -> Result { - 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 { - *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. } } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 490e49d051e..63e9a80adc6 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -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 => "".to_string() + ImplicitRet => "".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 { 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 { - 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 { 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 { - 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; } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index e4399655941..9bd3f49eea6 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -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) { diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index 6e430760e36..138c671ceb6 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -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)); diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 5d6f7048b82..4506cd7e463 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -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) { diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index cf48e1899d1..7c16196f5c2 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -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]); } } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 0aff56ba3cf..eaec715a6a7 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -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 diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 6f517f1f166..eda4c241f86 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -399,7 +399,7 @@ impl<'a> LifetimeContext<'a> { fn check_lifetime_defs(&mut self, lifetimes: &Vec) { 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( diff --git a/src/librustc/middle/save/mod.rs b/src/librustc/middle/save/mod.rs index 9dfde7ec084..dd9601f1c3c 100644 --- a/src/librustc/middle/save/mod.rs +++ b/src/librustc/middle/save/mod.rs @@ -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>) { 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 { "".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); diff --git a/src/librustc/middle/save/recorder.rs b/src/librustc/middle/save/recorder.rs index 0695b6b360c..9dd2e8d1437 100644 --- a/src/librustc/middle/save/recorder.rs +++ b/src/librustc/middle/save/recorder.rs @@ -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, diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index e05a3237b26..54ae4d124f6 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -315,8 +315,8 @@ impl VecPerParamSpace { 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, diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 2a45d536066..aca7054018d 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -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) -> VtableBuiltinData { - 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::>(); 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( diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index 31266ff199f..9ee2c3aa149 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -110,7 +110,7 @@ impl<'cx, 'tcx> Iterator> for Supertraits<'cx, 'tcx> { fn next(&mut self) -> Option> { 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> 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 diff --git a/src/librustc/middle/trans/_match.rs b/src/librustc/middle/trans/_match.rs index 224f843ded6..be02b6a1c81 100644 --- a/src/librustc/middle/trans/_match.rs +++ b/src/librustc/middle/trans/_match.rs @@ -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 = 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 = 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); } } diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 7ec0f8716c1..802ca56fd3b 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -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); diff --git a/src/librustc/middle/trans/asm.rs b/src/librustc/middle/trans/asm.rs index f4586fca52f..04237a2d449 100644 --- a/src/librustc/middle/trans/asm.rs +++ b/src/librustc/middle/trans/asm.rs @@ -62,7 +62,7 @@ pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm) }).collect::>(); // 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::>().append(ext_inputs.as_slice()); + }).collect::>(); + 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); diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index 2a3ccc26e5b..239193ab79a 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -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 { 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_{}_{}", diff --git a/src/librustc/middle/trans/builder.rs b/src/librustc/middle/trans/builder.rs index 0c0dee4c3f7..81428937e4b 100644 --- a/src/librustc/middle/trans/builder.rs +++ b/src/librustc/middle/trans/builder.rs @@ -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) { diff --git a/src/librustc/middle/trans/cabi_x86_64.rs b/src/librustc/middle/trans/cabi_x86_64.rs index 2fd58303de3..1b8a354259a 100644 --- a/src/librustc/middle/trans/cabi_x86_64.rs +++ b/src/librustc/middle/trans/cabi_x86_64.rs @@ -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; diff --git a/src/librustc/middle/trans/callee.rs b/src/librustc/middle/trans/callee.rs index 3bfd03da283..d610a80347b 100644 --- a/src/librustc/middle/trans/callee.rs +++ b/src/librustc/middle/trans/callee.rs @@ -260,7 +260,7 @@ pub fn trans_unboxing_shim(bcx: Block, let tcx = bcx.tcx(); // Transform the self type to `Box`. - 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)) })); diff --git a/src/librustc/middle/trans/cleanup.rs b/src/librustc/middle/trans/cleanup.rs index 9edca215aef..827df48071a 100644 --- a/src/librustc/middle/trans/cleanup.rs +++ b/src/librustc/middle/trans/cleanup.rs @@ -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 diff --git a/src/librustc/middle/trans/closure.rs b/src/librustc/middle/trans/closure.rs index 8f877f981c8..d620b037549 100644 --- a/src/librustc/middle/trans/closure.rs +++ b/src/librustc/middle/trans/closure.rs @@ -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); diff --git a/src/librustc/middle/trans/common.rs b/src/librustc/middle/trans/common.rs index 810a6f2e8d4..945345425b3 100644 --- a/src/librustc/middle/trans/common.rs +++ b/src/librustc/middle/trans/common.rs @@ -59,9 +59,9 @@ fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool { ty::ty_struct(def_id, ref substs) => { let fields = ty::struct_fields(ccx.tcx(), def_id, substs); fields.len() == 1 && - fields.get(0).ident.name == + fields[0].ident.name == token::special_idents::unnamed_field.name && - type_is_immediate(ccx, fields.get(0).mt.ty) + type_is_immediate(ccx, fields[0].mt.ty) } _ => false } @@ -914,7 +914,7 @@ pub fn node_id_substs(bcx: Block, ty::node_id_item_substs(tcx, id).substs } MethodCall(method_call) => { - tcx.method_map.borrow().get(&method_call).substs.clone() + (*tcx.method_map.borrow())[method_call].substs.clone() } }; diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index d83c46be14a..399d2a0ec28 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -311,7 +311,7 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr) -> (ValueRef, ty::t) { fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef { let map_list = |exprs: &[P]| { exprs.iter().map(|e| const_expr(cx, &**e).val0()) - .fold(Vec::new(), |l, val| l.append_one(val)) + .fold(Vec::new(), |mut l, val| { l.push(val); l }) }; unsafe { let _icx = push_ctxt("const_expr"); diff --git a/src/librustc/middle/trans/controlflow.rs b/src/librustc/middle/trans/controlflow.rs index 17d213b4911..b2611987f04 100644 --- a/src/librustc/middle/trans/controlflow.rs +++ b/src/librustc/middle/trans/controlflow.rs @@ -291,10 +291,9 @@ pub fn trans_for<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, // Set up the method call (to `.next()`). let method_call = MethodCall::expr(loop_info.id); - let method_type = loopback_bcx_in.tcx() + let method_type = (*loopback_bcx_in.tcx() .method_map - .borrow() - .get(&method_call) + .borrow())[method_call] .ty; let method_type = monomorphize_type(loopback_bcx_in, method_type); let method_result_type = ty::ty_fn_ret(method_type); diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 7a187b2112b..f2c965924cd 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -348,7 +348,7 @@ impl TypeMap { }; let mut unique_type_id = String::with_capacity(256); - unique_type_id.push_char('{'); + unique_type_id.push('{'); match ty::get(type_).sty { ty::ty_nil | @@ -380,13 +380,13 @@ impl TypeMap { } }, ty::ty_uniq(inner_type) => { - unique_type_id.push_char('~'); + unique_type_id.push('~'); let inner_type_id = self.get_unique_type_id_of_type(cx, inner_type); let inner_type_id = self.get_unique_type_id_as_string(inner_type_id); unique_type_id.push_str(inner_type_id.as_slice()); }, ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => { - unique_type_id.push_char('*'); + unique_type_id.push('*'); if mutbl == ast::MutMutable { unique_type_id.push_str("mut"); } @@ -396,7 +396,7 @@ impl TypeMap { unique_type_id.push_str(inner_type_id.as_slice()); }, ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => { - unique_type_id.push_char('&'); + unique_type_id.push('&'); if mutbl == ast::MutMutable { unique_type_id.push_str("mut"); } @@ -443,7 +443,7 @@ impl TypeMap { let parameter_type_id = self.get_unique_type_id_as_string(parameter_type_id); unique_type_id.push_str(parameter_type_id.as_slice()); - unique_type_id.push_char(','); + unique_type_id.push(','); } if sig.variadic { @@ -474,7 +474,7 @@ impl TypeMap { } }; - unique_type_id.push_char('}'); + unique_type_id.push('}'); // Trim to size before storing permanently unique_type_id.shrink_to_fit(); @@ -489,8 +489,6 @@ impl TypeMap { def_id: ast::DefId, substs: &subst::Substs, output: &mut String) { - use std::num::ToStrRadix; - // First, find out the 'real' def_id of the type. Items inlined from // other crates have to be mapped back to their source. let source_def_id = if def_id.krate == ast::LOCAL_CRATE { @@ -515,13 +513,13 @@ impl TypeMap { output.push_str(crate_hash.as_str()); output.push_str("/"); - output.push_str(def_id.node.to_str_radix(16).as_slice()); + output.push_str(format!("{:x}", def_id.node).as_slice()); // Maybe check that there is no self type here. let tps = substs.types.get_slice(subst::TypeSpace); if tps.len() > 0 { - output.push_char('<'); + output.push('<'); for &type_parameter in tps.iter() { let param_type_id = @@ -529,10 +527,10 @@ impl TypeMap { let param_type_id = type_map.get_unique_type_id_as_string(param_type_id); output.push_str(param_type_id.as_slice()); - output.push_char(','); + output.push(','); } - output.push_char('>'); + output.push('>'); } } } @@ -571,7 +569,7 @@ impl TypeMap { let parameter_type_id = self.get_unique_type_id_as_string(parameter_type_id); unique_type_id.push_str(parameter_type_id.as_slice()); - unique_type_id.push_char(','); + unique_type_id.push(','); } if sig.variadic { @@ -584,7 +582,7 @@ impl TypeMap { let return_type_id = self.get_unique_type_id_as_string(return_type_id); unique_type_id.push_str(return_type_id.as_slice()); - unique_type_id.push_char(':'); + unique_type_id.push(':'); for bound in bounds.builtin_bounds.iter() { match bound { @@ -593,7 +591,7 @@ impl TypeMap { ty::BoundCopy => unique_type_id.push_str("Copy"), ty::BoundSync => unique_type_id.push_str("Sync"), }; - unique_type_id.push_char('+'); + unique_type_id.push('+'); } } @@ -1402,7 +1400,7 @@ pub fn create_function_debug_context(cx: &CrateContext, return create_DIArray(DIB(cx), []); } - name_to_append_suffix_to.push_char('<'); + name_to_append_suffix_to.push('<'); // The list to be filled with template parameters: let mut template_params: Vec = @@ -1483,7 +1481,7 @@ pub fn create_function_debug_context(cx: &CrateContext, } } - name_to_append_suffix_to.push_char('>'); + name_to_append_suffix_to.push('>'); return create_DIArray(DIB(cx), template_params.as_slice()); } @@ -1526,7 +1524,7 @@ fn compile_unit_metadata(cx: &CrateContext) { // prepend "./" if necessary let dotdot = b".."; let prefix = &[dotdot[0], ::std::path::SEP_BYTE]; - let mut path_bytes = Vec::from_slice(p.as_vec()); + let mut path_bytes = p.as_vec().to_vec(); if path_bytes.slice_to(2) != prefix && path_bytes.slice_to(2) != dotdot { @@ -1927,7 +1925,7 @@ impl StructMemberDescriptionFactory { } let field_size = if self.is_simd { - machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields.get(0).mt.ty)) as uint + machine::llsize_of_alloc(cx, type_of::type_of(cx, self.fields[0].mt.ty)) as uint } else { 0xdeadbeef }; @@ -2038,7 +2036,7 @@ fn prepare_tuple_metadata(cx: &CrateContext, UNKNOWN_SCOPE_METADATA), tuple_llvm_type, TupleMDF(TupleMemberDescriptionFactory { - component_types: Vec::from_slice(component_types), + component_types: component_types.to_vec(), span: span, }) ) @@ -2081,7 +2079,7 @@ impl EnumMemberDescriptionFactory { describe_enum_variant(cx, self.enum_type, struct_def, - &**self.variants.get(i), + &*(*self.variants)[i], discriminant_info, self.containing_scope, self.span); @@ -2114,7 +2112,7 @@ impl EnumMemberDescriptionFactory { describe_enum_variant(cx, self.enum_type, struct_def, - &**self.variants.get(0), + &*(*self.variants)[0], NoDiscriminant, self.containing_scope, self.span); @@ -2143,7 +2141,7 @@ impl EnumMemberDescriptionFactory { // DWARF representation of enums uniform. // First create a description of the artificial wrapper struct: - let non_null_variant = self.variants.get(non_null_variant_index as uint); + let non_null_variant = &(*self.variants)[non_null_variant_index as uint]; let non_null_variant_ident = non_null_variant.name; let non_null_variant_name = token::get_ident(non_null_variant_ident); @@ -2160,7 +2158,7 @@ impl EnumMemberDescriptionFactory { // MemberDescription of the struct's single field. let sole_struct_member_description = MemberDescription { name: match non_null_variant.arg_names { - Some(ref names) => token::get_ident(*names.get(0)).get().to_string(), + Some(ref names) => token::get_ident(names[0]).get().to_string(), None => "".to_string() }, llvm_type: non_null_llvm_type, @@ -2190,7 +2188,7 @@ impl EnumMemberDescriptionFactory { // Encode the information about the null variant in the union // member's name. let null_variant_index = (1 - non_null_variant_index) as uint; - let null_variant_ident = self.variants.get(null_variant_index).name; + let null_variant_ident = (*self.variants)[null_variant_index].name; let null_variant_name = token::get_ident(null_variant_ident); let union_member_name = format!("RUST$ENCODED$ENUM${}${}", 0u, @@ -2216,7 +2214,7 @@ impl EnumMemberDescriptionFactory { describe_enum_variant(cx, self.enum_type, struct_def, - &**self.variants.get(nndiscr as uint), + &*(*self.variants)[nndiscr as uint], OptimizedDiscriminant(ptrfield), self.containing_scope, self.span); @@ -2232,7 +2230,7 @@ impl EnumMemberDescriptionFactory { // Encode the information about the null variant in the union // member's name. let null_variant_index = (1 - nndiscr) as uint; - let null_variant_ident = self.variants.get(null_variant_index).name; + let null_variant_ident = (*self.variants)[null_variant_index].name; let null_variant_name = token::get_ident(null_variant_ident); let discrfield = match ptrfield { adt::ThinPointer(field) => format!("{}", field), @@ -2706,14 +2704,14 @@ fn vec_slice_metadata(cx: &CrateContext, let member_descriptions = [ MemberDescription { name: "data_ptr".to_string(), - llvm_type: *member_llvm_types.get(0), + llvm_type: member_llvm_types[0], type_metadata: element_type_metadata, offset: ComputedMemberOffset, flags: FLAGS_NONE }, MemberDescription { name: "length".to_string(), - llvm_type: *member_llvm_types.get(1), + llvm_type: member_llvm_types[1], type_metadata: type_metadata(cx, ty::mk_uint(), span), offset: ComputedMemberOffset, flags: FLAGS_NONE @@ -3081,14 +3079,14 @@ fn bytes_to_bits(bytes: u64) -> u64 { #[inline] fn debug_context<'a>(cx: &'a CrateContext) -> &'a CrateDebugContext { - let debug_context: &'a CrateDebugContext = cx.dbg_cx().get_ref(); + let debug_context: &'a CrateDebugContext = cx.dbg_cx().as_ref().unwrap(); debug_context } #[inline] #[allow(non_snake_case)] fn DIB(cx: &CrateContext) -> DIBuilderRef { - cx.dbg_cx().get_ref().builder + cx.dbg_cx().as_ref().unwrap().builder } fn fn_should_be_ignored(fcx: &FunctionContext) -> bool { @@ -3576,7 +3574,7 @@ fn populate_scope_map(cx: &CrateContext, // same binding names. for arm_ref in arms.iter() { - let arm_span = arm_ref.pats.get(0).span; + let arm_span = arm_ref.pats[0].span; with_new_scope(cx, arm_span, @@ -3671,22 +3669,22 @@ fn push_debuginfo_type_name(cx: &CrateContext, push_type_params(cx, substs, output); }, ty::ty_tup(ref component_types) => { - output.push_char('('); + output.push('('); for &component_type in component_types.iter() { push_debuginfo_type_name(cx, component_type, true, output); output.push_str(", "); } - output.pop_char(); - output.pop_char(); - output.push_char(')'); + output.pop(); + output.pop(); + output.push(')'); }, ty::ty_uniq(inner_type) => { output.push_str("Box<"); push_debuginfo_type_name(cx, inner_type, true, output); - output.push_char('>'); + output.push('>'); }, ty::ty_ptr(ty::mt { ty: inner_type, mutbl } ) => { - output.push_char('*'); + output.push('*'); match mutbl { ast::MutImmutable => output.push_str("const "), ast::MutMutable => output.push_str("mut "), @@ -3695,7 +3693,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, push_debuginfo_type_name(cx, inner_type, true, output); }, ty::ty_rptr(_, ty::mt { ty: inner_type, mutbl }) => { - output.push_char('&'); + output.push('&'); if mutbl == ast::MutMutable { output.push_str("mut "); } @@ -3703,7 +3701,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, push_debuginfo_type_name(cx, inner_type, true, output); }, ty::ty_vec(inner_type, optional_length) => { - output.push_char('['); + output.push('['); push_debuginfo_type_name(cx, inner_type, true, output); match optional_length { @@ -3713,7 +3711,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, None => { /* nothing to do */ } }; - output.push_char(']'); + output.push(']'); }, ty::ty_trait(ref trait_data) => { push_item_name(cx, trait_data.def_id, false, output); @@ -3737,8 +3735,8 @@ fn push_debuginfo_type_name(cx: &CrateContext, push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } - output.pop_char(); - output.pop_char(); + output.pop(); + output.pop(); } if sig.variadic { @@ -3749,7 +3747,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, } } - output.push_char(')'); + output.push(')'); if !ty::type_is_nil(sig.output) { output.push_str(" -> "); @@ -3791,8 +3789,8 @@ fn push_debuginfo_type_name(cx: &CrateContext, push_debuginfo_type_name(cx, parameter_type, true, output); output.push_str(", "); } - output.pop_char(); - output.pop_char(); + output.pop(); + output.pop(); } if sig.variadic { @@ -3803,7 +3801,7 @@ fn push_debuginfo_type_name(cx: &CrateContext, } } - output.push_char(param_list_closing_char); + output.push(param_list_closing_char); if !ty::type_is_nil(sig.output) { output.push_str(" -> "); @@ -3845,8 +3843,8 @@ fn push_debuginfo_type_name(cx: &CrateContext, cx.sess().bug("debuginfo: Encountered empty item path!"); } - output.pop_char(); - output.pop_char(); + output.pop(); + output.pop(); } else { let name = token::get_name(path.last() .expect("debuginfo: Empty item path?") @@ -3868,17 +3866,17 @@ fn push_debuginfo_type_name(cx: &CrateContext, return; } - output.push_char('<'); + output.push('<'); for &type_parameter in substs.types.iter() { push_debuginfo_type_name(cx, type_parameter, true, output); output.push_str(", "); } - output.pop_char(); - output.pop_char(); + output.pop(); + output.pop(); - output.push_char('>'); + output.push('>'); } } @@ -3909,7 +3907,7 @@ impl NamespaceTreeNode { fill_nested(self, &mut name); name.push_str(format!("{}", item_name.len()).as_slice()); name.push_str(item_name); - name.push_char('E'); + name.push('E'); name } } diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index aa00de85890..d638286a9c5 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -1079,7 +1079,7 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ast::ExprMethodCall(_, _, ref args) => { callee::trans_method_call(bcx, expr, - &**args.get(0), + &*args[0], callee::ArgExprs(args.as_slice()), dest) } @@ -1787,7 +1787,7 @@ fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, rhs: Vec<(Datum, ast::NodeId)>, dest: Option) -> Result<'blk, 'tcx> { - let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty; + let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty; callee::trans_call_inner(bcx, Some(expr_info(expr)), monomorphize_type(bcx, method_ty), @@ -1808,11 +1808,10 @@ fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, dest: Option) -> Block<'blk, 'tcx> { let method_call = MethodCall::expr(expr.id); - let method_type = bcx.tcx() - .method_map - .borrow() - .get(&method_call) - .ty; + let method_type = (*bcx.tcx() + .method_map + .borrow())[method_call] + .ty; let mut all_args = vec!(callee); all_args.extend(args.iter().map(|e| &**e)); unpack_result!(bcx, diff --git a/src/librustc/middle/trans/foreign.rs b/src/librustc/middle/trans/foreign.rs index f6373ecc04c..406ccc56a62 100644 --- a/src/librustc/middle/trans/foreign.rs +++ b/src/librustc/middle/trans/foreign.rs @@ -321,8 +321,7 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } // Does Rust pass this argument by pointer? - let rust_indirect = type_of::arg_is_indirect(ccx, - *passed_arg_tys.get(i)); + let rust_indirect = type_of::arg_is_indirect(ccx, passed_arg_tys[i]); debug!("argument {}, llarg_rust={}, rust_indirect={}, arg_ty={}", i, @@ -335,9 +334,9 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, if !rust_indirect { let scratch = base::alloca(bcx, - type_of::type_of(ccx, *passed_arg_tys.get(i)), + type_of::type_of(ccx, passed_arg_tys[i]), "__arg"); - base::store_ty(bcx, llarg_rust, scratch, *passed_arg_tys.get(i)); + base::store_ty(bcx, llarg_rust, scratch, passed_arg_tys[i]); llarg_rust = scratch; } @@ -358,7 +357,7 @@ pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let llarg_foreign = if foreign_indirect { llarg_rust } else { - if ty::type_is_bool(*passed_arg_tys.get(i)) { + if ty::type_is_bool(passed_arg_tys[i]) { let val = LoadRangeAssert(bcx, llarg_rust, 0, 2, llvm::False); Trunc(bcx, val, Type::i1(bcx.ccx())) } else { @@ -746,10 +745,10 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext, // Careful to adapt for cases where the native convention uses // a pointer and Rust does not or vice versa. for i in range(0, tys.fn_sig.inputs.len()) { - let rust_ty = *tys.fn_sig.inputs.get(i); - let llrust_ty = *tys.llsig.llarg_tys.get(i); + let rust_ty = tys.fn_sig.inputs[i]; + let llrust_ty = tys.llsig.llarg_tys[i]; let rust_indirect = type_of::arg_is_indirect(ccx, rust_ty); - let llforeign_arg_ty = *tys.fn_ty.arg_tys.get(i); + let llforeign_arg_ty = tys.fn_ty.arg_tys[i]; let foreign_indirect = llforeign_arg_ty.is_indirect(); if llforeign_arg_ty.is_ignore() { diff --git a/src/librustc/middle/trans/glue.rs b/src/librustc/middle/trans/glue.rs index 5ed619ad295..8fc3426e372 100644 --- a/src/librustc/middle/trans/glue.rs +++ b/src/librustc/middle/trans/glue.rs @@ -262,9 +262,9 @@ fn trans_struct_drop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // use the fake info. info.unwrap_or(C_null(Type::i8p(bcx.ccx()))), GEPi(bcx, scratch.val, [0, abi::slice_elt_len])); - PointerCast(variant_cx, scratch.val, *params.get(0)) + PointerCast(variant_cx, scratch.val, params[0]) } else { - PointerCast(variant_cx, value, *params.get(0)) + PointerCast(variant_cx, value, params[0]) }; let args = vec!(self_arg); diff --git a/src/librustc/middle/trans/intrinsic.rs b/src/librustc/middle/trans/intrinsic.rs index 1dbacf98e53..e81844efad3 100644 --- a/src/librustc/middle/trans/intrinsic.rs +++ b/src/librustc/middle/trans/intrinsic.rs @@ -259,11 +259,11 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N let tp_ty = *substs.types.get(FnSpace, 0); let mode = appropriate_rvalue_mode(ccx, tp_ty); let src = Datum { - val: *llargs.get(1), + val: llargs[1], ty: tp_ty, kind: Rvalue::new(mode) }; - bcx = src.store_to(bcx, *llargs.get(0)); + bcx = src.store_to(bcx, llargs[0]); C_nil(ccx) } (_, "get_tydesc") => { @@ -307,130 +307,130 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N C_bool(ccx, ty::type_contents(ccx.tcx(), tp_ty).owns_managed()) } (_, "offset") => { - let ptr = *llargs.get(0); - let offset = *llargs.get(1); + let ptr = llargs[0]; + let offset = llargs[1]; InBoundsGEP(bcx, ptr, [offset]) } (_, "copy_nonoverlapping_memory") => { copy_intrinsic(bcx, false, false, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "copy_memory") => { copy_intrinsic(bcx, true, false, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "set_memory") => { memset_intrinsic(bcx, false, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "volatile_copy_nonoverlapping_memory") => { copy_intrinsic(bcx, false, true, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "volatile_copy_memory") => { copy_intrinsic(bcx, true, true, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "volatile_set_memory") => { memset_intrinsic(bcx, true, *substs.types.get(FnSpace, 0), - *llargs.get(0), *llargs.get(1), *llargs.get(2)) + llargs[0], llargs[1], llargs[2]) } (_, "volatile_load") => { - VolatileLoad(bcx, *llargs.get(0)) + VolatileLoad(bcx, llargs[0]) }, (_, "volatile_store") => { - VolatileStore(bcx, *llargs.get(1), *llargs.get(0)); + VolatileStore(bcx, llargs[1], llargs[0]); C_nil(ccx) }, - (_, "ctlz8") => count_zeros_intrinsic(bcx, "llvm.ctlz.i8", *llargs.get(0)), - (_, "ctlz16") => count_zeros_intrinsic(bcx, "llvm.ctlz.i16", *llargs.get(0)), - (_, "ctlz32") => count_zeros_intrinsic(bcx, "llvm.ctlz.i32", *llargs.get(0)), - (_, "ctlz64") => count_zeros_intrinsic(bcx, "llvm.ctlz.i64", *llargs.get(0)), - (_, "cttz8") => count_zeros_intrinsic(bcx, "llvm.cttz.i8", *llargs.get(0)), - (_, "cttz16") => count_zeros_intrinsic(bcx, "llvm.cttz.i16", *llargs.get(0)), - (_, "cttz32") => count_zeros_intrinsic(bcx, "llvm.cttz.i32", *llargs.get(0)), - (_, "cttz64") => count_zeros_intrinsic(bcx, "llvm.cttz.i64", *llargs.get(0)), + (_, "ctlz8") => count_zeros_intrinsic(bcx, "llvm.ctlz.i8", llargs[0]), + (_, "ctlz16") => count_zeros_intrinsic(bcx, "llvm.ctlz.i16", llargs[0]), + (_, "ctlz32") => count_zeros_intrinsic(bcx, "llvm.ctlz.i32", llargs[0]), + (_, "ctlz64") => count_zeros_intrinsic(bcx, "llvm.ctlz.i64", llargs[0]), + (_, "cttz8") => count_zeros_intrinsic(bcx, "llvm.cttz.i8", llargs[0]), + (_, "cttz16") => count_zeros_intrinsic(bcx, "llvm.cttz.i16", llargs[0]), + (_, "cttz32") => count_zeros_intrinsic(bcx, "llvm.cttz.i32", llargs[0]), + (_, "cttz64") => count_zeros_intrinsic(bcx, "llvm.cttz.i64", llargs[0]), (_, "i8_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i16_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i32_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i64_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.sadd.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u8_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u16_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u32_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u64_add_with_overflow") => with_overflow_intrinsic(bcx, "llvm.uadd.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i8_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i16_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i32_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i64_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.ssub.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u8_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u16_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u32_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u64_sub_with_overflow") => with_overflow_intrinsic(bcx, "llvm.usub.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i8_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i16_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i32_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "i64_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.smul.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u8_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i8", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u16_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i16", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u32_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i32", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "u64_mul_with_overflow") => with_overflow_intrinsic(bcx, "llvm.umul.with.overflow.i64", ret_ty, - *llargs.get(0), *llargs.get(1)), + llargs[0], llargs[1]), (_, "return_address") => { if !fcx.caller_expects_out_pointer { @@ -452,7 +452,7 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N let order = if split.len() == 2 { llvm::SequentiallyConsistent } else { - match *split.get(2) { + match split[2] { "relaxed" => llvm::Monotonic, "acq" => llvm::Acquire, "rel" => llvm::Release, @@ -461,7 +461,7 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N } }; - match *split.get(1) { + match split[1] { "cxchg" => { // See include/llvm/IR/Instructions.h for their implementation // of this, I assume that it's good enough for us to use for @@ -480,8 +480,8 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N llvm::SequentiallyConsistent }; - let res = AtomicCmpXchg(bcx, *llargs.get(0), *llargs.get(1), - *llargs.get(2), order, + let res = AtomicCmpXchg(bcx, llargs[0], llargs[1], + llargs[2], order, strongest_failure_ordering); if unsafe { llvm::LLVMVersionMinor() >= 5 } { ExtractValue(bcx, res, 0) @@ -491,10 +491,10 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N } "load" => { - AtomicLoad(bcx, *llargs.get(0), order) + AtomicLoad(bcx, llargs[0], order) } "store" => { - AtomicStore(bcx, *llargs.get(1), *llargs.get(0), order); + AtomicStore(bcx, llargs[1], llargs[0], order); C_nil(ccx) } @@ -520,7 +520,7 @@ pub fn trans_intrinsic_call<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, node: ast::N _ => ccx.sess().fatal("unknown atomic operation") }; - AtomicRMW(bcx, atom_op, *llargs.get(0), *llargs.get(1), order) + AtomicRMW(bcx, atom_op, llargs[0], llargs[1], order) } } diff --git a/src/librustc/middle/trans/meth.rs b/src/librustc/middle/trans/meth.rs index b0ce5a21464..fef2ead9883 100644 --- a/src/librustc/middle/trans/meth.rs +++ b/src/librustc/middle/trans/meth.rs @@ -718,7 +718,7 @@ fn emit_vtable_methods(bcx: Block, debug!("(making impl vtable) method has self or type \ params: {}", token::get_ident(ident)); - Some(C_null(Type::nil(ccx).ptr_to())).move_iter() + Some(C_null(Type::nil(ccx).ptr_to())).into_iter() } else { let mut fn_ref = trans_fn_ref_with_substs( bcx, @@ -732,11 +732,11 @@ fn emit_vtable_methods(bcx: Block, m_id, substs.clone()); } - Some(fn_ref).move_iter() + Some(fn_ref).into_iter() } } ty::TypeTraitItem(_) => { - None.move_iter() + None.into_iter() } } }).collect() diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 0a5691541f1..dbaebd07b02 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -2042,7 +2042,7 @@ pub fn simd_type(cx: &ctxt, ty: t) -> t { match get(ty).sty { ty_struct(did, ref substs) => { let fields = lookup_struct_fields(cx, did); - lookup_field_type(cx, did, fields.get(0).id, substs) + lookup_field_type(cx, did, fields[0].id, substs) } _ => fail!("simd_type called on invalid type") } @@ -2501,12 +2501,12 @@ pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents { if variants.len() == 2 { let mut data_idx = 0; - if variants.get(0).args.len() == 0 { + if variants[0].args.len() == 0 { data_idx = 1; } - if variants.get(data_idx).args.len() == 1 { - match get(*variants.get(data_idx).args.get(0)).sty { + if variants[data_idx].args.len() == 1 { + match get(variants[data_idx].args[0]).sty { ty_bare_fn(..) => { res = res - TC::ReachesFfiUnsafe; } _ => { } } @@ -2530,7 +2530,7 @@ pub fn type_contents(cx: &ctxt, ty: t) -> TypeContents { assert_eq!(p.def_id.krate, ast::LOCAL_CRATE); let ty_param_defs = cx.ty_param_defs.borrow(); - let tp_def = ty_param_defs.get(&p.def_id.node); + let tp_def = &(*ty_param_defs)[p.def_id.node]; kind_bounds_to_contents( cx, tp_def.bounds.builtin_bounds, @@ -4032,8 +4032,7 @@ fn lookup_locally_or_in_crate_store( pub fn trait_item(cx: &ctxt, trait_did: ast::DefId, idx: uint) -> ImplOrTraitItem { - let method_def_id = ty::trait_item_def_ids(cx, trait_did).get(idx) - .def_id(); + let method_def_id = (*ty::trait_item_def_ids(cx, trait_did))[idx].def_id(); impl_or_trait_item(cx, method_def_id) } diff --git a/src/librustc/middle/typeck/astconv.rs b/src/librustc/middle/typeck/astconv.rs index 0e9d255adf9..d29720e1a1a 100644 --- a/src/librustc/middle/typeck/astconv.rs +++ b/src/librustc/middle/typeck/astconv.rs @@ -156,7 +156,7 @@ pub fn opt_ast_region_to_region<'tcx, AC: AstConv<'tcx>, RS: RegionScope>( Some(v) => { let mut m = String::new(); let len = v.len(); - for (i, (name, n)) in v.move_iter().enumerate() { + for (i, (name, n)) in v.into_iter().enumerate() { m.push_str(if n == 1 { format!("`{}`", name) } else { @@ -194,9 +194,7 @@ pub fn opt_ast_region_to_region<'tcx, AC: AstConv<'tcx>, RS: RegionScope>( ty::ReStatic } - Ok(rs) => { - *rs.get(0) - } + Ok(rs) => rs[0], } } }; @@ -1251,7 +1249,7 @@ fn determine_explicit_self_category<'tcx, AC: AstConv<'tcx>, self_info.explicit_self.span, self_info.untransformed_self_ty, tm.ty, - || "not a valid type for `self`".to_owned()); + || "not a valid type for `self`".to_string()); return ty::ByReferenceExplicitSelfCategory(region, tm.mutbl) } @@ -1263,7 +1261,7 @@ fn determine_explicit_self_category<'tcx, AC: AstConv<'tcx>, self_info.explicit_self.span, self_info.untransformed_self_ty, typ, - || "not a valid type for `self`".to_owned()); + || "not a valid type for `self`".to_string()); return ty::ByBoxExplicitSelfCategory } _ => { @@ -1301,7 +1299,7 @@ pub fn ty_of_closure<'tcx, AC: AstConv<'tcx>>( // no guarantee that the correct number of expected args // were supplied if i < e.inputs.len() { - Some(*e.inputs.get(i)) + Some(e.inputs[i]) } else { None } @@ -1357,7 +1355,7 @@ pub fn conv_existential_bounds<'tcx, AC: AstConv<'tcx>, RS:RegionScope>( partition_bounds(this.tcx(), span, ast_bound_refs.as_slice()); if !trait_bounds.is_empty() { - let b = trait_bounds.get(0); + let b = &trait_bounds[0]; this.tcx().sess.span_err( b.path.span, format!("only the builtin traits can be used \ @@ -1453,7 +1451,7 @@ pub fn compute_opt_region_bound(tcx: &ty::ctxt, // Determine whether there is exactly one unique region in the set // of derived region bounds. If so, use that. Otherwise, report an // error. - let r = *derived_region_bounds.get(0); + let r = derived_region_bounds[0]; if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) { tcx.sess.span_err( span, diff --git a/src/librustc/middle/typeck/check/_match.rs b/src/librustc/middle/typeck/check/_match.rs index 9463bafc9d2..455300ecd3b 100644 --- a/src/librustc/middle/typeck/check/_match.rs +++ b/src/librustc/middle/typeck/check/_match.rs @@ -45,7 +45,7 @@ pub fn check_match(fcx: &FnCtxt, for arm in arms.iter() { let mut pcx = pat_ctxt { fcx: fcx, - map: pat_id_map(&tcx.def_map, &**arm.pats.get(0)), + map: pat_id_map(&tcx.def_map, &*arm.pats[0]), }; for p in arm.pats.iter() { check_pat(&mut pcx, &**p, discrim_ty);} @@ -322,7 +322,7 @@ pub fn check_struct_pat_fields(pcx: &pat_ctxt, } Some(&(index, ref mut used)) => { *used = true; - let class_field = class_fields.get(index).clone(); + let class_field = class_fields[index].clone(); let field_type = ty::lookup_field_type(tcx, class_id, class_field.id, @@ -496,7 +496,7 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { } } - let canon_id = *pcx.map.get(&path1.node); + let canon_id = pcx.map[path1.node]; if canon_id != pat.id { let ct = fcx.local_ty(pat.span, canon_id); demand::eqtype(fcx, pat.span, ct, typ); @@ -528,7 +528,7 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { match *structure { ty::ty_struct(cid, ref substs) => { // Verify that the pattern named the right structure. - let item_did = tcx.def_map.borrow().get(&pat.id).def_id(); + let item_did = (*tcx.def_map.borrow())[pat.id].def_id(); match ty::ty_to_def_id(ty::lookup_item_type(tcx, item_did).ty) { Some(struct_did) if struct_did != cid => { span_err!(tcx.sess, path.span, E0032, @@ -599,7 +599,7 @@ pub fn check_pat(pcx: &pat_ctxt, pat: &ast::Pat, expected: ty::t) { match *s { ty::ty_tup(ref ex_elts) if e_count == ex_elts.len() => { for (i, elt) in elts.iter().enumerate() { - check_pat(pcx, &**elt, *ex_elts.get(i)); + check_pat(pcx, &**elt, ex_elts[i]); } fcx.write_ty(pat.id, expected); } diff --git a/src/librustc/middle/typeck/check/method.rs b/src/librustc/middle/typeck/check/method.rs index c2e7be2781f..798e4acd291 100644 --- a/src/librustc/middle/typeck/check/method.rs +++ b/src/librustc/middle/typeck/check/method.rs @@ -276,7 +276,7 @@ fn construct_transformed_self_ty_for_object( ty::mk_uniq(tcx, tr) } ByReferenceExplicitSelfCategory(..) | ByBoxExplicitSelfCategory => { - let transformed_self_ty = *method_ty.fty.sig.inputs.get(0); + let transformed_self_ty = method_ty.fty.sig.inputs[0]; match ty::get(transformed_self_ty).sty { ty::ty_rptr(r, mt) => { // must be SelfRegion let r = r.subst(tcx, rcvr_substs); // handle Early-Bound lifetime @@ -490,7 +490,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { let impl_items = self.tcx().impl_items.borrow(); for impl_infos in self.tcx().trait_impls.borrow().find(&trait_did).iter() { for impl_did in impl_infos.borrow().iter() { - let items = impl_items.get(impl_did); + let items = &(*impl_items)[*impl_did]; self.push_candidates_from_impl(*impl_did, items.as_slice(), true); @@ -521,7 +521,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { trait_did: DefId, closure_did: DefId, closure_function_type: &ClosureTy) { - let trait_item = ty::trait_items(self.tcx(), trait_did).get(0) + let trait_item = (*ty::trait_items(self.tcx(), trait_did))[0] .clone(); let method = match trait_item { ty::MethodTraitItem(method) => method, @@ -538,7 +538,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { } // Get the tupled type of the arguments. - let arguments_type = *closure_function_type.sig.inputs.get(0); + let arguments_type = closure_function_type.sig.inputs[0]; let return_type = closure_function_type.sig.output; let closure_region = @@ -552,7 +552,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { rcvr_substs: subst::Substs::new_trait( vec![arguments_type, return_type], vec![], - *self.fcx.infcx().next_ty_vars(1).get(0)), + self.fcx.infcx().next_ty_vars(1)[0]), method_ty: method, origin: MethodStaticUnboxedClosure(closure_did), }); @@ -733,7 +733,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { } }) { Some(pos) => { - let method = match *trait_items.get(pos) { + let method = match (*trait_items)[pos] { ty::MethodTraitItem(ref method) => (*method).clone(), ty::TypeTraitItem(_) => { tcx.sess.bug("typechecking associated type as \ @@ -771,7 +771,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { let impl_items = self.tcx().impl_items.borrow(); for impl_infos in self.tcx().inherent_impls.borrow().find(&did).iter() { for impl_did in impl_infos.iter() { - let items = impl_items.get(impl_did); + let items = &(*impl_items)[*impl_did]; self.push_candidates_from_impl(*impl_did, items.as_slice(), false); @@ -1211,7 +1211,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { // return something so we don't get errors for every mutability return Some(MethodCallee { - origin: relevant_candidates.get(0).origin.clone(), + origin: relevant_candidates[0].origin.clone(), ty: ty::mk_err(), substs: subst::Substs::empty() }); @@ -1225,7 +1225,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { } } - Some(self.confirm_candidate(rcvr_ty, relevant_candidates.get(0))) + Some(self.confirm_candidate(rcvr_ty, &relevant_candidates[0])) } fn filter_candidates(&self, rcvr_ty: ty::t, candidates: &[Candidate]) -> Vec { @@ -1299,7 +1299,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { "incorrect number of type parameters given for this method"); self.fcx.infcx().next_ty_vars(num_method_tps) } else { - Vec::from_slice(self.supplied_tps) + self.supplied_tps.to_vec() } }; @@ -1329,7 +1329,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { let args = fn_sig.inputs.slice_from(1).iter().map(|t| { t.subst(tcx, &all_substs) }); - Some(*fn_sig.inputs.get(0)).into_iter().chain(args).collect() + Some(fn_sig.inputs[0]).into_iter().chain(args).collect() } _ => fn_sig.inputs.subst(tcx, &all_substs) }; @@ -1348,7 +1348,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { tcx, &fn_sig, |br| self.fcx.infcx().next_region_var( infer::LateBoundRegion(self.span, br))); - let transformed_self_ty = *fn_sig.inputs.get(0); + let transformed_self_ty = fn_sig.inputs[0]; let fty = ty::mk_bare_fn(tcx, ty::BareFnTy { sig: fn_sig, fn_style: bare_fn_ty.fn_style, @@ -1394,7 +1394,7 @@ impl<'a, 'tcx> LookupContext<'a, 'tcx> { _ => return, }; - match ty::get(*sig.inputs.get(0)).sty { + match ty::get(sig.inputs[0]).sty { ty::ty_rptr(_, ty::mt { ty: _, mutbl: ast::MutMutable, diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index a9c4317b9ee..4aea9cfa293 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -1056,8 +1056,8 @@ fn compare_impl_method(tcx: &ty::ctxt, let trait_to_skol_substs = trait_to_impl_substs .subst(tcx, &impl_to_skol_substs) - .with_method(Vec::from_slice(skol_tps.get_slice(subst::FnSpace)), - Vec::from_slice(skol_regions.get_slice(subst::FnSpace))); + .with_method(skol_tps.get_slice(subst::FnSpace).to_vec(), + skol_regions.get_slice(subst::FnSpace).to_vec()); // Check region bounds. if !check_region_bounds_on_impl_method(tcx, @@ -2598,7 +2598,7 @@ fn check_argument_types<'a>(fcx: &FnCtxt, if is_block == check_blocks { debug!("checking the argument"); - let mut formal_ty = *formal_tys.get(i); + let mut formal_ty = formal_tys[i]; match deref_args { DoDerefArgs => { @@ -3301,7 +3301,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, fcx.ccx.tcx.sess.span_bug(expr.span, "can't make anon regions here?!") } - Ok(regions) => *regions.get(0), + Ok(regions) => regions[0], }; let closure_type = ty::mk_unboxed_closure(fcx.ccx.tcx, local_def(expr.id), @@ -3643,7 +3643,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, let mut missing_fields = Vec::new(); for class_field in field_types.iter() { let name = class_field.name; - let (_, seen) = *class_field_map.get(&name); + let (_, seen) = class_field_map[name]; if !seen { missing_fields.push( format!("`{}`", token::get_name(name).get())) @@ -3871,7 +3871,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, ty::ty_struct(did, ref substs) => { let fields = ty::struct_fields(fcx.tcx(), did, substs); fields.len() == 1 - && fields.get(0).ident == + && fields[0].ident == token::special_idents::unnamed_field } _ => false @@ -4258,7 +4258,7 @@ fn check_expr_with_unifier(fcx: &FnCtxt, let elt_ts = elts.iter().enumerate().map(|(i, e)| { let t = match flds { Some(ref fs) if i < fs.len() => { - let ety = *fs.get(i); + let ety = fs[i]; check_expr_coercable_to_type(fcx, &**e, ety); ety } @@ -4763,7 +4763,7 @@ pub fn check_const(ccx: &CrateCtxt, let inh = static_inherited_fields(ccx); let rty = ty::node_id_to_type(ccx.tcx, id); let fcx = blank_fn_ctxt(ccx, &inh, rty, e.id); - let declty = fcx.ccx.tcx.tcache.borrow().get(&local_def(id)).ty; + let declty = (*fcx.ccx.tcx.tcache.borrow())[local_def(id)].ty; check_const_with_ty(&fcx, sp, e, declty); } @@ -4853,7 +4853,7 @@ pub fn check_simd(tcx: &ty::ctxt, sp: Span, id: ast::NodeId) { span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty"); return; } - let e = ty::lookup_field_type(tcx, did, fields.get(0).id, substs); + let e = ty::lookup_field_type(tcx, did, fields[0].id, substs); if !fields.iter().all( |f| ty::lookup_field_type(tcx, did, f.id, substs) == e) { span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous"); @@ -5514,7 +5514,7 @@ pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &ast::ForeignItem) { assert!(split.len() >= 2, "Atomic intrinsic not correct format"); //We only care about the operation here - match *split.get(1) { + match split[1] { "cxchg" => (1, vec!(ty::mk_mut_ptr(tcx, param(ccx, 0)), param(ccx, 0), param(ccx, 0)), diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index b595b9b84ae..76074120c0e 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -641,7 +641,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { } ast::ExprMethodCall(_, _, ref args) => { - constrain_call(rcx, expr, Some(&**args.get(0)), + constrain_call(rcx, expr, Some(&*args[0]), args.slice_from(1).iter().map(|e| &**e), false); visit::walk_expr(rcx, expr); @@ -1200,7 +1200,7 @@ fn constrain_autoderefs(rcx: &mut Rcx, // Treat overloaded autoderefs as if an AutoRef adjustment // was applied on the base type, as that is always the case. let fn_sig = ty::ty_fn_sig(method.ty); - let self_ty = *fn_sig.inputs.get(0); + let self_ty = fn_sig.inputs[0]; let (m, r) = match ty::get(self_ty).sty { ty::ty_rptr(r, ref m) => (m.mutbl, r), _ => rcx.tcx().sess.span_bug(deref_expr.span, diff --git a/src/librustc/middle/typeck/coherence/mod.rs b/src/librustc/middle/typeck/coherence/mod.rs index eef466ceebb..7906e0101ee 100644 --- a/src/librustc/middle/typeck/coherence/mod.rs +++ b/src/librustc/middle/typeck/coherence/mod.rs @@ -434,12 +434,12 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { }; for &impl_did in trait_impls.borrow().iter() { - let items = impl_items.get(&impl_did); + let items = &(*impl_items)[impl_did]; if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; } - let method_def_id = *items.get(0); + let method_def_id = items[0]; let self_type = self.get_self_type_for_implementation(impl_did); match ty::get(self_type.ty).sty { @@ -524,10 +524,10 @@ fn subst_receiver_types_in_method_ty(tcx: &ty::ctxt, for &space in [subst::TypeSpace, subst::SelfSpace].iter() { method_generics.types.replace( space, - Vec::from_slice(impl_poly_type.generics.types.get_slice(space))); + impl_poly_type.generics.types.get_slice(space).to_vec()); method_generics.regions.replace( space, - Vec::from_slice(impl_poly_type.generics.regions.get_slice(space))); + impl_poly_type.generics.regions.get_slice(space).to_vec()); } debug!("subst_receiver_types_in_method_ty: method_generics={}", diff --git a/src/librustc/middle/typeck/collect.rs b/src/librustc/middle/typeck/collect.rs index 8e4948bbea9..2ffb90861bf 100644 --- a/src/librustc/middle/typeck/collect.rs +++ b/src/librustc/middle/typeck/collect.rs @@ -1298,11 +1298,11 @@ pub fn convert_struct(ccx: &CrateCtxt, write_ty_to_tcx(tcx, ctor_id, selfty); tcx.tcache.borrow_mut().insert(local_def(ctor_id), pty); - } else if struct_def.fields.get(0).node.kind.is_unnamed() { + } else if struct_def.fields[0].node.kind.is_unnamed() { // Tuple-like. let inputs: Vec<_> = struct_def.fields.iter().map( - |field| tcx.tcache.borrow().get( - &local_def(field.node.id)).ty).collect(); + |field| (*tcx.tcache.borrow())[ + local_def(field.node.id)].ty).collect(); let ctor_fn_ty = ty::mk_ctor_fn(tcx, ctor_id, inputs.as_slice(), @@ -2124,8 +2124,8 @@ fn conv_param_bounds<'tcx,AC>(this: &AC, unboxed_fn_ty_bounds } = astconv::partition_bounds(this.tcx(), span, all_bounds.as_slice()); - let unboxed_fn_ty_bounds = unboxed_fn_ty_bounds.move_iter().map(|b| { - let trait_id = this.tcx().def_map.borrow().get(&b.ref_id).def_id(); + let unboxed_fn_ty_bounds = unboxed_fn_ty_bounds.into_iter().map(|b| { + let trait_id = (*this.tcx().def_map.borrow())[b.ref_id].def_id(); let mut kind = None; for &(lang_item, this_kind) in [ (this.tcx().lang_items.fn_trait(), ast::FnUnboxedClosureKind), @@ -2170,7 +2170,7 @@ fn conv_param_bounds<'tcx,AC>(this: &AC, .chain(unboxed_fn_ty_bounds) .collect(); let region_bounds: Vec = - region_bounds.move_iter() + region_bounds.into_iter() .map(|r| ast_region_to_region(this.tcx(), r)) .collect(); ty::ParamBounds { diff --git a/src/librustc/middle/typeck/infer/combine.rs b/src/librustc/middle/typeck/infer/combine.rs index 8ae0b603e48..15c4830646d 100644 --- a/src/librustc/middle/typeck/infer/combine.rs +++ b/src/librustc/middle/typeck/infer/combine.rs @@ -52,7 +52,6 @@ use middle::typeck::infer::type_variable::{RelationDir, EqTo, use middle::ty_fold::{TypeFoldable}; use util::ppaux::Repr; -use std::result; use syntax::ast::{Onceness, FnStyle}; use syntax::ast; @@ -89,11 +88,10 @@ pub trait Combine<'tcx> { bs.len()))); } - try!(result::fold_(as_ - .iter() - .zip(bs.iter()) - .map(|(a, b)| self.equate().tys(*a, *b)))); - Ok(Vec::from_slice(as_)) + try!(as_.iter().zip(bs.iter()) + .map(|(a, b)| self.equate().tys(*a, *b)) + .collect::>>()); + Ok(as_.to_vec()) } fn substs(&self, @@ -342,8 +340,8 @@ pub fn super_fn_sigs<'tcx, C: Combine<'tcx>>(this: &C, b_args: &[ty::t]) -> cres> { if a_args.len() == b_args.len() { - result::collect(a_args.iter().zip(b_args.iter()) - .map(|(a, b)| this.args(*a, *b))) + a_args.iter().zip(b_args.iter()) + .map(|(a, b)| this.args(*a, *b)).collect() } else { Err(ty::terr_arg_count) } @@ -537,9 +535,10 @@ pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C, a: ty::t, b: ty::t) -> cres { if as_.len() == bs.len() { - result::collect(as_.iter().zip(bs.iter()) - .map(|(a, b)| this.tys(*a, *b))) - .and_then(|ts| Ok(ty::mk_tup(tcx, ts)) ) + as_.iter().zip(bs.iter()) + .map(|(a, b)| this.tys(*a, *b)) + .collect::>() + .map(|ts| ty::mk_tup(tcx, ts)) } else { Err(ty::terr_tuple_size( expected_found(this, as_.len(), bs.len()))) diff --git a/src/librustc/middle/typeck/infer/error_reporting.rs b/src/librustc/middle/typeck/infer/error_reporting.rs index 56f06d7f99c..c3ed70f4cb7 100644 --- a/src/librustc/middle/typeck/infer/error_reporting.rs +++ b/src/librustc/middle/typeck/infer/error_reporting.rs @@ -256,7 +256,7 @@ impl<'a, 'tcx> ErrorReporting for InferCtxt<'a, 'tcx> { } } if !same_regions.is_empty() { - let common_scope_id = same_regions.get(0).scope_id; + let common_scope_id = same_regions[0].scope_id; for sr in same_regions.iter() { // Since ProcessedErrors is used to reconstruct the function // declaration, we want to make sure that they are, in fact, @@ -1003,7 +1003,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { names.push(lt_name); } names.sort(); - let name = token::str_to_ident(names.get(0).as_slice()).name; + let name = token::str_to_ident(names[0].as_slice()).name; return (name_to_dummy_lifetime(name), Kept); } return (self.life_giver.give_lifetime(), Fresh); @@ -1209,7 +1209,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> { let mut new_ty = P(ty.clone()); let mut ty_queue = vec!(ty); while !ty_queue.is_empty() { - let cur_ty = ty_queue.shift().unwrap(); + let cur_ty = ty_queue.remove(0).unwrap(); match cur_ty.node { ast::TyRptr(lt_opt, ref mut_ty) => { let rebuild = match lt_opt { @@ -1768,7 +1768,7 @@ impl LifeGiver { let (n, r) = (counter/26 + 1, counter % 26); let letter: char = from_u32((r+97) as u32).unwrap(); for _ in range(0, n) { - s.push_char(letter); + s.push(letter); } s } diff --git a/src/librustc/middle/typeck/infer/region_inference/mod.rs b/src/librustc/middle/typeck/infer/region_inference/mod.rs index 504550f0d40..b4704b2a27c 100644 --- a/src/librustc/middle/typeck/infer/region_inference/mod.rs +++ b/src/librustc/middle/typeck/infer/region_inference/mod.rs @@ -255,7 +255,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { pub fn commit(&self, snapshot: RegionSnapshot) { debug!("RegionVarBindings: commit({})", snapshot.length); assert!(self.undo_log.borrow().len() > snapshot.length); - assert!(*self.undo_log.borrow().get(snapshot.length) == OpenSnapshot); + assert!((*self.undo_log.borrow())[snapshot.length] == OpenSnapshot); let mut undo_log = self.undo_log.borrow_mut(); if snapshot.length == 0 { @@ -269,7 +269,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { debug!("RegionVarBindings: rollback_to({})", snapshot); let mut undo_log = self.undo_log.borrow_mut(); assert!(undo_log.len() > snapshot.length); - assert!(*undo_log.get(snapshot.length) == OpenSnapshot); + assert!((*undo_log)[snapshot.length] == OpenSnapshot); while undo_log.len() > snapshot.length + 1 { match undo_log.pop().unwrap() { OpenSnapshot => { @@ -529,7 +529,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { match *self.values.borrow() { None => { self.tcx.sess.span_bug( - self.var_origins.borrow().get(rid.index).span(), + (*self.var_origins.borrow())[rid.index].span(), "attempt to resolve region variable before values have \ been computed!") } @@ -608,7 +608,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { let mut result_index = 0; while result_index < result_set.len() { // nb: can't use uint::range() here because result_set grows - let r = *result_set.get(result_index); + let r = result_set[result_index]; debug!("result_index={}, r={}", result_index, r); for undo_entry in @@ -636,13 +636,13 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { ReFree(a), ReInfer(ReVar(b))); } &AddVerify(i) => { - match self.verifys.borrow().get(i) { - &VerifyRegSubReg(_, a, b) => { + match (*self.verifys.borrow())[i] { + VerifyRegSubReg(_, a, b) => { consider_adding_bidirectional_edges( &mut result_set, r, a, b); } - &VerifyParamBound(_, _, a, ref bs) => { + VerifyParamBound(_, _, a, ref bs) => { for &b in bs.iter() { consider_adding_bidirectional_edges( &mut result_set, r, @@ -727,7 +727,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => { self.tcx.sess.span_bug( - self.var_origins.borrow().get(v_id.index).span(), + (*self.var_origins.borrow())[v_id.index].span(), format!("lub_concrete_regions invoked with \ non-concrete regions: {}, {}", a, @@ -834,7 +834,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { (ReInfer(ReVar(v_id)), _) | (_, ReInfer(ReVar(v_id))) => { self.tcx.sess.span_bug( - self.var_origins.borrow().get(v_id.index).span(), + (*self.var_origins.borrow())[v_id.index].span(), format!("glb_concrete_regions invoked with \ non-concrete regions: {}, {}", a, @@ -1269,7 +1269,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { if opt_graph.is_none() { opt_graph = Some(self.construct_graph()); } - let graph = opt_graph.get_ref(); + let graph = opt_graph.as_ref().unwrap(); let node_vid = RegionVid { index: idx }; match var_data[idx].classification { @@ -1370,7 +1370,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { if !self.is_subregion_of(lower_bound.region, upper_bound.region) { errors.push(SubSupConflict( - self.var_origins.borrow().get(node_idx.index).clone(), + (*self.var_origins.borrow())[node_idx.index].clone(), lower_bound.origin.clone(), lower_bound.region, upper_bound.origin.clone(), @@ -1381,7 +1381,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } self.tcx.sess.span_bug( - self.var_origins.borrow().get(node_idx.index).span(), + (*self.var_origins.borrow())[node_idx.index].span(), format!("collect_error_for_expanding_node() could not find error \ for var {}, lower_bounds={}, upper_bounds={}", node_idx, @@ -1414,7 +1414,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { Ok(_) => {} Err(_) => { errors.push(SupSupConflict( - self.var_origins.borrow().get(node_idx.index).clone(), + (*self.var_origins.borrow())[node_idx.index].clone(), upper_bound_1.origin.clone(), upper_bound_1.region, upper_bound_2.origin.clone(), @@ -1426,7 +1426,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } self.tcx.sess.span_bug( - self.var_origins.borrow().get(node_idx.index).span(), + (*self.var_origins.borrow())[node_idx.index].span(), format!("collect_error_for_contracting_node() could not find error \ for var {}, upper_bounds={}", node_idx, @@ -1578,7 +1578,7 @@ fn normalize(values: &Vec, r: ty::Region) -> ty::Region { } fn lookup(values: &Vec, rid: ty::RegionVid) -> ty::Region { - match *values.get(rid.index) { + match values[rid.index] { Value(r) => r, NoValue => ReEmpty, // No constraints, return ty::ReEmpty ErrorValue => ReStatic, // Previously reported error. diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index dd6e087b672..20e550f3f30 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -657,7 +657,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { // variance not yet inferred, so return a symbolic // variance. let InferredIndex(index) = self.inferred_index(param_def_id.node); - self.terms_cx.inferred_infos.get(index).term + self.terms_cx.inferred_infos[index].term } else { // Parameter on an item defined within another crate: // variance already inferred, just look it up. @@ -980,15 +980,14 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { let Constraint { inferred, variance: term } = *constraint; let InferredIndex(inferred) = inferred; let variance = self.evaluate(term); - let old_value = *self.solutions.get(inferred); + let old_value = self.solutions[inferred]; let new_value = glb(variance, old_value); if old_value != new_value { debug!("Updating inferred {} (node {}) \ from {} to {} due to {}", inferred, self.terms_cx - .inferred_infos - .get(inferred) + .inferred_infos[inferred] .param_id, old_value, new_value, @@ -1017,14 +1016,14 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { let mut index = 0; let num_inferred = self.terms_cx.num_inferred(); while index < num_inferred { - let item_id = inferred_infos.get(index).item_id; + let item_id = inferred_infos[index].item_id; let mut types = VecPerParamSpace::empty(); let mut regions = VecPerParamSpace::empty(); while index < num_inferred && - inferred_infos.get(index).item_id == item_id { - let info = inferred_infos.get(index); - let variance = *solutions.get(index); + inferred_infos[index].item_id == item_id { + let info = inferred_infos[index]; + let variance = solutions[index]; debug!("Index {} Info {} / {} / {} Variance {}", index, info.index, info.kind, info.space, variance); match info.kind { @@ -1074,7 +1073,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { } InferredTerm(InferredIndex(index)) => { - *self.solutions.get(index) + self.solutions[index] } } } diff --git a/src/librustc/plugin/load.rs b/src/librustc/plugin/load.rs index ecbe3409139..921cd7a4107 100644 --- a/src/librustc/plugin/load.rs +++ b/src/librustc/plugin/load.rs @@ -77,8 +77,8 @@ pub fn load_plugins(sess: &Session, krate: &ast::Crate, Some(addl_plugins) => { // Add in the additional plugins requested by the frontend let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins; - plugins.macros.push_all_move(addl_macros); - plugins.registrars.push_all_move(addl_registrars); + plugins.macros.extend(addl_macros.into_iter()); + plugins.registrars.extend(addl_registrars.into_iter()); } None => () } diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 082dde978d8..ed38f6f871d 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -139,7 +139,7 @@ pub fn can_reach,T:Eq+Clone+Hash>( let mut queue = vec!(source); let mut i = 0; while i < queue.len() { - match edges_map.find(queue.get(i)) { + match edges_map.find(&queue[i]) { Some(edges) => { for target in edges.iter() { if *target == destination { diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 085295cad7d..a20a988c881 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -270,7 +270,7 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { ast::NormalFn => {} _ => { s.push_str(fn_style.to_string().as_slice()); - s.push_char(' '); + s.push(' '); } }; @@ -282,7 +282,7 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { match ident { Some(i) => { - s.push_char(' '); + s.push(' '); s.push_str(token::get_ident(i).get()); } _ => { } @@ -307,7 +307,7 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { ast::NormalFn => {} _ => { s.push_str(cty.fn_style.to_string().as_slice()); - s.push_char(' '); + s.push(' '); } }; @@ -330,7 +330,7 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { } } - s.into_owned() + s } fn push_sig_to_string(cx: &ctxt, @@ -339,13 +339,13 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { ket: char, sig: &ty::FnSig, bounds: &str) { - s.push_char(bra); + s.push(bra); let strs: Vec = sig.inputs.iter().map(|a| fn_input_to_string(cx, *a)).collect(); s.push_str(strs.connect(", ").as_slice()); if sig.variadic { s.push_str(", ..."); } - s.push_char(ket); + s.push(ket); if !bounds.is_empty() { s.push_str(":"); @@ -355,7 +355,7 @@ pub fn ty_to_string(cx: &ctxt, typ: t) -> String { if ty::get(sig.output).sty != ty_nil { s.push_str(" -> "); if ty::type_is_bot(sig.output) { - s.push_char('!'); + s.push('!'); } else { s.push_str(ty_to_string(cx, sig.output).as_slice()); } @@ -670,10 +670,10 @@ impl Repr for ty::BuiltinBounds { let mut res = Vec::new(); for b in self.iter() { res.push(match b { - ty::BoundSend => "Send".to_owned(), - ty::BoundSized => "Sized".to_owned(), - ty::BoundCopy => "Copy".to_owned(), - ty::BoundSync => "Sync".to_owned(), + ty::BoundSend => "Send".to_string(), + ty::BoundSized => "Sized".to_string(), + ty::BoundCopy => "Copy".to_string(), + ty::BoundSync => "Sync".to_string(), }); } res.connect("+") @@ -1007,10 +1007,10 @@ impl Repr for ty::BuiltinBound { impl UserString for ty::BuiltinBound { fn user_string(&self, _tcx: &ctxt) -> String { match *self { - ty::BoundSend => "Send".to_owned(), - ty::BoundSized => "Sized".to_owned(), - ty::BoundCopy => "Copy".to_owned(), - ty::BoundSync => "Sync".to_owned(), + ty::BoundSend => "Send".to_string(), + ty::BoundSized => "Sized".to_string(), + ty::BoundCopy => "Copy".to_string(), + ty::BoundSync => "Sync".to_string(), } } } diff --git a/src/librustc/util/snapshot_vec.rs b/src/librustc/util/snapshot_vec.rs index 03e1559cba2..7a7c8f8d94f 100644 --- a/src/librustc/util/snapshot_vec.rs +++ b/src/librustc/util/snapshot_vec.rs @@ -94,7 +94,7 @@ impl> SnapshotVec { } pub fn get<'a>(&'a self, index: uint) -> &'a T { - self.values.get(index) + &self.values[index] } pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T { @@ -133,7 +133,7 @@ impl> SnapshotVec { // Invariant established by start_snapshot(): assert!( - match *self.undo_log.get(snapshot.length) { + match self.undo_log[snapshot.length] { OpenSnapshot => true, _ => false }); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 02ba4aabc99..ca8a6cd0c40 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -708,9 +708,11 @@ impl fmt::Show for ModuleSummary { let path = context.connect("::"); try!(write!(f, "")); - try!(write!(f, "{}", - Vec::from_slice(context.slice_from(1)) - .append_one("index.html").connect("/"), + try!(write!(f, "{}", { + let mut url = context.slice_from(1).to_vec(); + url.push("index.html"); + url.connect("/") + }, path)); try!(write!(f, "")); try!(write!(f, " fmt::Show for Item<'a> { } } try!(write!(fmt, "{}", - shortty(self.item), self.item.name.get_ref().as_slice())); + shortty(self.item), self.item.name.as_ref().unwrap().as_slice())); // Write stability level try!(write!(fmt, "{}", Stability(&self.item.stability))); @@ -1395,12 +1395,12 @@ impl<'a> fmt::Show for Item<'a> { fn item_path(item: &clean::Item) -> String { match item.inner { clean::ModuleItem(..) => { - format!("{}/index.html", item.name.get_ref()) + format!("{}/index.html", item.name.as_ref().unwrap()) } _ => { format!("{}.{}.html", shortty(item).to_static_str(), - *item.name.get_ref()) + *item.name.as_ref().unwrap()) } } } @@ -1560,7 +1560,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, ConciseStability(&myitem.stability), VisSpace(myitem.visibility), MutableSpace(s.mutability), - *myitem.name.get_ref(), + *myitem.name.as_ref().unwrap(), s.type_, Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }), Markdown(blank(myitem.doc_value())))); @@ -1574,7 +1574,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, ", ConciseStability(&myitem.stability), VisSpace(myitem.visibility), - *myitem.name.get_ref(), + *myitem.name.as_ref().unwrap(), s.type_, Initializer(s.expr.as_slice(), Item { cx: cx, item: myitem }), Markdown(blank(myitem.doc_value())))); @@ -1611,7 +1611,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, {} ", - *myitem.name.get_ref(), + *myitem.name.as_ref().unwrap(), Markdown(shorter(myitem.doc_value())), class = shortty(myitem), href = item_path(myitem), @@ -1630,7 +1630,7 @@ fn item_function(w: &mut fmt::Formatter, it: &clean::Item, {name}{generics}{decl}{where_clause}", vis = VisSpace(it.visibility), fn_style = FnStyleSpace(f.fn_style), - name = it.name.get_ref().as_slice(), + name = it.name.as_ref().unwrap().as_slice(), generics = f.generics, where_clause = WhereClause(&f.generics), decl = f.decl)); @@ -1651,7 +1651,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, // Output the trait definition try!(write!(w, "
{}trait {}{}{}{} ",
                   VisSpace(it.visibility),
-                  it.name.get_ref().as_slice(),
+                  it.name.as_ref().unwrap().as_slice(),
                   t.generics,
                   bounds,
                   WhereClause(&t.generics)));
@@ -1700,7 +1700,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
                   -> fmt::Result {
         try!(write!(w, "

{}", shortty(m.item()), - *m.item().name.get_ref(), + *m.item().name.as_ref().unwrap(), ConciseStability(&m.item().stability))); try!(render_method(w, m.item())); try!(write!(w, "

")); @@ -1753,11 +1753,11 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, path = if ast_util::is_local(it.def_id) { cx.current.connect("/") } else { - let path = cache.external_paths.get(&it.def_id); + let path = &cache.external_paths[it.def_id]; path.slice_to(path.len() - 1).connect("/") }, ty = shortty(it).to_static_str(), - name = *it.name.get_ref())); + name = *it.name.as_ref().unwrap())); Ok(()) } @@ -1772,7 +1772,7 @@ fn render_method(w: &mut fmt::Formatter, meth: &clean::Item) -> fmt::Result { _ => "", }, ty = shortty(it), - name = it.name.get_ref().as_slice(), + name = it.name.as_ref().unwrap().as_slice(), generics = *g, decl = Method(selfty, d), where_clause = WhereClause(g)) @@ -1816,7 +1816,7 @@ fn item_struct(w: &mut fmt::Formatter, it: &clean::Item, try!(write!(w, "\ {stab}{name}", stab = ConciseStability(&field.stability), - name = field.name.get_ref().as_slice())); + name = field.name.as_ref().unwrap().as_slice())); try!(document(w, field)); try!(write!(w, "")); } @@ -1832,7 +1832,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item, e: &clean::Enum) -> fmt::Result { try!(write!(w, "
{}enum {}{}{}",
                   VisSpace(it.visibility),
-                  it.name.get_ref().as_slice(),
+                  it.name.as_ref().unwrap().as_slice(),
                   e.generics,
                   WhereClause(&e.generics)));
     if e.variants.len() == 0 && !e.variants_stripped {
@@ -1885,7 +1885,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
         for variant in e.variants.iter() {
             try!(write!(w, "{stab}{name}",
                           stab = ConciseStability(&variant.stability),
-                          name = variant.name.get_ref().as_slice()));
+                          name = variant.name.as_ref().unwrap().as_slice()));
             try!(document(w, variant));
             match variant.inner {
                 clean::VariantItem(ref var) => {
@@ -1906,8 +1906,8 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
                                 try!(write!(w, "\
                                                   {f}",
-                                              v = variant.name.get_ref().as_slice(),
-                                              f = field.name.get_ref().as_slice()));
+                                              v = variant.name.as_ref().unwrap().as_slice(),
+                                              f = field.name.as_ref().unwrap().as_slice()));
                                 try!(document(w, field));
                                 try!(write!(w, ""));
                             }
@@ -1936,7 +1936,7 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
     try!(write!(w, "{}{}{}",
                   VisSpace(it.visibility),
                   if structhead {"struct "} else {""},
-                  it.name.get_ref().as_slice()));
+                  it.name.as_ref().unwrap().as_slice()));
     match g {
         Some(g) => try!(write!(w, "{}{}", *g, WhereClause(g))),
         None => {}
@@ -1953,7 +1953,7 @@ fn render_struct(w: &mut fmt::Formatter, it: &clean::Item,
                     clean::StructFieldItem(clean::TypedStructField(ref ty)) => {
                         try!(write!(w, "    {}{}: {},\n{}",
                                       VisSpace(field.visibility),
-                                      field.name.get_ref().as_slice(),
+                                      field.name.as_ref().unwrap().as_slice(),
                                       *ty,
                                       tab));
                     }
@@ -2042,7 +2042,7 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result {
     fn doctraititem(w: &mut fmt::Formatter, item: &clean::Item, dox: bool)
                     -> fmt::Result {
         try!(write!(w, "

{}", - *item.name.get_ref(), + *item.name.as_ref().unwrap(), ConciseStability(&item.stability))); try!(render_method(w, item)); try!(write!(w, "

\n")); @@ -2096,7 +2096,7 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result { fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item, t: &clean::Typedef) -> fmt::Result { try!(write!(w, "
type {}{} = {};
", - it.name.get_ref().as_slice(), + it.name.as_ref().unwrap().as_slice(), t.generics, t.type_)); @@ -2231,5 +2231,5 @@ fn get_basic_keywords() -> &'static str { } fn make_item_keywords(it: &clean::Item) -> String { - format!("{}, {}", get_basic_keywords(), it.name.get_ref()) + format!("{}, {}", get_basic_keywords(), it.name.as_ref().unwrap()) } diff --git a/src/librustrt/args.rs b/src/librustrt/args.rs index 9b1dd7a8254..3138c9be992 100644 --- a/src/librustrt/args.rs +++ b/src/librustrt/args.rs @@ -125,8 +125,8 @@ mod imp { let saved_value = take(); let expected = vec![ - Vec::from_slice(b"happy"), - Vec::from_slice(b"today?"), + b"happy".to_vec(), + b"today?".to_vec(), ]; put(expected.clone()); diff --git a/src/librustrt/c_str.rs b/src/librustrt/c_str.rs index a5ac70286fe..a4129fe3506 100644 --- a/src/librustrt/c_str.rs +++ b/src/librustrt/c_str.rs @@ -204,30 +204,6 @@ impl CString { self.buf as *mut _ } - /// Calls a closure with a reference to the underlying `*libc::c_char`. - #[deprecated="use `.as_ptr()`"] - pub fn with_ref(&self, f: |*const libc::c_char| -> T) -> T { - f(self.buf) - } - - /// Calls a closure with a mutable reference to the underlying `*libc::c_char`. - #[deprecated="use `.as_mut_ptr()`"] - pub fn with_mut_ref(&mut self, f: |*mut libc::c_char| -> T) -> T { - f(self.buf as *mut libc::c_char) - } - - /// Returns true if the CString is a null. - #[deprecated="a CString cannot be null"] - pub fn is_null(&self) -> bool { - self.buf.is_null() - } - - /// Returns true if the CString is not null. - #[deprecated="a CString cannot be null"] - pub fn is_not_null(&self) -> bool { - self.buf.is_not_null() - } - /// Returns whether or not the `CString` owns the buffer. pub fn owns_buffer(&self) -> bool { self.owns_buffer_ diff --git a/src/libsemver/lib.rs b/src/libsemver/lib.rs deleted file mode 100644 index cc0e7d9ba2d..00000000000 --- a/src/libsemver/lib.rs +++ /dev/null @@ -1,462 +0,0 @@ -// Copyright 2012-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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Semantic version parsing and comparison. -//! -//! Semantic versioning (see http://semver.org/) is a set of rules for -//! assigning version numbers intended to convey meaning about what has -//! changed, and how much. A version number has five parts: -//! -//! * Major number, updated for incompatible API changes -//! * Minor number, updated for backwards-compatible API additions -//! * Patch number, updated for backwards-compatible bugfixes -//! * Pre-release information (optional), preceded by a hyphen (`-`) -//! * Build metadata (optional), preceded by a plus sign (`+`) -//! -//! The three mandatory components are required to be decimal numbers. The -//! pre-release information and build metadata are required to be a -//! period-separated list of identifiers containing only alphanumeric -//! characters and hyphens. -//! -//! An example version number with all five components is -//! `0.8.1-rc.3.0+20130922.linux`. - -#![crate_name = "semver"] -#![deprecated = "This is now a cargo package located at: \ - https://github.com/rust-lang/semver"] -#![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(default_type_params)] - -use std::char; -use std::cmp; -use std::fmt::Show; -use std::fmt; -use std::hash; - -/// An identifier in the pre-release or build metadata. If the identifier can -/// be parsed as a decimal value, it will be represented with `Numeric`. -#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -#[allow(missing_doc)] -pub enum Identifier { - Numeric(uint), - AlphaNumeric(String) -} - -impl fmt::Show for Identifier { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Numeric(ref n) => n.fmt(f), - AlphaNumeric(ref s) => s.fmt(f) - } - } -} - - -/// Represents a version number conforming to the semantic versioning scheme. -#[deriving(Clone, Eq)] -pub struct Version { - /// The major version, to be incremented on incompatible changes. - pub major: uint, - /// The minor version, to be incremented when functionality is added in a - /// backwards-compatible manner. - pub minor: uint, - /// The patch version, to be incremented when backwards-compatible bug - /// fixes are made. - pub patch: uint, - /// The pre-release version identifier, if one exists. - pub pre: Vec, - /// The build metadata, ignored when determining version precedence. - pub build: Vec, -} - -impl fmt::Show for Version { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}.{}.{}", self.major, self.minor, self.patch)) - if !self.pre.is_empty() { - try!(write!(f, "-")); - for (i, x) in self.pre.iter().enumerate() { - if i != 0 { try!(write!(f, ".")) }; - try!(x.fmt(f)); - } - } - if !self.build.is_empty() { - try!(write!(f, "+")); - for (i, x) in self.build.iter().enumerate() { - if i != 0 { try!(write!(f, ".")) }; - try!(x.fmt(f)); - } - } - Ok(()) - } -} - -impl cmp::PartialEq for Version { - #[inline] - fn eq(&self, other: &Version) -> bool { - // We should ignore build metadata here, otherwise versions v1 and v2 - // can exist such that !(v1 < v2) && !(v1 > v2) && v1 != v2, which - // violate strict total ordering rules. - self.major == other.major && - self.minor == other.minor && - self.patch == other.patch && - self.pre == other.pre - } -} - -impl cmp::PartialOrd for Version { - fn partial_cmp(&self, other: &Version) -> Option { - Some(self.cmp(other)) - } -} - -impl cmp::Ord for Version { - fn cmp(&self, other: &Version) -> Ordering { - match self.major.cmp(&other.major) { - Equal => {} - r => return r, - } - - match self.minor.cmp(&other.minor) { - Equal => {} - r => return r, - } - - match self.patch.cmp(&other.patch) { - Equal => {} - r => return r, - } - - // NB: semver spec says 0.0.0-pre < 0.0.0 - // but the version of ord defined for vec - // says that [] < [pre] so we alter it here - match (self.pre.len(), other.pre.len()) { - (0, 0) => Equal, - (0, _) => Greater, - (_, 0) => Less, - (_, _) => self.pre.cmp(&other.pre) - } - } -} - -impl hash::Hash for Version { - fn hash(&self, into: &mut S) { - self.major.hash(into); - self.minor.hash(into); - self.patch.hash(into); - self.pre.hash(into); - } -} - -fn take_nonempty_prefix>(rdr: &mut T, pred: |char| -> bool) - -> (String, Option) { - let mut buf = String::new(); - let mut ch = rdr.next(); - loop { - match ch { - None => break, - Some(c) if !pred(c) => break, - Some(c) => { - buf.push_char(c); - ch = rdr.next(); - } - } - } - (buf, ch) -} - -fn take_num>(rdr: &mut T) -> Option<(uint, Option)> { - let (s, ch) = take_nonempty_prefix(rdr, char::is_digit); - match from_str::(s.as_slice()) { - None => None, - Some(i) => Some((i, ch)) - } -} - -fn take_ident>(rdr: &mut T) -> Option<(Identifier, Option)> { - let (s,ch) = take_nonempty_prefix(rdr, char::is_alphanumeric); - if s.as_slice().chars().all(char::is_digit) { - match from_str::(s.as_slice()) { - None => None, - Some(i) => Some((Numeric(i), ch)) - } - } else { - Some((AlphaNumeric(s), ch)) - } -} - -fn expect(ch: Option, c: char) -> Option<()> { - if ch != Some(c) { - None - } else { - Some(()) - } -} - -fn parse_iter>(rdr: &mut T) -> Option { - let maybe_vers = take_num(rdr).and_then(|(major, ch)| { - expect(ch, '.').and_then(|_| Some(major)) - }).and_then(|major| { - take_num(rdr).and_then(|(minor, ch)| { - expect(ch, '.').and_then(|_| Some((major, minor))) - }) - }).and_then(|(major, minor)| { - take_num(rdr).and_then(|(patch, ch)| { - Some((major, minor, patch, ch)) - }) - }); - - let (major, minor, patch, ch) = match maybe_vers { - Some((a, b, c, d)) => (a, b, c, d), - None => return None - }; - - let mut pre = vec!(); - let mut build = vec!(); - - let mut ch = ch; - if ch == Some('-') { - loop { - let (id, c) = match take_ident(rdr) { - Some((id, c)) => (id, c), - None => return None - }; - pre.push(id); - ch = c; - if ch != Some('.') { break; } - } - } - - if ch == Some('+') { - loop { - let (id, c) = match take_ident(rdr) { - Some((id, c)) => (id, c), - None => return None - }; - build.push(id); - ch = c; - if ch != Some('.') { break; } - } - } - - Some(Version { - major: major, - minor: minor, - patch: patch, - pre: pre, - build: build, - }) -} - - -/// Parse a string into a semver object. -pub fn parse(s: &str) -> Option { - if !s.is_ascii() { - return None; - } - let s = s.trim(); - let v = parse_iter(&mut s.chars()); - match v { - Some(v) => { - if v.to_string().equiv(&s) { - Some(v) - } else { - None - } - } - None => None - } -} - -#[test] -fn test_parse() { - assert_eq!(parse(""), None); - assert_eq!(parse(" "), None); - assert_eq!(parse("1"), None); - assert_eq!(parse("1.2"), None); - assert_eq!(parse("1.2"), None); - assert_eq!(parse("1"), None); - assert_eq!(parse("1.2"), None); - assert_eq!(parse("1.2.3-"), None); - assert_eq!(parse("a.b.c"), None); - assert_eq!(parse("1.2.3 abc"), None); - - assert!(parse("1.2.3") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(), - build: vec!(), - })); - assert!(parse(" 1.2.3 ") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(), - build: vec!(), - })); - assert!(parse("1.2.3-alpha1") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(AlphaNumeric("alpha1".to_string())), - build: vec!(), - })); - assert!(parse(" 1.2.3-alpha1 ") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(AlphaNumeric("alpha1".to_string())), - build: vec!() - })); - assert!(parse("1.2.3+build5") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(), - build: vec!(AlphaNumeric("build5".to_string())) - })); - assert!(parse(" 1.2.3+build5 ") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(), - build: vec!(AlphaNumeric("build5".to_string())) - })); - assert!(parse("1.2.3-alpha1+build5") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(AlphaNumeric("alpha1".to_string())), - build: vec!(AlphaNumeric("build5".to_string())) - })); - assert!(parse(" 1.2.3-alpha1+build5 ") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(AlphaNumeric("alpha1".to_string())), - build: vec!(AlphaNumeric("build5".to_string())) - })); - assert!(parse("1.2.3-1.alpha1.9+build5.7.3aedf ") == Some(Version { - major: 1u, - minor: 2u, - patch: 3u, - pre: vec!(Numeric(1),AlphaNumeric("alpha1".to_string()),Numeric(9)), - build: vec!(AlphaNumeric("build5".to_string()), - Numeric(7), - AlphaNumeric("3aedf".to_string())) - })); - -} - -#[test] -fn test_eq() { - assert_eq!(parse("1.2.3"), parse("1.2.3")); - assert_eq!(parse("1.2.3-alpha1"), parse("1.2.3-alpha1")); - assert_eq!(parse("1.2.3+build.42"), parse("1.2.3+build.42")); - assert_eq!(parse("1.2.3-alpha1+42"), parse("1.2.3-alpha1+42")); - assert_eq!(parse("1.2.3+23"), parse("1.2.3+42")); -} - -#[test] -fn test_ne() { - assert!(parse("0.0.0") != parse("0.0.1")); - assert!(parse("0.0.0") != parse("0.1.0")); - assert!(parse("0.0.0") != parse("1.0.0")); - assert!(parse("1.2.3-alpha") != parse("1.2.3-beta")); -} - -#[test] -fn test_show() { - assert_eq!(format!("{}", parse("1.2.3").unwrap()), - "1.2.3".to_string()); - assert_eq!(format!("{}", parse("1.2.3-alpha1").unwrap()), - "1.2.3-alpha1".to_string()); - assert_eq!(format!("{}", parse("1.2.3+build.42").unwrap()), - "1.2.3+build.42".to_string()); - assert_eq!(format!("{}", parse("1.2.3-alpha1+42").unwrap()), - "1.2.3-alpha1+42".to_string()); -} - -#[test] -fn test_to_string() { - assert_eq!(parse("1.2.3").unwrap().to_string(), "1.2.3".to_string()); - assert_eq!(parse("1.2.3-alpha1").unwrap().to_string(), "1.2.3-alpha1".to_string()); - assert_eq!(parse("1.2.3+build.42").unwrap().to_string(), "1.2.3+build.42".to_string()); - assert_eq!(parse("1.2.3-alpha1+42").unwrap().to_string(), "1.2.3-alpha1+42".to_string()); -} - -#[test] -fn test_lt() { - assert!(parse("0.0.0") < parse("1.2.3-alpha2")); - assert!(parse("1.0.0") < parse("1.2.3-alpha2")); - assert!(parse("1.2.0") < parse("1.2.3-alpha2")); - assert!(parse("1.2.3-alpha1") < parse("1.2.3")); - assert!(parse("1.2.3-alpha1") < parse("1.2.3-alpha2")); - assert!(!(parse("1.2.3-alpha2") < parse("1.2.3-alpha2"))); - assert!(!(parse("1.2.3+23") < parse("1.2.3+42"))); -} - -#[test] -fn test_le() { - assert!(parse("0.0.0") <= parse("1.2.3-alpha2")); - assert!(parse("1.0.0") <= parse("1.2.3-alpha2")); - assert!(parse("1.2.0") <= parse("1.2.3-alpha2")); - assert!(parse("1.2.3-alpha1") <= parse("1.2.3-alpha2")); - assert!(parse("1.2.3-alpha2") <= parse("1.2.3-alpha2")); - assert!(parse("1.2.3+23") <= parse("1.2.3+42")); -} - -#[test] -fn test_gt() { - assert!(parse("1.2.3-alpha2") > parse("0.0.0")); - assert!(parse("1.2.3-alpha2") > parse("1.0.0")); - assert!(parse("1.2.3-alpha2") > parse("1.2.0")); - assert!(parse("1.2.3-alpha2") > parse("1.2.3-alpha1")); - assert!(parse("1.2.3") > parse("1.2.3-alpha2")); - assert!(!(parse("1.2.3-alpha2") > parse("1.2.3-alpha2"))); - assert!(!(parse("1.2.3+23") > parse("1.2.3+42"))); -} - -#[test] -fn test_ge() { - assert!(parse("1.2.3-alpha2") >= parse("0.0.0")); - assert!(parse("1.2.3-alpha2") >= parse("1.0.0")); - assert!(parse("1.2.3-alpha2") >= parse("1.2.0")); - assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha1")); - assert!(parse("1.2.3-alpha2") >= parse("1.2.3-alpha2")); - assert!(parse("1.2.3+23") >= parse("1.2.3+42")); -} - -#[test] -fn test_spec_order() { - let vs = ["1.0.0-alpha", - "1.0.0-alpha.1", - "1.0.0-alpha.beta", - "1.0.0-beta", - "1.0.0-beta.2", - "1.0.0-beta.11", - "1.0.0-rc.1", - "1.0.0"]; - let mut i = 1; - while i < vs.len() { - let a = parse(vs[i-1]).unwrap(); - let b = parse(vs[i]).unwrap(); - assert!(a < b); - i += 1; - } -} diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index eda38e96cbb..73b4773fb3f 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -406,14 +406,6 @@ impl<'a> Encoder<'a> { } m.unwrap() } - - /// Encode the specified struct into a json str - /// - /// Note: this function is deprecated. Consider using `json::encode` instead. - #[deprecated = "Replaced by `json::encode`"] - pub fn str_encode, io::IoError>>(object: &T) -> string::String { - encode(object) - } } impl<'a> ::Encoder for Encoder<'a> { diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 1c80627d328..07be15486fd 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -25,13 +25,6 @@ use string::{mod, String}; use to_string::IntoStr; use vec::Vec; -#[deprecated="this trait has been renamed to `AsciiExt`"] -pub use self::AsciiExt as StrAsciiExt; - -#[deprecated="this trait has been renamed to `OwnedAsciiExt`"] -pub use self::OwnedAsciiExt as OwnedStrAsciiExt; - - /// Datatype to hold one ascii character. It wraps a `u8`, with the highest bit always zero. #[deriving(Clone, PartialEq, PartialOrd, Ord, Eq, Hash)] pub struct Ascii { chr: u8 } @@ -49,26 +42,12 @@ impl Ascii { self.chr as char } - #[inline] - #[allow(missing_doc)] - #[deprecated="renamed to `to_lowercase`"] - pub fn to_lower(self) -> Ascii { - self.to_lowercase() - } - /// Convert to lowercase. #[inline] pub fn to_lowercase(self) -> Ascii { Ascii{chr: ASCII_LOWER_MAP[self.chr as uint]} } - /// Deprecated: use `to_uppercase` - #[inline] - #[deprecated="renamed to `to_uppercase`"] - pub fn to_upper(self) -> Ascii { - self.to_uppercase() - } - /// Convert to uppercase. #[inline] pub fn to_uppercase(self) -> Ascii { @@ -83,13 +62,6 @@ impl Ascii { // the following methods are like ctype, and the implementation is inspired by musl - #[inline] - #[allow(missing_doc)] - #[deprecated="renamed to `is_alphabetic`"] - pub fn is_alpha(&self) -> bool { - self.is_alphabetic() - } - /// Check if the character is a letter (a-z, A-Z) #[inline] pub fn is_alphabetic(&self) -> bool { @@ -102,13 +74,6 @@ impl Ascii { self.chr >= 0x30 && self.chr <= 0x39 } - #[inline] - #[allow(missing_doc)] - #[deprecated="renamed to `is_alphanumeric`"] - pub fn is_alnum(&self) -> bool { - self.is_alphanumeric() - } - /// Check if the character is a letter or number #[inline] pub fn is_alphanumeric(&self) -> bool { @@ -139,26 +104,12 @@ impl Ascii { (self.chr - 0x20) < 0x5F } - /// Deprecated: use `to_lowercase` - #[inline] - #[deprecated="renamed to `is_lowercase`"] - pub fn is_lower(&self) -> bool { - self.is_lowercase() - } - /// Checks if the character is lowercase #[inline] pub fn is_lowercase(&self) -> bool { (self.chr - b'a') < 26 } - #[inline] - #[allow(missing_doc)] - #[deprecated="renamed to `is_uppercase`"] - pub fn is_upper(&self) -> bool { - self.is_uppercase() - } - /// Checks if the character is uppercase #[inline] pub fn is_uppercase(&self) -> bool { @@ -581,7 +532,6 @@ mod tests { use prelude::*; use super::*; use char::from_u32; - use vec::Vec; use str::StrSlice; macro_rules! v2ascii ( @@ -590,7 +540,7 @@ mod tests { ) macro_rules! vec2ascii ( - ($($e:expr),*) => (Vec::from_slice([$(Ascii{chr:$e}),*])); + ($($e:expr),*) => ([$(Ascii{chr:$e}),*].to_vec()); ) #[test] diff --git a/src/libstd/collections/hashmap/map.rs b/src/libstd/collections/hashmap/map.rs index bdd9d8d9d1f..ac0d117e02a 100644 --- a/src/libstd/collections/hashmap/map.rs +++ b/src/libstd/collections/hashmap/map.rs @@ -22,7 +22,7 @@ use iter; use mem::replace; use mem; use num; -use ops::{Deref, DerefMut}; +use ops::Deref; use option::{Some, None, Option}; use result::{Ok, Err}; use ops::Index; @@ -425,25 +425,6 @@ impl SearchResult { } } -/// A newtyped mutable reference to the hashmap that allows e.g. Deref to be -/// implemented without making changes to the visible interface of HashMap. -/// Used internally because it's accepted by the search functions above. -struct MapMutRef<'a, K: 'a, V: 'a, H: 'a> { - map_ref: &'a mut HashMap -} - -impl<'a, K, V, H> Deref> for MapMutRef<'a, K, V, H> { - fn deref(&self) -> &RawTable { - &self.map_ref.table - } -} - -impl<'a, K, V, H> DerefMut> for MapMutRef<'a, K, V, H> { - fn deref_mut(&mut self) -> &mut RawTable { - &mut self.map_ref.table - } -} - impl, V, S, H: Hasher> HashMap { fn make_hash>(&self, x: &X) -> SafeHash { table::make_hash(&self.hasher, x) @@ -847,253 +828,6 @@ impl, V, S, H: Hasher> HashMap { } } - /// Inserts an element which has already been hashed, returning a reference - /// to that element inside the hashtable. This is more efficient that using - /// `insert`, since the key will not be rehashed. - fn insert_hashed(&mut self, hash: SafeHash, k: K, v: V) -> &mut V { - let potential_new_size = self.table.size() + 1; - self.make_some_room(potential_new_size); - self.insert_hashed_nocheck(hash, k, v) - } - - /// Deprecated: use `entry` as follows instead: - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hashmap::{Occupied, Vacant}; - /// - /// let mut map = HashMap::new(); - /// - /// let result = match map.entry("a") { - /// Vacant(entry) => entry.set(1i), - /// Occupied(entry) => entry.into_mut(), - /// }; - /// assert_eq!(*result, 1); - /// ``` - /// - /// Return the value corresponding to the key in the map, or insert - /// and return the value if it doesn't exist. - /// - /// # Example - /// - /// ``` - /// #![allow(deprecated)] - /// use std::collections::HashMap; - /// let mut map = HashMap::new(); - /// - /// // Insert 1i with key "a" - /// assert_eq!(*map.find_or_insert("a", 1i), 1); - /// - /// // Find the existing key - /// assert_eq!(*map.find_or_insert("a", -2), 1); - /// ``` - #[deprecated = "use entry instead"] - #[allow(deprecated)] - pub fn find_or_insert(&mut self, k: K, v: V) -> &mut V { - self.find_with_or_insert_with(k, v, |_k, _v, _a| (), |_k, a| a) - } - - /// Deprecated: use `entry` as follows instead: - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hashmap::{Occupied, Vacant}; - /// - /// let mut map = HashMap::new(); - /// - /// let result = match map.entry("a") { - /// Vacant(entry) => entry.set(1i), - /// Occupied(entry) => entry.into_mut(), - /// }; - /// assert_eq!(*result, 1); - /// ``` - /// - /// Return the value corresponding to the key in the map, or create, - /// insert, and return a new value if it doesn't exist. - /// - /// # Example - /// - /// ``` - /// #![allow(deprecated)] - /// use std::collections::HashMap; - /// let mut map = HashMap::new(); - /// - /// // Insert 10 with key 2 - /// assert_eq!(*map.find_or_insert_with(2i, |&key| 5 * key as uint), 10u); - /// - /// // Find the existing key - /// assert_eq!(*map.find_or_insert_with(2, |&key| key as uint), 10); - /// ``` - #[deprecated = "use entry instead"] - #[allow(deprecated)] - pub fn find_or_insert_with<'a>(&'a mut self, k: K, f: |&K| -> V) - -> &'a mut V { - self.find_with_or_insert_with(k, (), |_k, _v, _a| (), |k, _a| f(k)) - } - - /// Deprecated: use `entry` as follows instead: - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hashmap::{Occupied, Vacant}; - /// - /// let mut map = HashMap::new(); - /// - /// let result = match map.entry("a") { - /// Vacant(entry) => entry.set(1u), - /// Occupied(mut entry) => { - /// *entry.get_mut() += 1; - /// entry.into_mut() - /// } - /// }; - /// assert_eq!(*result, 1); - /// ``` - /// - /// Insert a key-value pair into the map if the key is not already present. - /// Otherwise, modify the existing value for the key. - /// Returns the new or modified value for the key. - /// - /// # Example - /// - /// ``` - /// #![allow(deprecated)] - /// use std::collections::HashMap; - /// let mut map = HashMap::new(); - /// - /// // Insert 2 with key "a" - /// assert_eq!(*map.insert_or_update_with("a", 2u, |_key, val| *val = 3), 2); - /// - /// // Update and return the existing value - /// assert_eq!(*map.insert_or_update_with("a", 9, |_key, val| *val = 7), 7); - /// assert_eq!(map["a"], 7); - /// ``` - #[deprecated = "use entry instead"] - pub fn insert_or_update_with<'a>( - &'a mut self, - k: K, - v: V, - f: |&K, &mut V|) - -> &'a mut V { - let potential_new_size = self.table.size() + 1; - self.make_some_room(potential_new_size); - - let hash = self.make_hash(&k); - self.insert_or_replace_with(hash, k, v, |kref, vref, _v| f(kref, vref)) - } - - /// Deprecated: use `entry` as follows instead: - /// - /// ``` - /// use std::collections::HashMap; - /// use std::collections::hashmap::{Occupied, Vacant}; - /// - /// let mut map = HashMap::new(); - /// - /// let result = match map.entry("a") { - /// Vacant(entry) => entry.set(1u), - /// Occupied(mut entry) => { - /// *entry.get_mut() += 1; - /// entry.into_mut() - /// } - /// }; - /// assert_eq!(*result, 1); - /// ``` - /// - /// Modify and return the value corresponding to the key in the map, or - /// insert and return a new value if it doesn't exist. - /// - /// This method allows for all insertion behaviours of a hashmap; - /// see methods like - /// [`insert`](../trait.MutableMap.html#tymethod.insert), - /// [`find_or_insert`](#method.find_or_insert) and - /// [`insert_or_update_with`](#method.insert_or_update_with) - /// for less general and more friendly variations of this. - /// - /// # Example - /// - /// ``` - /// #![allow(deprecated)] - /// use std::collections::HashMap; - /// - /// // map some strings to vectors of strings - /// let mut map = HashMap::new(); - /// map.insert("a key", vec!["value"]); - /// map.insert("z key", vec!["value"]); - /// - /// let new = vec!["a key", "b key", "z key"]; - /// - /// for k in new.into_iter() { - /// map.find_with_or_insert_with( - /// k, "new value", - /// // if the key does exist either prepend or append this - /// // new value based on the first letter of the key. - /// |key, already, new| { - /// if key.as_slice().starts_with("z") { - /// already.insert(0, new); - /// } else { - /// already.push(new); - /// } - /// }, - /// // if the key doesn't exist in the map yet, add it in - /// // the obvious way. - /// |_k, v| vec![v]); - /// } - /// - /// assert_eq!(map.len(), 3); - /// assert_eq!(map["a key"], vec!["value", "new value"]); - /// assert_eq!(map["b key"], vec!["new value"]); - /// assert_eq!(map["z key"], vec!["new value", "value"]); - /// ``` - #[deprecated = "use entry instead"] - pub fn find_with_or_insert_with<'a, A>(&'a mut self, - k: K, - a: A, - found: |&K, &mut V, A|, - not_found: |&K, A| -> V) - -> &'a mut V - { - let hash = self.make_hash(&k); - let this = MapMutRef { map_ref: self }; - - match search_hashed(this, &hash, &k) { - FoundExisting(bucket) => { - let (_, v_ref) = bucket.into_mut_refs(); - found(&k, v_ref, a); - v_ref - } - TableRef(this) => { - let v = not_found(&k, a); - this.map_ref.insert_hashed(hash, k, v) - } - } - } - - /// 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::HashMap; - /// - /// let mut map = HashMap::new(); - /// map.insert("a", 1i); - /// assert_eq!(map.get(&"a"), &1); - /// ``` - #[deprecated = "prefer indexing instead, e.g., map[key]"] - pub fn get<'a>(&'a self, k: &K) -> &'a V { - match self.find(k) { - Some(v) => v, - None => fail!("no entry found for key") - } - } - /// Retrieves a mutable value for the given key. /// See [`find_mut`](../trait.MutableMap.html#tymethod.find_mut) for a non-failing alternative. /// @@ -1274,12 +1008,6 @@ impl, V, S, H: Hasher> HashMap { Entries { inner: self.table.iter() } } - /// Deprecated: use `iter_mut`. - #[deprecated = "use iter_mut"] - pub fn mut_iter(&mut self) -> MutEntries { - self.iter_mut() - } - /// An iterator visiting all key-value pairs in arbitrary order, /// with mutable references to the values. /// Iterator element type is `(&'a K, &'a mut V)`. @@ -1307,12 +1035,6 @@ impl, V, S, H: Hasher> HashMap { MutEntries { inner: self.table.iter_mut() } } - /// Deprecated: use `into_iter`. - #[deprecated = "use into_iter"] - pub fn move_iter(self) -> MoveEntries { - self.into_iter() - } - /// Creates a consuming iterator, that is, one that moves each key-value /// pair out of the map in arbitrary order. The map cannot be used after /// calling this. @@ -1468,9 +1190,8 @@ impl, V, S, H: Hasher + Default> Default for HashMap impl, V, S, H: Hasher> Index for HashMap { #[inline] - #[allow(deprecated)] fn index<'a>(&'a self, index: &K) -> &'a V { - self.get(index) + self.find(index).expect("no entry found for key") } } @@ -1929,29 +1650,6 @@ mod test_map { assert_eq!(*m.find(&1).unwrap(), 2); } - #[test] - #[allow(deprecated)] // insert_or_update_with - fn test_update_with() { - let mut m = HashMap::with_capacity(4); - assert!(m.insert(1i, 2i)); - - for i in range(1i, 1000) { - assert_eq!( - i + 2, - *m.insert_or_update_with(i + 1, i + 2, |_k, _v| { - fail!("Key not yet present"); - }) - ); - assert_eq!( - i + 1, - *m.insert_or_update_with(i, i + 3, |k, v| { - assert_eq!(*k, i); - assert_eq!(*v, i + 1); - }) - ); - } - } - #[test] fn test_conflict_remove() { let mut m = HashMap::with_capacity(4); diff --git a/src/libstd/io/net/udp.rs b/src/libstd/io/net/udp.rs index b8fb187548c..53e60d553be 100644 --- a/src/libstd/io/net/udp.rs +++ b/src/libstd/io/net/udp.rs @@ -85,13 +85,6 @@ impl UdpSocket { } } - #[allow(missing_doc)] - #[deprecated = "renamed to `recv_from`"] - pub fn recvfrom(&mut self, buf: &mut [u8]) - -> IoResult<(uint, SocketAddr)> { - self.recv_from(buf) - } - /// Sends data on the socket to the given address. Returns nothing on /// success. pub fn send_to(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> { @@ -101,12 +94,6 @@ impl UdpSocket { }).map_err(IoError::from_rtio_error) } - #[allow(missing_doc)] - #[deprecated = "renamed to `send_to`"] - pub fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> IoResult<()> { - self.send_to(buf, dst) - } - /// Creates a `UdpStream`, which allows use of the `Reader` and `Writer` /// traits to receive and send data from the same address. This transfers /// ownership of the socket to the stream. @@ -176,12 +163,6 @@ impl UdpSocket { }.map_err(IoError::from_rtio_error) } - /// Sets the broadcast flag on or off - #[deprecated="renamed to `set_broadcast`"] - pub fn set_broadast(&mut self, broadcast: bool) -> IoResult<()> { - self.set_broadcast(broadcast) - } - /// Sets the read/write timeout for this socket. /// /// For more information, see `TcpStream::set_timeout` diff --git a/src/libstd/lib.rs b/src/libstd/lib.rs index 82c8d8071b3..c47cd025994 100644 --- a/src/libstd/lib.rs +++ b/src/libstd/lib.rs @@ -134,7 +134,6 @@ extern crate rustrt; #[cfg(test)] pub use realstd::kinds; #[cfg(test)] pub use realstd::ops; #[cfg(test)] pub use realstd::cmp; -#[cfg(test)] pub use realstd::ty; #[cfg(test)] pub use realstd::boxed; @@ -159,13 +158,10 @@ pub use core::tuple; // FIXME #15320: primitive documentation needs top-level modules, this // should be `std::tuple::unit`. pub use core::unit; -#[cfg(not(test))] pub use core::ty; pub use core::result; pub use core::option; pub use alloc::boxed; -#[deprecated = "use boxed instead"] -pub use boxed as owned; pub use alloc::rc; diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index f98e81bb2c8..3fa181b8478 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -333,29 +333,6 @@ pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> String { r } -impl num::ToStrRadix for f32 { - /// Converts a float to a string in a given radix - /// - /// # Arguments - /// - /// * num - The float value - /// * radix - The base to use - /// - /// # Failure - /// - /// Fails if called on a special value like `inf`, `-inf` or `NaN` due to - /// possible misinterpretation of the result at higher bases. If those values - /// are expected, use `to_str_radix_special()` instead. - #[inline] - fn to_str_radix(&self, rdx: uint) -> String { - let (r, special) = strconv::float_to_str_common( - *self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); - if special { fail!("number has a special value, \ - try to_str_radix_special() if those are expected") } - r - } -} - /// Convert a string in base 16 to a float. /// Accepts an optional binary exponent. /// diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index 5a5ca65a36d..b9d54ba182b 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -341,29 +341,6 @@ pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> String { r } -impl num::ToStrRadix for f64 { - /// Converts a float to a string in a given radix - /// - /// # Arguments - /// - /// * num - The float value - /// * radix - The base to use - /// - /// # Failure - /// - /// Fails if called on a special value like `inf`, `-inf` or `NAN` due to - /// possible misinterpretation of the result at higher bases. If those values - /// are expected, use `to_str_radix_special()` instead. - #[inline] - fn to_str_radix(&self, rdx: uint) -> String { - let (r, special) = strconv::float_to_str_common( - *self, rdx, true, strconv::SignNeg, strconv::DigAll, strconv::ExpNone, false); - if special { fail!("number has a special value, \ - try to_str_radix_special() if those are expected") } - r - } -} - /// Convert a string in base 16 to a float. /// Accepts an optional binary exponent. /// diff --git a/src/libstd/num/i16.rs b/src/libstd/num/i16.rs index 9e4cc06f0a2..d7732b474db 100644 --- a/src/libstd/num/i16.rs +++ b/src/libstd/num/i16.rs @@ -14,10 +14,9 @@ #![doc(primitive = "i16")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::i16::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i32.rs b/src/libstd/num/i32.rs index 54259fcad55..778f1c6748c 100644 --- a/src/libstd/num/i32.rs +++ b/src/libstd/num/i32.rs @@ -14,10 +14,9 @@ #![doc(primitive = "i32")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::i32::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i64.rs b/src/libstd/num/i64.rs index b5fe6825ca4..ae3d57eeac6 100644 --- a/src/libstd/num/i64.rs +++ b/src/libstd/num/i64.rs @@ -14,10 +14,9 @@ #![doc(primitive = "i64")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::i64::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/i8.rs b/src/libstd/num/i8.rs index 7aa9a41e340..8a3f379893c 100644 --- a/src/libstd/num/i8.rs +++ b/src/libstd/num/i8.rs @@ -14,10 +14,9 @@ #![doc(primitive = "i8")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::i8::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/int.rs b/src/libstd/num/int.rs index 74ee61634c6..51af04b32d4 100644 --- a/src/libstd/num/int.rs +++ b/src/libstd/num/int.rs @@ -14,10 +14,9 @@ #![doc(primitive = "int")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::int::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 62e609bb2e1..ca45b40e687 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -51,52 +51,12 @@ impl FromStrRadix for $T { } } -// String conversion functions and impl num -> str - -/// Convert to a string as a byte slice in a given base. -/// -/// Use in place of x.to_string() when you do not need to store the string permanently -/// -/// # Examples -/// -/// ``` -/// #![allow(deprecated)] -/// -/// std::int::to_str_bytes(123, 10, |v| { -/// assert!(v == "123".as_bytes()); -/// }); -/// ``` -#[inline] -#[deprecated = "just use .to_string(), or a BufWriter with write! if you mustn't allocate"] -pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { - use io::{Writer, Seek}; - // The radix can be as low as 2, so we need at least 64 characters for a - // base 2 number, and then we need another for a possible '-' character. - let mut buf = [0u8, ..65]; - let amt = { - let mut wr = ::io::BufWriter::new(buf); - (write!(&mut wr, "{}", ::fmt::radix(n, radix as u8))).unwrap(); - wr.tell().unwrap() as uint - }; - f(buf[..amt]) -} - -#[deprecated = "use fmt::radix"] -impl ToStrRadix for $T { - /// Convert to a string in a given base. - #[inline] - fn to_str_radix(&self, radix: uint) -> String { - format!("{}", ::fmt::radix(*self, radix as u8)) - } -} - #[cfg(test)] mod tests { use prelude::*; use super::*; use i32; - use num::ToStrRadix; use str::StrSlice; #[test] @@ -142,16 +102,6 @@ mod tests { assert!(parse_bytes("-9".as_bytes(), 2u).is_none()); } - #[test] - fn test_to_string() { - assert_eq!((0 as $T).to_str_radix(10u), "0".to_string()); - assert_eq!((1 as $T).to_str_radix(10u), "1".to_string()); - assert_eq!((-1 as $T).to_str_radix(10u), "-1".to_string()); - assert_eq!((127 as $T).to_str_radix(16u), "7f".to_string()); - assert_eq!((100 as $T).to_str_radix(10u), "100".to_string()); - - } - #[test] fn test_int_to_str_overflow() { let mut i8_val: i8 = 127_i8; diff --git a/src/libstd/num/mod.rs b/src/libstd/num/mod.rs index 27ee1e3ce3b..564b6a25f7f 100644 --- a/src/libstd/num/mod.rs +++ b/src/libstd/num/mod.rs @@ -17,7 +17,6 @@ #![allow(missing_doc)] use option::Option; -use string::String; #[cfg(test)] use fmt::Show; @@ -111,12 +110,6 @@ pub trait FloatMath: Float { fn atanh(self) -> Self; } -/// A generic trait for converting a value to a string with a radix (base) -#[deprecated = "use fmt::radix"] -pub trait ToStrRadix { - fn to_str_radix(&self, radix: uint) -> String; -} - /// A generic trait for converting a string with a radix (base) to a value #[experimental = "might need to return Result"] pub trait FromStrRadix { diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 48ee7664c16..af66e6ca934 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -20,7 +20,7 @@ use num::{Float, FPNaN, FPInfinite, ToPrimitive}; use num; use ops::{Add, Sub, Mul, Div, Rem, Neg}; use option::{None, Option, Some}; -use slice::{ImmutableSlice, MutableSlice}; +use slice::{ImmutableSlice, MutableSlice, CloneableVector}; use std::cmp::{PartialOrd, PartialEq}; use str::StrSlice; use string::String; @@ -168,8 +168,7 @@ static NAN_BUF: [u8, ..3] = [b'N', b'a', b'N']; * # Failure * - Fails if `radix` < 2 or `radix` > 36. */ -#[deprecated = "format!() and friends should be favored instead"] -pub fn int_to_str_bytes_common(num: T, radix: uint, sign: SignFormat, f: |u8|) { +fn int_to_str_bytes_common(num: T, radix: uint, sign: SignFormat, f: |u8|) { assert!(2 <= radix && radix <= 36); let _0: T = Zero::zero(); @@ -257,7 +256,6 @@ pub fn int_to_str_bytes_common(num: T, radix: uint, sign: SignFormat, f: * - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict * between digit and exponent sign `'p'`. */ -#[allow(deprecated)] pub fn float_to_str_bytes_common+Neg+Rem+Mul>( num: T, radix: uint, negative_zero: bool, @@ -278,17 +276,17 @@ pub fn float_to_str_bytes_common { return (Vec::from_slice("NaN".as_bytes()), true); } + FPNaN => { return (b"NaN".to_vec(), true); } FPInfinite if num > _0 => { return match sign { - SignAll => (Vec::from_slice("+inf".as_bytes()), true), - _ => (Vec::from_slice("inf".as_bytes()), true) + SignAll => (b"+inf".to_vec(), true), + _ => (b"inf".to_vec(), true) }; } FPInfinite if num < _0 => { return match sign { - SignNone => (Vec::from_slice("inf".as_bytes()), true), - _ => (Vec::from_slice("-inf".as_bytes()), true), + SignNone => (b"inf".to_vec(), true), + _ => (b"-inf".to_vec(), true), }; } _ => {} @@ -413,18 +411,18 @@ pub fn float_to_str_bytes_common start_fractional_digits && *buf.get(i) == b'0' { + while i > start_fractional_digits && buf[i] == b'0' { i -= 1; } // Only attempt to truncate digits if buf has fractional digits if i >= start_fractional_digits { // If buf ends with '.', cut that too. - if *buf.get(i) == b'.' { i -= 1 } + if buf[i] == b'.' { i -= 1 } // only resize buf if we actually remove digits if i < buf_max_i { - buf = Vec::from_slice(buf.slice(0, i + 1)); + buf = buf.slice(0, i + 1).to_vec(); } } } // If exact and trailing '.', just cut that else { let max_i = buf.len() - 1; - if *buf.get(max_i) == b'.' { - buf = Vec::from_slice(buf.slice(0, max_i)); + if buf[max_i] == b'.' { + buf = buf.slice(0, max_i).to_vec(); } } diff --git a/src/libstd/num/u16.rs b/src/libstd/num/u16.rs index c141ecc9cba..bb619b5b2f5 100644 --- a/src/libstd/num/u16.rs +++ b/src/libstd/num/u16.rs @@ -14,10 +14,9 @@ #![doc(primitive = "u16")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::u16::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u32.rs b/src/libstd/num/u32.rs index 8a8e2729a53..754103ba5da 100644 --- a/src/libstd/num/u32.rs +++ b/src/libstd/num/u32.rs @@ -14,10 +14,9 @@ #![doc(primitive = "u32")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::u32::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u64.rs b/src/libstd/num/u64.rs index 1b4f8bc433f..da497d2cbe4 100644 --- a/src/libstd/num/u64.rs +++ b/src/libstd/num/u64.rs @@ -14,10 +14,9 @@ #![doc(primitive = "u64")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::u64::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/u8.rs b/src/libstd/num/u8.rs index 28f22429235..bdfcdb2c5a5 100644 --- a/src/libstd/num/u8.rs +++ b/src/libstd/num/u8.rs @@ -14,10 +14,9 @@ #![doc(primitive = "u8")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::u8::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/uint.rs b/src/libstd/num/uint.rs index da328074453..5090219d3de 100644 --- a/src/libstd/num/uint.rs +++ b/src/libstd/num/uint.rs @@ -14,10 +14,9 @@ #![doc(primitive = "uint")] use from_str::FromStr; -use num::{ToStrRadix, FromStrRadix}; +use num::FromStrRadix; use num::strconv; use option::Option; -use string::String; pub use core::uint::{BITS, BYTES, MIN, MAX}; diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index a033308af16..f9bc9eb539a 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -82,35 +82,14 @@ pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { f(buf[..amt]) } -#[deprecated = "use fmt::radix"] -impl ToStrRadix for $T { - /// Convert to a string in a given base. - #[inline] - fn to_str_radix(&self, radix: uint) -> String { - format!("{}", ::fmt::radix(*self, radix as u8)) - } -} - #[cfg(test)] mod tests { use prelude::*; use super::*; - use num::ToStrRadix; use str::StrSlice; use u16; - #[test] - pub fn test_to_string() { - assert_eq!((0 as $T).to_str_radix(10u), "0".to_string()); - assert_eq!((1 as $T).to_str_radix(10u), "1".to_string()); - assert_eq!((2 as $T).to_str_radix(10u), "2".to_string()); - assert_eq!((11 as $T).to_str_radix(10u), "11".to_string()); - assert_eq!((11 as $T).to_str_radix(16u), "b".to_string()); - assert_eq!((255 as $T).to_str_radix(16u), "ff".to_string()); - assert_eq!((0xff as $T).to_str_radix(10u), "255".to_string()); - } - #[test] pub fn test_from_str() { assert_eq!(from_str::<$T>("0"), Some(0u as $T)); @@ -199,18 +178,6 @@ mod tests { assert_eq!(from_str::("0"), Some(u64_val)); assert!(from_str::("-1").is_none()); } - - #[test] - #[should_fail] - pub fn to_str_radix1() { - 100u.to_str_radix(1u); - } - - #[test] - #[should_fail] - pub fn to_str_radix37() { - 100u.to_str_radix(37u); - } } )) diff --git a/src/libstd/sync/mod.rs b/src/libstd/sync/mod.rs index 8cfa1ebd598..38e1e952f77 100644 --- a/src/libstd/sync/mod.rs +++ b/src/libstd/sync/mod.rs @@ -26,9 +26,6 @@ pub use core_sync::{RWLock, RWLockReadGuard, RWLockWriteGuard}; pub use core_sync::{Semaphore, SemaphoreGuard}; pub use core_sync::one::{Once, ONCE_INIT}; -#[deprecated = "use atomic instead"] -pub use core_sync::atomic as atomics; - pub use self::future::Future; pub use self::task_pool::TaskPool; diff --git a/src/libstd/task.rs b/src/libstd/task.rs index 04d3bb8b3a7..1d1e6ae4feb 100644 --- a/src/libstd/task.rs +++ b/src/libstd/task.rs @@ -225,26 +225,6 @@ impl TaskBuilder { } } - /// Add a wrapper to the body of the spawned task. - /// - /// Before the task is spawned it is passed through a 'body generator' - /// function that may perform local setup operations as well as wrap - /// the task body in remote setup operations. With this the behavior - /// of tasks can be extended in simple ways. - /// - /// This function augments the current body generator with a new body - /// generator by applying the task body which results from the - /// existing body generator to the new body generator. - #[deprecated = "this function will be removed soon"] - pub fn with_wrapper(mut self, wrapper: proc(v: proc():Send):Send -> proc():Send) - -> TaskBuilder { - self.gen_body = match self.gen_body.take() { - Some(prev) => Some(proc(body) { wrapper(prev(body)) }), - None => Some(wrapper) - }; - self - } - // Where spawning actually happens (whether yielding a future or not) fn spawn_internal(self, f: proc():Send, on_exit: Option>):Send>) { @@ -353,18 +333,6 @@ pub fn try_future(f: proc():Send -> T) -> Future(blk: |Option<&str>| -> U) -> U { - use rt::task::Task; - - let task = Local::borrow(None::); - match task.name { - Some(ref name) => blk(Some(name.as_slice())), - None => blk(None) - } -} - /// Read the name of the current task. #[stable] pub fn name() -> Option { @@ -446,20 +414,6 @@ mod test { rx.recv(); } - #[test] - #[allow(deprecated)] - fn test_with_wrapper() { - let (tx, rx) = channel(); - TaskBuilder::new().with_wrapper(proc(body) { - let result: proc():Send = proc() { - body(); - tx.send(()); - }; - result - }).spawn(proc() { }); - rx.recv(); - } - #[test] fn test_try_future() { let result = TaskBuilder::new().try_future(proc() {}); diff --git a/src/libsync/comm/duplex.rs b/src/libsync/comm/duplex.rs deleted file mode 100644 index 1dc1f4b87f2..00000000000 --- a/src/libsync/comm/duplex.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2012-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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! - -Higher level communication abstractions. - -*/ - -#![allow(missing_doc)] -#![allow(deprecated)] -#![deprecated = "This type is replaced by having a pair of channels. This type \ - is not fully composable with other channels in terms of \ - or possible semantics on a duplex stream. It will be removed \ - soon"] - -use core::prelude::*; - -use comm; -use comm::{Sender, Receiver, channel}; - -/// An extension of `pipes::stream` that allows both sending and receiving. -pub struct DuplexStream { - tx: Sender, - rx: Receiver, -} - -/// Creates a bidirectional stream. -pub fn duplex() -> (DuplexStream, DuplexStream) { - let (tx1, rx1) = channel(); - let (tx2, rx2) = channel(); - (DuplexStream { tx: tx1, rx: rx2 }, - DuplexStream { tx: tx2, rx: rx1 }) -} - -// Allow these methods to be used without import: -impl DuplexStream { - pub fn send(&self, x: S) { - self.tx.send(x) - } - pub fn send_opt(&self, x: S) -> Result<(), S> { - self.tx.send_opt(x) - } - pub fn recv(&self) -> R { - self.rx.recv() - } - pub fn try_recv(&self) -> Result { - self.rx.try_recv() - } - pub fn recv_opt(&self) -> Result { - self.rx.recv_opt() - } -} - -#[allow(deprecated)] -#[cfg(test)] -mod test { - use std::prelude::*; - use comm::duplex; - - #[test] - pub fn duplex_stream_1() { - let (left, right) = duplex(); - - left.send("abc".to_string()); - right.send(123i); - - assert!(left.recv() == 123); - assert!(right.recv() == "abc".to_string()); - } -} diff --git a/src/libsync/comm/mod.rs b/src/libsync/comm/mod.rs index 4e66dd69a60..ddfd1088a41 100644 --- a/src/libsync/comm/mod.rs +++ b/src/libsync/comm/mod.rs @@ -333,7 +333,6 @@ use rustrt::local::Local; use rustrt::task::{Task, BlockedTask}; pub use comm::select::{Select, Handle}; -pub use comm::duplex::{DuplexStream, duplex}; macro_rules! test ( { fn $name:ident() $b:block $(#[$a:meta])*} => ( @@ -354,14 +353,13 @@ macro_rules! test ( $(#[$a])* #[test] fn native() { use native; let (tx, rx) = channel(); - native::task::spawn(proc() { tx.send(f()) }); + spawn(proc() { tx.send(f()) }); rx.recv(); } } ) ) -mod duplex; mod oneshot; mod select; mod shared; @@ -1064,7 +1062,6 @@ impl Drop for Receiver { mod test { use std::prelude::*; - use native; use std::os; use super::*; @@ -1224,7 +1221,7 @@ mod test { tx3.send(()); }); rx1.recv(); - native::task::spawn(proc() { + spawn(proc() { for _ in range(0i, 40) { tx2.send(1); } @@ -1238,7 +1235,7 @@ mod test { fn recv_from_outside_runtime() { let (tx, rx) = channel::(); let (dtx, drx) = channel(); - native::task::spawn(proc() { + spawn(proc() { for _ in range(0i, 40) { assert_eq!(rx.recv(), 1); } @@ -1256,12 +1253,12 @@ mod test { let (tx2, rx2) = channel::(); let (tx3, rx3) = channel::<()>(); let tx4 = tx3.clone(); - native::task::spawn(proc() { + spawn(proc() { assert_eq!(rx1.recv(), 1); tx2.send(2); tx4.send(()); }); - native::task::spawn(proc() { + spawn(proc() { tx1.send(1); assert_eq!(rx2.recv(), 2); tx3.send(()); diff --git a/src/libsync/mpmc_bounded_queue.rs b/src/libsync/mpmc_bounded_queue.rs index fa29bb6088a..b3b504f49ca 100644 --- a/src/libsync/mpmc_bounded_queue.rs +++ b/src/libsync/mpmc_bounded_queue.rs @@ -167,7 +167,6 @@ impl Clone for Queue { mod tests { use std::prelude::*; use super::Queue; - use native; #[test] fn test() { @@ -180,7 +179,7 @@ mod tests { for _ in range(0, nthreads) { let q = q.clone(); let tx = tx.clone(); - native::task::spawn(proc() { + spawn(proc() { let q = q; for i in range(0, nmsgs) { assert!(q.push(i)); @@ -194,7 +193,7 @@ mod tests { let (tx, rx) = channel(); completion_rxs.push(rx); let q = q.clone(); - native::task::spawn(proc() { + spawn(proc() { let q = q; let mut i = 0u; loop { diff --git a/src/libsync/mpsc_queue.rs b/src/libsync/mpsc_queue.rs index ad2539fc260..ac2acf3d7d4 100644 --- a/src/libsync/mpsc_queue.rs +++ b/src/libsync/mpsc_queue.rs @@ -161,7 +161,6 @@ mod tests { use alloc::arc::Arc; - use native; use super::{Queue, Data, Empty, Inconsistent}; #[test] @@ -186,7 +185,7 @@ mod tests { for _ in range(0, nthreads) { let tx = tx.clone(); let q = q.clone(); - native::task::spawn(proc() { + spawn(proc() { for i in range(0, nmsgs) { q.push(i); } diff --git a/src/libsync/mutex.rs b/src/libsync/mutex.rs index 796c62354c3..7d191eab2d1 100644 --- a/src/libsync/mutex.rs +++ b/src/libsync/mutex.rs @@ -525,7 +525,6 @@ impl Drop for Mutex { mod test { use std::prelude::*; use super::{Mutex, StaticMutex, MUTEX_INIT}; - use native; #[test] fn smoke() { @@ -563,7 +562,7 @@ mod test { let (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); - native::task::spawn(proc() { inc(); tx2.send(()); }); + spawn(proc() { inc(); tx2.send(()); }); let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); } diff --git a/src/libsync/spsc_queue.rs b/src/libsync/spsc_queue.rs index cb4d33049d8..9cd64d46bad 100644 --- a/src/libsync/spsc_queue.rs +++ b/src/libsync/spsc_queue.rs @@ -296,8 +296,6 @@ impl Drop for Queue { mod test { use std::prelude::*; - use native; - use super::{queue}; #[test] @@ -364,7 +362,7 @@ mod test { let (consumer, mut producer) = queue(bound); let (tx, rx) = channel(); - native::task::spawn(proc() { + spawn(proc() { // Move the consumer to a local mutable slot let mut consumer = consumer; for _ in range(0u, 100000) { diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index fb5373cee00..60e4db405d7 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -699,8 +699,12 @@ struct NodeCollector<'ast> { impl<'ast> NodeCollector<'ast> { fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) { - self.map.grow_set(id as uint, &NotPresent, entry); debug!("ast_map: {} => {}", id, entry); + let len = self.map.len(); + if id as uint >= len { + self.map.grow(id as uint - len + 1, NotPresent); + } + *self.map.get_mut(id as uint) = entry; } fn insert(&mut self, id: NodeId, node: Node<'ast>) { diff --git a/src/libsyntax/ast_util.rs b/src/libsyntax/ast_util.rs index 726aceb5819..5626f0a8ad9 100644 --- a/src/libsyntax/ast_util.rs +++ b/src/libsyntax/ast_util.rs @@ -202,7 +202,7 @@ pub fn impl_pretty_name(trait_ref: &Option, ty: &Ty) -> Ident { let mut pretty = pprust::ty_to_string(ty); match *trait_ref { Some(ref trait_ref) => { - pretty.push_char('.'); + pretty.push('.'); pretty.push_str(pprust::path_to_string(&trait_ref.path).as_slice()); } None => {} diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 5d96cc359c2..4df334a3f2c 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -283,9 +283,9 @@ impl FileMap { /// filemap.start_pos + newline_offset_relative_to_the_start_of_filemap. pub fn next_line(&self, pos: BytePos) { // the new charpos must be > the last one (or it's the first one). - let mut lines = self.lines.borrow_mut();; + let mut lines = self.lines.borrow_mut(); let line_len = lines.len(); - assert!(line_len == 0 || (*lines.get(line_len - 1) < pos)) + assert!(line_len == 0 || ((*lines)[line_len - 1] < pos)) lines.push(pos); } @@ -293,7 +293,7 @@ impl FileMap { /// pub fn get_line(&self, line: int) -> String { let lines = self.lines.borrow(); - let begin: BytePos = *lines.get(line as uint) - self.start_pos; + let begin: BytePos = (*lines)[line as uint] - self.start_pos; let begin = begin.to_uint(); let slice = self.src.as_slice().slice_from(begin); match slice.find('\n') { @@ -351,7 +351,7 @@ impl CodeMap { // overflowing into the next filemap in case the last byte of span is also the last // byte of filemap, which leads to incorrect results from CodeMap.span_to_*. if src.len() > 0 && !src.as_slice().ends_with("\n") { - src.push_char('\n'); + src.push('\n'); } let filemap = Rc::new(FileMap { @@ -446,7 +446,7 @@ impl CodeMap { pub fn lookup_byte_offset(&self, bpos: BytePos) -> FileMapAndBytePos { let idx = self.lookup_filemap_idx(bpos); - let fm = self.files.borrow().get(idx).clone(); + let fm = (*self.files.borrow())[idx].clone(); let offset = bpos - fm.start_pos; FileMapAndBytePos {fm: fm, pos: offset} } @@ -455,7 +455,7 @@ impl CodeMap { pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { let idx = self.lookup_filemap_idx(bpos); let files = self.files.borrow(); - let map = files.get(idx); + let map = &(*files)[idx]; // The number of extra bytes due to multibyte chars in the FileMap let mut total_extra_bytes = 0; @@ -480,34 +480,37 @@ impl CodeMap { fn lookup_filemap_idx(&self, pos: BytePos) -> uint { let files = self.files.borrow(); - let files = files; + let files = &*files; let len = files.len(); let mut a = 0u; let mut b = len; while b - a > 1u { let m = (a + b) / 2u; - if files.get(m).start_pos > pos { + if files[m].start_pos > pos { b = m; } else { a = m; } } - // There can be filemaps with length 0. These have the same start_pos as the previous - // filemap, but are not the filemaps we want (because they are length 0, they cannot - // contain what we are looking for). So, rewind until we find a useful filemap. + // There can be filemaps with length 0. These have the same start_pos as + // the previous filemap, but are not the filemaps we want (because they + // are length 0, they cannot contain what we are looking for). So, + // rewind until we find a useful filemap. loop { - let lines = files.get(a).lines.borrow(); + let lines = files[a].lines.borrow(); let lines = lines; if lines.len() > 0 { break; } if a == 0 { - fail!("position {} does not resolve to a source location", pos.to_uint()); + fail!("position {} does not resolve to a source location", + pos.to_uint()); } a -= 1; } if a >= len { - fail!("position {} does not resolve to a source location", pos.to_uint()) + fail!("position {} does not resolve to a source location", + pos.to_uint()) } return a; @@ -517,14 +520,14 @@ impl CodeMap { let idx = self.lookup_filemap_idx(pos); let files = self.files.borrow(); - let f = files.get(idx).clone(); + let f = (*files)[idx].clone(); let mut a = 0u; { let lines = f.lines.borrow(); let mut b = lines.len(); while b - a > 1u { let m = (a + b) / 2u; - if *lines.get(m) > pos { b = m; } else { a = m; } + if (*lines)[m] > pos { b = m; } else { a = m; } } } FileMapAndLine {fm: f, line: a} @@ -534,7 +537,7 @@ impl CodeMap { let FileMapAndLine {fm: f, line: a} = self.lookup_line(pos); let line = a + 1u; // Line numbers start at 1 let chpos = self.bytepos_to_file_charpos(pos); - let linebpos = *f.lines.borrow().get(a); + let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); debug!("byte pos {} is on the line at byte pos {}", pos, linebpos); @@ -704,7 +707,7 @@ mod test { assert_eq!(file_lines.file.name, "blork.rs".to_string()); assert_eq!(file_lines.lines.len(), 1); - assert_eq!(*file_lines.lines.get(0), 1u); + assert_eq!(file_lines.lines[0], 1u); } #[test] diff --git a/src/libsyntax/crateid.rs b/src/libsyntax/crateid.rs deleted file mode 100644 index 67605360a48..00000000000 --- a/src/libsyntax/crateid.rs +++ /dev/null @@ -1,216 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use std::fmt; - -/// CrateIds identify crates and include the crate name and optionally a path -/// and version. In the full form, they look like relative URLs. Example: -/// `github.com/rust-lang/rust#std:1.0` would be a package ID with a path of -/// `github.com/rust-lang/rust` and a crate name of `std` with a version of -/// `1.0`. If no crate name is given after the hash, the name is inferred to -/// be the last component of the path. If no version is given, it is inferred -/// to be `0.0`. - -use std::from_str::FromStr; - -#[deriving(Clone, PartialEq)] -pub struct CrateId { - /// A path which represents the codes origin. By convention this is the - /// URL, without `http://` or `https://` prefix, to the crate's repository - pub path: String, - /// The name of the crate. - pub name: String, - /// The version of the crate. - pub version: Option, -} - -impl fmt::Show for CrateId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.path)); - let version = match self.version { - None => "0.0", - Some(ref version) => version.as_slice(), - }; - if self.path == self.name || - self.path - .as_slice() - .ends_with(format!("/{}", self.name).as_slice()) { - write!(f, "#{}", version) - } else { - write!(f, "#{}:{}", self.name, version) - } - } -} - -impl FromStr for CrateId { - fn from_str(s: &str) -> Option { - let pieces: Vec<&str> = s.splitn(1, '#').collect(); - let path = pieces.get(0).to_string(); - - if path.as_slice().starts_with("/") || path.as_slice().ends_with("/") || - path.as_slice().starts_with(".") || path.is_empty() { - return None; - } - - let path_pieces: Vec<&str> = path.as_slice() - .rsplitn(1, '/') - .collect(); - let inferred_name = *path_pieces.get(0); - - let (name, version) = if pieces.len() == 1 { - (inferred_name.to_string(), None) - } else { - let hash_pieces: Vec<&str> = pieces.get(1) - .splitn(1, ':') - .collect(); - let (hash_name, hash_version) = if hash_pieces.len() == 1 { - ("", *hash_pieces.get(0)) - } else { - (*hash_pieces.get(0), *hash_pieces.get(1)) - }; - - let name = if !hash_name.is_empty() { - hash_name.to_string() - } else { - inferred_name.to_string() - }; - - let version = if !hash_version.is_empty() { - if hash_version == "0.0" { - None - } else { - Some(hash_version.to_string()) - } - } else { - None - }; - - (name, version) - }; - - Some(CrateId { - path: path.to_string(), - name: name, - version: version, - }) - } -} - -impl CrateId { - pub fn version_or_default<'a>(&'a self) -> &'a str { - match self.version { - None => "0.0", - Some(ref version) => version.as_slice(), - } - } - - pub fn short_name_with_version(&self) -> String { - format!("{}-{}", self.name, self.version_or_default()) - } - - pub fn matches(&self, other: &CrateId) -> bool { - // FIXME: why does this not match on `path`? - if self.name != other.name { return false } - match (&self.version, &other.version) { - (&Some(ref v1), &Some(ref v2)) => v1 == v2, - _ => true, - } - } -} - -#[test] -fn bare_name() { - let crateid: CrateId = from_str("foo").expect("valid crateid"); - assert_eq!(crateid.name, "foo".to_string()); - assert_eq!(crateid.version, None); - assert_eq!(crateid.path, "foo".to_string()); -} - -#[test] -fn bare_name_single_char() { - let crateid: CrateId = from_str("f").expect("valid crateid"); - assert_eq!(crateid.name, "f".to_string()); - assert_eq!(crateid.version, None); - assert_eq!(crateid.path, "f".to_string()); -} - -#[test] -fn empty_crateid() { - let crateid: Option = from_str(""); - assert!(crateid.is_none()); -} - -#[test] -fn simple_path() { - let crateid: CrateId = from_str("example.com/foo/bar").expect("valid crateid"); - assert_eq!(crateid.name, "bar".to_string()); - assert_eq!(crateid.version, None); - assert_eq!(crateid.path, "example.com/foo/bar".to_string()); -} - -#[test] -fn simple_version() { - let crateid: CrateId = from_str("foo#1.0").expect("valid crateid"); - assert_eq!(crateid.name, "foo".to_string()); - assert_eq!(crateid.version, Some("1.0".to_string())); - assert_eq!(crateid.path, "foo".to_string()); -} - -#[test] -fn absolute_path() { - let crateid: Option = from_str("/foo/bar"); - assert!(crateid.is_none()); -} - -#[test] -fn path_ends_with_slash() { - let crateid: Option = from_str("foo/bar/"); - assert!(crateid.is_none()); -} - -#[test] -fn path_and_version() { - let crateid: CrateId = from_str("example.com/foo/bar#1.0").expect("valid crateid"); - assert_eq!(crateid.name, "bar".to_string()); - assert_eq!(crateid.version, Some("1.0".to_string())); - assert_eq!(crateid.path, "example.com/foo/bar".to_string()); -} - -#[test] -fn single_chars() { - let crateid: CrateId = from_str("a/b#1").expect("valid crateid"); - assert_eq!(crateid.name, "b".to_string()); - assert_eq!(crateid.version, Some("1".to_string())); - assert_eq!(crateid.path, "a/b".to_string()); -} - -#[test] -fn missing_version() { - let crateid: CrateId = from_str("foo#").expect("valid crateid"); - assert_eq!(crateid.name, "foo".to_string()); - assert_eq!(crateid.version, None); - assert_eq!(crateid.path, "foo".to_string()); -} - -#[test] -fn path_and_name() { - let crateid: CrateId = from_str("foo/rust-bar#bar:1.0").expect("valid crateid"); - assert_eq!(crateid.name, "bar".to_string()); - assert_eq!(crateid.version, Some("1.0".to_string())); - assert_eq!(crateid.path, "foo/rust-bar".to_string()); -} - -#[test] -fn empty_name() { - let crateid: CrateId = from_str("foo/bar#:1.0").expect("valid crateid"); - assert_eq!(crateid.name, "bar".to_string()); - assert_eq!(crateid.version, Some("1.0".to_string())); - assert_eq!(crateid.path, "foo/bar".to_string()); -} diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 9782f301667..3da1b1f3175 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -446,7 +446,7 @@ fn highlight_lines(err: &mut EmitterWriter, if lines.lines.len() == 1u { let lo = cm.lookup_char_pos(sp.lo); let mut digits = 0u; - let mut num = (*lines.lines.get(0) + 1u) / 10u; + let mut num = (lines.lines[0] + 1u) / 10u; // how many digits must be indent past? while num > 0u { num /= 10u; digits += 1u; } @@ -458,9 +458,9 @@ fn highlight_lines(err: &mut EmitterWriter, // part of the 'filename:line ' part of the previous line. let skip = fm.name.len() + digits + 3u; for _ in range(0, skip) { - s.push_char(' '); + s.push(' '); } - let orig = fm.get_line(*lines.lines.get(0) as int); + let orig = fm.get_line(lines.lines[0] as int); for pos in range(0u, left-skip) { let cur_char = orig.as_bytes()[pos] as char; // Whenever a tab occurs on the previous line, we insert one on @@ -468,8 +468,8 @@ fn highlight_lines(err: &mut EmitterWriter, // That way the squiggly line will usually appear in the correct // position. match cur_char { - '\t' => s.push_char('\t'), - _ => s.push_char(' '), + '\t' => s.push('\t'), + _ => s.push(' '), }; } try!(write!(&mut err.dst, "{}", s)); @@ -479,7 +479,7 @@ fn highlight_lines(err: &mut EmitterWriter, // the ^ already takes up one space let num_squigglies = hi.col.to_uint()-lo.col.to_uint()-1u; for _ in range(0, num_squigglies) { - s.push_char('~'); + s.push('~'); } } try!(print_maybe_styled(err, @@ -523,10 +523,10 @@ fn custom_highlight_lines(w: &mut EmitterWriter, let skip = last_line_start.len() + hi.col.to_uint() - 1; let mut s = String::new(); for _ in range(0, skip) { - s.push_char(' '); + s.push(' '); } - s.push_char('^'); - s.push_char('\n'); + s.push('^'); + s.push('\n'); print_maybe_styled(w, s.as_slice(), term::attr::ForegroundColor(lvl.color())) diff --git a/src/libsyntax/ext/base.rs b/src/libsyntax/ext/base.rs index 63d45939c2a..5cc2fe03618 100644 --- a/src/libsyntax/ext/base.rs +++ b/src/libsyntax/ext/base.rs @@ -495,7 +495,7 @@ impl<'a> ExtCtxt<'a> { pub fn new_parser_from_tts(&self, tts: &[ast::TokenTree]) -> parser::Parser<'a> { - parse::tts_to_parser(self.parse_sess, Vec::from_slice(tts), self.cfg()) + parse::tts_to_parser(self.parse_sess, tts.to_vec(), self.cfg()) } pub fn codemap(&self) -> &'a CodeMap { &self.parse_sess.span_diagnostic.cm } diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 98ac6fe6a6c..437efbf96f8 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -618,7 +618,7 @@ impl<'a> AstBuilder for ExtCtxt<'a> { ident: ast::Ident, mut args: Vec> ) -> P { let id = Spanned { node: ident, span: span }; - args.unshift(expr); + args.insert(0, expr); self.expr(span, ast::ExprMethodCall(id, Vec::new(), args)) } fn expr_block(&self, b: P) -> P { diff --git a/src/libsyntax/ext/concat.rs b/src/libsyntax/ext/concat.rs index cd3e247a806..af7cd4157ec 100644 --- a/src/libsyntax/ext/concat.rs +++ b/src/libsyntax/ext/concat.rs @@ -35,7 +35,7 @@ pub fn expand_syntax_ext(cx: &mut base::ExtCtxt, accumulator.push_str(s.get()); } ast::LitChar(c) => { - accumulator.push_char(c); + accumulator.push(c); } ast::LitInt(i, ast::UnsignedIntLit(_)) | ast::LitInt(i, ast::SignedIntLit(_, ast::Plus)) | diff --git a/src/libsyntax/ext/deriving/clone.rs b/src/libsyntax/ext/deriving/clone.rs index 64607ffd5d4..9748b531345 100644 --- a/src/libsyntax/ext/deriving/clone.rs +++ b/src/libsyntax/ext/deriving/clone.rs @@ -80,7 +80,7 @@ fn cs_clone( } } - if all_fields.len() >= 1 && all_fields.get(0).name.is_none() { + if all_fields.len() >= 1 && all_fields[0].name.is_none() { // enum-like let subcalls = all_fields.iter().map(subcall).collect(); cx.expr_call_ident(trait_span, ctor_ident, subcalls) diff --git a/src/libsyntax/ext/deriving/generic/mod.rs b/src/libsyntax/ext/deriving/generic/mod.rs index 10c045b811a..2310a4460e2 100644 --- a/src/libsyntax/ext/deriving/generic/mod.rs +++ b/src/libsyntax/ext/deriving/generic/mod.rs @@ -447,10 +447,12 @@ impl<'a> TraitDef<'a> { attr::mark_used(&attr); let opt_trait_ref = Some(trait_ref); let ident = ast_util::impl_pretty_name(&opt_trait_ref, &*self_type); + let mut a = vec![attr]; + a.extend(self.attributes.iter().map(|a| a.clone())); cx.item( self.span, ident, - (vec!(attr)).append(self.attributes.as_slice()), + a, ast::ItemImpl(trait_generics, opt_trait_ref, self_type, @@ -943,8 +945,8 @@ impl<'a> MethodDef<'a> { // of them (using `field_index` tracked above). // That is the heart of the transposition. let others = self_pats_idents.iter().map(|fields| { - let &(_, _opt_ident, ref other_getter_expr) = - fields.get(field_index); + let (_, _opt_ident, ref other_getter_expr) = + fields[field_index]; // All Self args have same variant, so // opt_idents are the same. (Assert diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index 16ce264fe71..322a84eaa2b 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -80,7 +80,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, EnumMatching(_, _, ref fields) if fields.len() == 0 => {} Struct(ref fields) | EnumMatching(_, _, ref fields) => { - if fields.get(0).name.is_none() { + if fields[0].name.is_none() { // tuple struct/"normal" variant format_string.push_str("("); diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index c792d4b99ee..39b710e0d57 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -165,7 +165,7 @@ pub fn expand_expr(e: P, fld: &mut MacroExpander) -> P { let mut arms = Vec::with_capacity(else_if_arms.len() + 2); arms.push(pat_arm); - arms.push_all_move(else_if_arms); + arms.extend(else_if_arms.into_iter()); arms.push(else_arm); let match_expr = fld.cx.expr(span, ast::ExprMatch(expr, arms, ast::MatchIfLetDesugar)); @@ -257,7 +257,7 @@ fn expand_mac_invoc(mac: ast::Mac, span: codemap::Span, // let compilation continue return None; } - let extname = pth.segments.get(0).identifier; + let extname = pth.segments[0].identifier; let extnamestr = token::get_ident(extname); match fld.cx.syntax_env.find(&extname.name) { None => { @@ -505,7 +505,7 @@ pub fn expand_item_mac(it: P, fld: &mut MacroExpander) node: MacInvocTT(ref pth, ref tts, _), .. }) => { - (pth.segments.get(0).identifier, pth.span, (*tts).clone()) + (pth.segments[0].identifier, pth.span, (*tts).clone()) } _ => fld.cx.span_bug(it.span, "invalid item macro invocation") }; @@ -695,7 +695,8 @@ fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroE rename_fld.fold_pat(expanded_pat) }; // add them to the existing pending renames: - fld.cx.syntax_env.info().pending_renames.push_all_move(new_pending_renames); + fld.cx.syntax_env.info().pending_renames + .extend(new_pending_renames.into_iter()); Local { id: id, ty: expanded_ty, @@ -744,7 +745,7 @@ fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm { } // all of the pats must have the same set of bindings, so use the // first one to extract them and generate new names: - let idents = pattern_bindings(&**expanded_pats.get(0)); + let idents = pattern_bindings(&*expanded_pats[0]); let new_renames = idents.into_iter().map(|id| (id, fresh_name(&id))).collect(); // apply the renaming, but only to the PatIdents: let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames}; @@ -860,7 +861,7 @@ fn expand_pat(p: P, fld: &mut MacroExpander) -> P { fld.cx.span_err(pth.span, "expected macro name without module separators"); return DummyResult::raw_pat(span); } - let extname = pth.segments.get(0).identifier; + let extname = pth.segments[0].identifier; let extnamestr = token::get_ident(extname); let marked_after = match fld.cx.syntax_env.find(&extname.name) { None => { @@ -1022,7 +1023,7 @@ fn expand_method(m: P, fld: &mut MacroExpander) -> SmallVector *shouldmatch.iter().max().unwrap())); @@ -1630,16 +1631,15 @@ mod test { let string = token::get_ident(final_varref_ident); println!("varref's first segment's string: \"{}\"", string.get()); println!("binding #{}: {}, resolves to {}", - binding_idx, *bindings.get(binding_idx), binding_name); + binding_idx, bindings[binding_idx], binding_name); mtwt::with_sctable(|x| mtwt::display_sctable(x)); }; if shouldmatch.contains(&idx) { // it should be a path of length 1, and it should // be free-identifier=? or bound-identifier=? to the given binding assert_eq!(varref.segments.len(),1); - let varref_name = mtwt::resolve(varref.segments.get(0).identifier); - let varref_marks = mtwt::marksof(varref.segments - .get(0) + let varref_name = mtwt::resolve(varref.segments[0].identifier); + let varref_marks = mtwt::marksof(varref.segments[0] .identifier .ctxt, invalid_name); @@ -1654,7 +1654,7 @@ mod test { assert_eq!(varref_marks,binding_marks.clone()); } } else { - let varref_name = mtwt::resolve(varref.segments.get(0).identifier); + let varref_name = mtwt::resolve(varref.segments[0].identifier); let fail = (varref.segments.len() == 1) && (varref_name == binding_name); // temp debugging: @@ -1696,19 +1696,19 @@ foo_module!() // the xx binding should bind all of the xx varrefs: for (idx,v) in varrefs.iter().filter(|p| { p.segments.len() == 1 - && "xx" == token::get_ident(p.segments.get(0).identifier).get() + && "xx" == token::get_ident(p.segments[0].identifier).get() }).enumerate() { - if mtwt::resolve(v.segments.get(0).identifier) != resolved_binding { + if mtwt::resolve(v.segments[0].identifier) != resolved_binding { println!("uh oh, xx binding didn't match xx varref:"); println!("this is xx varref \\# {}", idx); println!("binding: {}", cxbind); println!("resolves to: {}", resolved_binding); - println!("varref: {}", v.segments.get(0).identifier); + println!("varref: {}", v.segments[0].identifier); println!("resolves to: {}", - mtwt::resolve(v.segments.get(0).identifier)); + mtwt::resolve(v.segments[0].identifier)); mtwt::with_sctable(|x| mtwt::display_sctable(x)); } - assert_eq!(mtwt::resolve(v.segments.get(0).identifier), + assert_eq!(mtwt::resolve(v.segments[0].identifier), resolved_binding); }; } diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 07f0ca85f35..87cd61c9b22 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -241,13 +241,13 @@ impl<'a, 'b> Context<'a, 'b> { return; } { - let arg_type = match self.arg_types.get(arg) { - &None => None, - &Some(ref x) => Some(x) + let arg_type = match self.arg_types[arg] { + None => None, + Some(ref x) => Some(x) }; - self.verify_same(self.args.get(arg).span, &ty, arg_type); + self.verify_same(self.args[arg].span, &ty, arg_type); } - if self.arg_types.get(arg).is_none() { + if self.arg_types[arg].is_none() { *self.arg_types.get_mut(arg) = Some(ty); } } @@ -544,7 +544,7 @@ impl<'a, 'b> Context<'a, 'b> { // of each variable because we don't want to move out of the arguments // passed to this function. for (i, e) in self.args.into_iter().enumerate() { - let arg_ty = match self.arg_types.get(i).as_ref() { + let arg_ty = match self.arg_types[i].as_ref() { Some(ty) => ty, None => continue // error already generated }; @@ -568,7 +568,7 @@ impl<'a, 'b> Context<'a, 'b> { let lname = self.ecx.ident_of(format!("__arg{}", *name).as_slice()); pats.push(self.ecx.pat_ident(e.span, lname)); - *names.get_mut(*self.name_positions.get(name)) = + *names.get_mut(self.name_positions[*name]) = Some(Context::format_arg(self.ecx, e.span, arg_ty, self.ecx.expr_ident(e.span, lname))); heads.push(self.ecx.expr_addr_of(e.span, e)); @@ -787,7 +787,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, None => break } } - match parser.errors.shift() { + match parser.errors.remove(0) { Some(error) => { cx.ecx.span_err(cx.fmtsp, format!("invalid format string: {}", @@ -804,7 +804,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span, // Make sure that all arguments were used and all arguments have types. for (i, ty) in cx.arg_types.iter().enumerate() { if ty.is_none() { - cx.ecx.span_err(cx.args.get(i).span, "argument never used"); + cx.ecx.span_err(cx.args[i].span, "argument never used"); } } for (name, e) in cx.names.iter() { diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 523299abce1..b4f8b9f8228 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -188,7 +188,7 @@ fn resolve_internal(id: Ident, } let resolved = { - let result = *table.table.borrow().get(id.ctxt as uint); + let result = (*table.table.borrow())[id.ctxt as uint]; match result { EmptyCtxt => id.name, // ignore marks here: @@ -232,7 +232,7 @@ fn marksof_internal(ctxt: SyntaxContext, let mut result = Vec::new(); let mut loopvar = ctxt; loop { - let table_entry = *table.table.borrow().get(loopvar as uint); + let table_entry = (*table.table.borrow())[loopvar as uint]; match table_entry { EmptyCtxt => { return result; @@ -259,7 +259,7 @@ fn marksof_internal(ctxt: SyntaxContext, /// FAILS when outside is not a mark. pub fn outer_mark(ctxt: SyntaxContext) -> Mrk { with_sctable(|sctable| { - match *sctable.table.borrow().get(ctxt as uint) { + match (*sctable.table.borrow())[ctxt as uint] { Mark(mrk, _) => mrk, _ => fail!("can't retrieve outer mark when outside is not a mark") } @@ -330,7 +330,7 @@ mod tests { let mut result = Vec::new(); loop { let table = table.table.borrow(); - match *table.get(sc as uint) { + match (*table)[sc as uint] { EmptyCtxt => {return result;}, Mark(mrk,tail) => { result.push(M(mrk)); @@ -355,9 +355,9 @@ mod tests { assert_eq!(unfold_test_sc(test_sc.clone(),EMPTY_CTXT,&mut t),4); { let table = t.table.borrow(); - assert!(*table.get(2) == Mark(9,0)); - assert!(*table.get(3) == Rename(id(101,0),Name(14),2)); - assert!(*table.get(4) == Mark(3,3)); + assert!((*table)[2] == Mark(9,0)); + assert!((*table)[3] == Rename(id(101,0),Name(14),2)); + assert!((*table)[4] == Mark(3,3)); } assert_eq!(refold_test_sc(4,&t),test_sc); } @@ -376,8 +376,8 @@ mod tests { assert_eq!(unfold_marks(vec!(3,7),EMPTY_CTXT,&mut t),3); { let table = t.table.borrow(); - assert!(*table.get(2) == Mark(7,0)); - assert!(*table.get(3) == Mark(3,2)); + assert!((*table)[2] == Mark(7,0)); + assert!((*table)[3] == Mark(3,2)); } } diff --git a/src/libsyntax/ext/quote.rs b/src/libsyntax/ext/quote.rs index e8949c4aa4f..84775c12d64 100644 --- a/src/libsyntax/ext/quote.rs +++ b/src/libsyntax/ext/quote.rs @@ -657,18 +657,20 @@ fn mk_tt(cx: &ExtCtxt, sp: Span, tt: &ast::TokenTree) -> Vec> { ast::TTNonterminal(sp, ident) => { - // tt.push_all_move($ident.to_tokens(ext_cx)) + // tt.extend($ident.to_tokens(ext_cx).into_iter()) let e_to_toks = cx.expr_method_call(sp, cx.expr_ident(sp, ident), id_ext("to_tokens"), vec!(cx.expr_ident(sp, id_ext("ext_cx")))); + let e_to_toks = + cx.expr_method_call(sp, e_to_toks, id_ext("into_iter"), vec![]); let e_push = cx.expr_method_call(sp, cx.expr_ident(sp, id_ext("tt")), - id_ext("push_all_move"), + id_ext("extend"), vec!(e_to_toks)); vec!(cx.stmt_expr(e_push)) @@ -680,7 +682,7 @@ fn mk_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Vec> { let mut ss = Vec::new(); for tt in tts.iter() { - ss.push_all_move(mk_tt(cx, sp, tt)); + ss.extend(mk_tt(cx, sp, tt).into_iter()); } ss } @@ -742,7 +744,7 @@ fn expand_tts(cx: &ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let stmt_let_tt = cx.stmt_let(sp, true, id_ext("tt"), cx.expr_vec_ng(sp)); let mut vector = vec!(stmt_let_sp, stmt_let_tt); - vector.push_all_move(mk_tts(cx, sp, tts.as_slice())); + vector.extend(mk_tts(cx, sp, tts.as_slice()).into_iter()); let block = cx.expr_block( cx.block_all(sp, Vec::new(), diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 88376108fec..78fcd729aae 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -286,7 +286,7 @@ pub fn parse(sess: &ParseSess, // Only touch the binders we have actually bound for idx in range(ei.match_lo, ei.match_hi) { - let sub = (*ei.matches.get(idx)).clone(); + let sub = (ei.matches[idx]).clone(); new_pos.matches .get_mut(idx) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, @@ -321,7 +321,7 @@ pub fn parse(sess: &ParseSess, eof_eis.push(ei); } } else { - match ei.elts.get(idx).node.clone() { + match ei.elts[idx].node.clone() { /* need to descend into sequence */ MatchSeq(ref matchers, ref sep, zero_ok, match_idx_lo, match_idx_hi) => { @@ -388,7 +388,7 @@ pub fn parse(sess: &ParseSess, if (bb_eis.len() > 0u && next_eis.len() > 0u) || bb_eis.len() > 1u { let nts = bb_eis.iter().map(|ei| { - match ei.elts.get(ei.idx).node { + match ei.elts[ei.idx].node { MatchNonterminal(bind, name, _) => { (format!("{} ('{}')", token::get_ident(name), @@ -413,7 +413,7 @@ pub fn parse(sess: &ParseSess, let mut rust_parser = Parser::new(sess, cfg.clone(), box rdr.clone()); let mut ei = bb_eis.pop().unwrap(); - match ei.elts.get(ei.idx).node { + match ei.elts[ei.idx].node { MatchNonterminal(_, name, idx) => { let name_string = token::get_ident(name); ei.matches.get_mut(idx).push(Rc::new(MatchedNonterminal( diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 7a7dbc54c9e..91db3a9d8df 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -255,12 +255,12 @@ pub fn add_new_extension<'cx>(cx: &'cx mut ExtCtxt, argument_gram); // Extract the arguments: - let lhses = match **argument_map.get(&lhs_nm) { + let lhses = match *argument_map[lhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(sp, "wrong-structured lhs") }; - let rhses = match **argument_map.get(&rhs_nm) { + let rhses = match *argument_map[rhs_nm] { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(sp, "wrong-structured rhs") }; diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 1b9f6f16542..35ec37d842a 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -79,7 +79,7 @@ fn lookup_cur_matched_by_matched(r: &TtReader, start: Rc) -> Rc ads.get(*idx).clone() + MatchedSeq(ref ads, _) => ads[*idx].clone() } }) } @@ -194,7 +194,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { let t = { let frame = r.stack.last().unwrap(); // FIXME(pcwalton): Bad copy. - (*frame.forest.get(frame.idx)).clone() + (*frame.forest)[frame.idx].clone() }; match t { TTDelim(tts) => { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 2eb3b398da8..5e29167bf1a 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -22,9 +22,10 @@ use ast::*; use ast; use ast_util; use codemap::{respan, Span, Spanned}; +use owned_slice::OwnedSlice; use parse::token; use ptr::P; -use owned_slice::OwnedSlice; +use std::ptr; use util::small_vector::SmallVector; use std::rc::Rc; @@ -36,11 +37,10 @@ pub trait MoveMap { impl MoveMap for Vec { fn move_map(mut self, f: |T| -> T) -> Vec { - use std::{mem, ptr}; for p in self.iter_mut() { unsafe { // FIXME(#5016) this shouldn't need to zero to be safe. - mem::move_val_init(p, f(ptr::read_and_zero(p))); + ptr::write(p, f(ptr::read_and_zero(p))); } } self @@ -935,7 +935,7 @@ pub fn noop_fold_item_underscore(i: Item_, folder: &mut T) -> Item_ { match *impl_item { MethodImplItem(ref x) => { for method in folder.fold_method((*x).clone()) - .move_iter() { + .into_iter() { new_impl_items.push(MethodImplItem(method)) } } @@ -963,7 +963,7 @@ pub fn noop_fold_item_underscore(i: Item_, folder: &mut T) -> Item_ { RequiredMethod(m) => { SmallVector::one(RequiredMethod( folder.fold_type_method(m))) - .move_iter() + .into_iter() } ProvidedMethod(method) => { // the awkward collect/iter idiom here is because @@ -971,15 +971,15 @@ pub fn noop_fold_item_underscore(i: Item_, folder: &mut T) -> Item_ { // trait bound, they're not actually the same type, so // the method arms don't unify. let methods: SmallVector = - folder.fold_method(method).move_iter() + folder.fold_method(method).into_iter() .map(|m| ProvidedMethod(m)).collect(); - methods.move_iter() + methods.into_iter() } TypeTraitItem(at) => { SmallVector::one(TypeTraitItem(P( folder.fold_associated_type( (*at).clone())))) - .move_iter() + .into_iter() } }; r diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs index 8c2652e5699..4881be8996a 100644 --- a/src/libsyntax/lib.rs +++ b/src/libsyntax/lib.rs @@ -26,7 +26,6 @@ #![allow(unknown_features)] #![feature(macro_rules, globs, default_type_params, phase, slicing_syntax)] #![feature(quote, struct_variant, unsafe_destructor, import_shadowing)] -#![allow(deprecated)] extern crate arena; extern crate fmt_macros; @@ -61,7 +60,6 @@ pub mod ast_util; pub mod attr; pub mod codemap; pub mod config; -pub mod crateid; pub mod diagnostic; pub mod feature_gate; pub mod fold; diff --git a/src/libsyntax/owned_slice.rs b/src/libsyntax/owned_slice.rs index 798a54c1062..e5c37e5041a 100644 --- a/src/libsyntax/owned_slice.rs +++ b/src/libsyntax/owned_slice.rs @@ -122,7 +122,7 @@ impl Default for OwnedSlice { impl Clone for OwnedSlice { fn clone(&self) -> OwnedSlice { - OwnedSlice::from_vec(Vec::from_slice(self.as_slice())) + OwnedSlice::from_vec(self.as_slice().to_vec()) } } diff --git a/src/libsyntax/parse/lexer/comments.rs b/src/libsyntax/parse/lexer/comments.rs index c53638ed07d..551d15048f1 100644 --- a/src/libsyntax/parse/lexer/comments.rs +++ b/src/libsyntax/parse/lexer/comments.rs @@ -64,21 +64,21 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String { let mut j = lines.len(); // first line of all-stars should be omitted if lines.len() > 0 && - lines.get(0).as_slice().chars().all(|c| c == '*') { + lines[0].as_slice().chars().all(|c| c == '*') { i += 1; } - while i < j && lines.get(i).as_slice().trim().is_empty() { + while i < j && lines[i].as_slice().trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted - if j > i && lines.get(j - 1) + if j > i && lines[j - 1] .as_slice() .chars() .skip(1) .all(|c| c == '*') { j -= 1; } - while j > i && lines.get(j - 1).as_slice().trim().is_empty() { + while j > i && lines[j - 1].as_slice().trim().is_empty() { j -= 1; } return lines.slice(i, j).iter().map(|x| (*x).clone()).collect(); @@ -252,7 +252,7 @@ fn read_block_comment(rdr: &mut StringReader, // doc-comments are not really comments, they are attributes if (rdr.curr_is('*') && !rdr.nextch_is('*')) || rdr.curr_is('!') { while !(rdr.curr_is('*') && rdr.nextch_is('/')) && !rdr.is_eof() { - curr_line.push_char(rdr.curr.unwrap()); + curr_line.push(rdr.curr.unwrap()); rdr.bump(); } if !rdr.is_eof() { @@ -279,17 +279,17 @@ fn read_block_comment(rdr: &mut StringReader, curr_line = String::new(); rdr.bump(); } else { - curr_line.push_char(rdr.curr.unwrap()); + curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); - curr_line.push_char('*'); + curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr.nextch_is('/') { rdr.bump(); rdr.bump(); - curr_line.push_char('/'); + curr_line.push('/'); level -= 1; } else { rdr.bump(); } } diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 38c985af370..55d071b8d60 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -180,7 +180,7 @@ impl<'a> StringReader<'a> { fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> ! { let mut m = m.to_string(); m.push_str(": "); - char::escape_default(c, |c| m.push_char(c)); + char::escape_default(c, |c| m.push(c)); self.fatal_span_(from_pos, to_pos, m.as_slice()); } @@ -189,7 +189,7 @@ impl<'a> StringReader<'a> { fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) { let mut m = m.to_string(); m.push_str(": "); - char::escape_default(c, |c| m.push_char(c)); + char::escape_default(c, |c| m.push(c)); self.err_span_(from_pos, to_pos, m.as_slice()); } @@ -1227,7 +1227,7 @@ impl<'a> StringReader<'a> { fn read_to_eol(&mut self) -> String { let mut val = String::new(); while !self.curr_is('\n') && !self.is_eof() { - val.push_char(self.curr.unwrap()); + val.push(self.curr.unwrap()); self.bump(); } if self.curr_is('\n') { self.bump(); } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index c4a8775a012..f1baccfcd80 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -455,7 +455,7 @@ pub fn str_lit(lit: &str) -> String { for _ in range(0, n - 1) { // we don't need to move past the first \ chars.next(); } - res.push_char(c); + res.push(c); } }, '\r' => { @@ -467,9 +467,9 @@ pub fn str_lit(lit: &str) -> String { fail!("lexer accepted bare CR"); } chars.next(); - res.push_char('\n'); + res.push('\n'); } - c => res.push_char(c), + c => res.push(c), } }, None => break @@ -497,9 +497,9 @@ pub fn raw_str_lit(lit: &str) -> String { fail!("lexer accepted bare CR"); } chars.next(); - res.push_char('\n'); + res.push('\n'); } else { - res.push_char(c); + res.push(c); } }, None => break diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 17f52bc21c5..abab816bfeb 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -281,12 +281,13 @@ macro_rules! maybe_whole ( ) -fn maybe_append(lhs: Vec , rhs: Option >) - -> Vec { +fn maybe_append(mut lhs: Vec, rhs: Option>) + -> Vec { match rhs { - None => lhs, - Some(ref attrs) => lhs.append(attrs.as_slice()) + Some(ref attrs) => lhs.extend(attrs.iter().map(|a| a.clone())), + None => {} } + lhs } @@ -452,7 +453,8 @@ impl<'a> Parser<'a> { } else if inedible.contains(&self.token) { // leave it in the input } else { - let expected = edible.iter().map(|x| (*x).clone()).collect::>().append(inedible); + let mut expected = edible.iter().map(|x| x.clone()).collect::>(); + expected.push_all(inedible); let expect = tokens_to_string(expected.as_slice()); let actual = self.this_token_to_string(); self.fatal( @@ -496,8 +498,8 @@ impl<'a> Parser<'a> { match e.node { ExprPath(..) => { // might be unit-struct construction; check for recoverableinput error. - let expected = edible.iter().map(|x| (*x).clone()).collect::>() - .append(inedible); + let mut expected = edible.iter().map(|x| x.clone()).collect::>(); + expected.push_all(inedible); self.check_for_erroneous_unit_struct_expecting( expected.as_slice()); } @@ -517,8 +519,8 @@ impl<'a> Parser<'a> { if self.last_token .as_ref() .map_or(false, |t| is_ident_or_path(&**t)) { - let expected = edible.iter().map(|x| (*x).clone()).collect::>() - .append(inedible.as_slice()); + let mut expected = edible.iter().map(|x| x.clone()).collect::>(); + expected.push_all(inedible.as_slice()); self.check_for_erroneous_unit_struct_expecting( expected.as_slice()); } @@ -1335,7 +1337,8 @@ impl<'a> Parser<'a> { debug!("parse_trait_methods(): parsing provided method"); let (inner_attrs, body) = p.parse_inner_attrs_and_block(); - let attrs = attrs.append(inner_attrs.as_slice()); + let mut attrs = attrs; + attrs.push_all(inner_attrs.as_slice()); ProvidedMethod(P(ast::Method { attrs: attrs, id: ast::DUMMY_NODE_ID, @@ -2119,7 +2122,7 @@ impl<'a> Parser<'a> { |p| p.parse_expr() ); let mut exprs = vec!(first_expr); - exprs.push_all_move(remaining_exprs); + exprs.extend(remaining_exprs.into_iter()); ex = ExprVec(exprs); } else { // Vector with one element. @@ -2337,7 +2340,7 @@ impl<'a> Parser<'a> { ); hi = self.last_span.hi; - es.unshift(e); + es.insert(0, e); let id = spanned(dot, hi, i); let nd = self.mk_method_call(id, tys, es); e = self.mk_expr(lo, hi, nd); @@ -2600,7 +2603,7 @@ impl<'a> Parser<'a> { self.parse_seq_to_before_end(&close_delim, seq_sep_none(), |p| p.parse_token_tree()); - result.push_all_move(trees); + result.extend(trees.into_iter()); // Parse the close delimiter. result.push(parse_any_tt_tok(self)); @@ -3380,12 +3383,10 @@ impl<'a> Parser<'a> { _ => { if !enum_path.global && enum_path.segments.len() == 1 && - enum_path.segments - .get(0) + enum_path.segments[0] .lifetimes .len() == 0 && - enum_path.segments - .get(0) + enum_path.segments[0] .types .len() == 0 { // it could still be either an enum @@ -3394,7 +3395,7 @@ impl<'a> Parser<'a> { pat = PatIdent(BindByValue(MutImmutable), codemap::Spanned{ span: enum_path.span, - node: enum_path.segments.get(0) + node: enum_path.segments[0] .identifier}, None); } else { @@ -4256,7 +4257,7 @@ impl<'a> Parser<'a> { sep, parse_arg_fn ); - fn_inputs.unshift(Arg::new_self(explicit_self_sp, mutbl_self, $self_id)); + fn_inputs.insert(0, Arg::new_self(explicit_self_sp, mutbl_self, $self_id)); fn_inputs } token::RPAREN => { @@ -4449,7 +4450,8 @@ impl<'a> Parser<'a> { self.parse_where_clause(&mut generics); let (inner_attrs, body) = self.parse_inner_attrs_and_block(); let body_span = body.span; - let new_attrs = attrs.append(inner_attrs.as_slice()); + let mut new_attrs = attrs; + new_attrs.push_all(inner_attrs.as_slice()); (ast::MethDecl(ident, generics, abi, @@ -4490,7 +4492,7 @@ impl<'a> Parser<'a> { let (inner_attrs, mut method_attrs) = self.parse_inner_attrs_and_next(); while !self.eat(&token::RBRACE) { - method_attrs.push_all_move(self.parse_outer_attributes()); + method_attrs.extend(self.parse_outer_attributes().into_iter()); let vis = self.parse_visibility(); if self.eat_keyword(keywords::Type) { impl_items.push(TypeImplItem(P(self.parse_typedef( @@ -4711,7 +4713,9 @@ impl<'a> Parser<'a> { while self.token != term { let mut attrs = self.parse_outer_attributes(); if first { - attrs = attrs_remaining.clone().append(attrs.as_slice()); + let mut tmp = attrs_remaining.clone(); + tmp.push_all(attrs.as_slice()); + attrs = tmp; first = false; } debug!("parse_mod_items: parse_item_or_view_item(attrs={})", @@ -4826,7 +4830,7 @@ impl<'a> Parser<'a> { "cannot declare a new module at this location"); let this_module = match self.mod_path_stack.last() { Some(name) => name.get().to_string(), - None => self.root_module_name.get_ref().clone(), + None => self.root_module_name.as_ref().unwrap().clone(), }; self.span_note(id_sp, format!("maybe move this module `{0}` \ @@ -5536,7 +5540,7 @@ impl<'a> Parser<'a> { } else { s.push_str("priv") } - s.push_char('`'); + s.push('`'); let last_span = self.last_span; self.span_fatal(last_span, s.as_slice()); } @@ -5677,7 +5681,7 @@ impl<'a> Parser<'a> { } _ => () } - let mut rename_to = *path.get(path.len() - 1u); + let mut rename_to = path[path.len() - 1u]; let path = ast::Path { span: mk_sp(lo, self.span.hi), global: false, @@ -5705,7 +5709,8 @@ impl<'a> Parser<'a> { mut extern_mod_allowed: bool, macros_allowed: bool) -> ParsedItemsAndViewItems { - let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice()); + let mut attrs = first_item_attrs; + attrs.push_all(self.parse_outer_attributes().as_slice()); // First, parse view items. let mut view_items : Vec = Vec::new(); let mut items = Vec::new(); @@ -5786,7 +5791,8 @@ impl<'a> Parser<'a> { fn parse_foreign_items(&mut self, first_item_attrs: Vec , macros_allowed: bool) -> ParsedItemsAndViewItems { - let mut attrs = first_item_attrs.append(self.parse_outer_attributes().as_slice()); + let mut attrs = first_item_attrs; + attrs.push_all(self.parse_outer_attributes().as_slice()); let mut foreign_items = Vec::new(); loop { match self.parse_foreign_item(attrs, macros_allowed) { diff --git a/src/libsyntax/print/pp.rs b/src/libsyntax/print/pp.rs index f1fdc71b9c6..65efd4f0042 100644 --- a/src/libsyntax/print/pp.rs +++ b/src/libsyntax/print/pp.rs @@ -134,12 +134,12 @@ pub fn buf_str(toks: Vec, s.push_str(", "); } s.push_str(format!("{}={}", - szs.get(i), - tok_str(toks.get(i).clone())).as_slice()); + szs[i], + tok_str(toks[i].clone())).as_slice()); i += 1u; i %= n; } - s.push_char(']'); + s.push(']'); return s.into_string(); } @@ -299,7 +299,7 @@ pub struct Printer { impl Printer { pub fn last_token(&mut self) -> Token { - (*self.token.get(self.right)).clone() + self.token[self.right].clone() } // be very careful with this! pub fn replace_last_token(&mut self, t: Token) { @@ -311,8 +311,8 @@ impl Printer { Eof => { if !self.scan_stack_empty { self.check_stack(0); - let left = (*self.token.get(self.left)).clone(); - let left_size = *self.size.get(self.left); + let left = self.token[self.left].clone(); + let left_size = self.size[self.left]; try!(self.advance_left(left, left_size)); } self.indent(0); @@ -388,14 +388,14 @@ impl Printer { debug!("scan window is {}, longer than space on line ({})", self.right_total - self.left_total, self.space); if !self.scan_stack_empty { - if self.left == *self.scan_stack.get(self.bottom) { + if self.left == self.scan_stack[self.bottom] { debug!("setting {} to infinity and popping", self.left); let scanned = self.scan_pop_bottom(); *self.size.get_mut(scanned) = SIZE_INFINITY; } } - let left = (*self.token.get(self.left)).clone(); - let left_size = *self.size.get(self.left); + let left = self.token[self.left].clone(); + let left_size = self.size[self.left]; try!(self.advance_left(left, left_size)); if self.left != self.right { try!(self.check_stream()); @@ -416,7 +416,7 @@ impl Printer { } pub fn scan_pop(&mut self) -> uint { assert!((!self.scan_stack_empty)); - let x = *self.scan_stack.get(self.top); + let x = self.scan_stack[self.top]; if self.top == self.bottom { self.scan_stack_empty = true; } else { @@ -426,11 +426,11 @@ impl Printer { } pub fn scan_top(&mut self) -> uint { assert!((!self.scan_stack_empty)); - return *self.scan_stack.get(self.top); + return self.scan_stack[self.top]; } pub fn scan_pop_bottom(&mut self) -> uint { assert!((!self.scan_stack_empty)); - let x = *self.scan_stack.get(self.bottom); + let x = self.scan_stack[self.bottom]; if self.top == self.bottom { self.scan_stack_empty = true; } else { @@ -458,8 +458,8 @@ impl Printer { if self.left != self.right { self.left += 1u; self.left %= self.buf_len; - let left = (*self.token.get(self.left)).clone(); - let left_size = *self.size.get(self.left); + let left = self.token[self.left].clone(); + let left_size = self.size[self.left]; try!(self.advance_left(left, left_size)); } ret @@ -470,29 +470,28 @@ impl Printer { pub fn check_stack(&mut self, k: int) { if !self.scan_stack_empty { let x = self.scan_top(); - match self.token.get(x) { - &Begin(_) => { - if k > 0 { + match self.token[x] { + Begin(_) => { + if k > 0 { + let popped = self.scan_pop(); + *self.size.get_mut(popped) = self.size[x] + + self.right_total; + self.check_stack(k - 1); + } + } + End => { + // paper says + not =, but that makes no sense. let popped = self.scan_pop(); - *self.size.get_mut(popped) = *self.size.get(x) + - self.right_total; - self.check_stack(k - 1); + *self.size.get_mut(popped) = 1; + self.check_stack(k + 1); } - } - &End => { - // paper says + not =, but that makes no sense. - let popped = self.scan_pop(); - *self.size.get_mut(popped) = 1; - self.check_stack(k + 1); - } - _ => { - let popped = self.scan_pop(); - *self.size.get_mut(popped) = *self.size.get(x) + - self.right_total; - if k > 0 { - self.check_stack(k); + _ => { + let popped = self.scan_pop(); + *self.size.get_mut(popped) = self.size[x] + self.right_total; + if k > 0 { + self.check_stack(k); + } } - } } } } @@ -511,7 +510,7 @@ impl Printer { let print_stack = &mut self.print_stack; let n = print_stack.len(); if n != 0u { - *print_stack.get(n - 1u) + (*print_stack)[n - 1] } else { PrintStackElem { offset: 0, diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index f654bc30680..cdcbeedddb2 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -175,7 +175,7 @@ pub fn to_string(f: |&mut State| -> IoResult<()>) -> String { let obj: TraitObject = mem::transmute_copy(&s.s.out); let wr: Box = mem::transmute(obj.data); let result = - String::from_utf8(Vec::from_slice(wr.get_ref().as_slice())).unwrap(); + String::from_utf8(wr.get_ref().as_slice().to_vec()).unwrap(); mem::forget(wr); result.to_string() } @@ -1466,7 +1466,7 @@ impl<'a> State<'a> { } ast::ExprMethodCall(ident, ref tys, ref args) => { let base_args = args.slice_from(1); - try!(self.print_expr(&**args.get(0))); + try!(self.print_expr(&*args[0])); try!(word(&mut self.s, ".")); try!(self.print_ident(ident.node)); if tys.len() > 0u { @@ -2144,7 +2144,7 @@ impl<'a> State<'a> { for &explicit_self in opt_explicit_self.iter() { let m = match explicit_self { &ast::SelfStatic => ast::MutImmutable, - _ => match decl.inputs.get(0).pat.node { + _ => match decl.inputs[0].pat.node { ast::PatIdent(ast::BindByValue(m), _, _) => m, _ => ast::MutImmutable } @@ -2319,7 +2319,7 @@ impl<'a> State<'a> { try!(self.commasep(Inconsistent, ints.as_slice(), |s, &idx| { if idx < generics.lifetimes.len() { - let lifetime = generics.lifetimes.get(idx); + let lifetime = &generics.lifetimes[idx]; s.print_lifetime_def(lifetime) } else { let idx = idx - generics.lifetimes.len(); @@ -2663,14 +2663,14 @@ impl<'a> State<'a> { ast::LitStr(ref st, style) => self.print_string(st.get(), style), ast::LitByte(byte) => { let mut res = String::from_str("b'"); - (byte as char).escape_default(|c| res.push_char(c)); - res.push_char('\''); + (byte as char).escape_default(|c| res.push(c)); + res.push('\''); word(&mut self.s, res.as_slice()) } ast::LitChar(ch) => { let mut res = String::from_str("'"); - ch.escape_default(|c| res.push_char(c)); - res.push_char('\''); + ch.escape_default(|c| res.push(c)); + res.push('\''); word(&mut self.s, res.as_slice()) } ast::LitInt(i, t) => { @@ -2718,7 +2718,7 @@ impl<'a> State<'a> { match self.literals { Some(ref lits) => { while self.cur_cmnt_and_lit.cur_lit < lits.len() { - let ltrl = (*(*lits).get(self.cur_cmnt_and_lit.cur_lit)).clone(); + let ltrl = (*lits)[self.cur_cmnt_and_lit.cur_lit].clone(); if ltrl.pos > pos { return None; } self.cur_cmnt_and_lit.cur_lit += 1u; if ltrl.pos == pos { return Some(ltrl); } @@ -2750,7 +2750,7 @@ impl<'a> State<'a> { comments::Mixed => { assert_eq!(cmnt.lines.len(), 1u); try!(zerobreak(&mut self.s)); - try!(word(&mut self.s, cmnt.lines.get(0).as_slice())); + try!(word(&mut self.s, cmnt.lines[0].as_slice())); zerobreak(&mut self.s) } comments::Isolated => { @@ -2768,7 +2768,7 @@ impl<'a> State<'a> { comments::Trailing => { try!(word(&mut self.s, " ")); if cmnt.lines.len() == 1u { - try!(word(&mut self.s, cmnt.lines.get(0).as_slice())); + try!(word(&mut self.s, cmnt.lines[0].as_slice())); hardbreak(&mut self.s) } else { try!(self.ibox(0u)); @@ -2814,7 +2814,7 @@ impl<'a> State<'a> { match self.comments { Some(ref cmnts) => { if self.cur_cmnt_and_lit.cur_cmnt < cmnts.len() { - Some((*cmnts.get(self.cur_cmnt_and_lit.cur_cmnt)).clone()) + Some(cmnts[self.cur_cmnt_and_lit.cur_cmnt].clone()) } else { None } diff --git a/src/libsyntax/ptr.rs b/src/libsyntax/ptr.rs index bd560abf3bd..1b231ed861b 100644 --- a/src/libsyntax/ptr.rs +++ b/src/libsyntax/ptr.rs @@ -37,6 +37,7 @@ use std::fmt; use std::fmt::Show; use std::hash::Hash; +use std::ptr; use serialize::{Encodable, Decodable, Encoder, Decoder}; /// An owned smart pointer. @@ -61,11 +62,10 @@ impl P { /// Transform the inner value, consuming `self` and producing a new `P`. pub fn map(mut self, f: |T| -> T) -> P { - use std::{mem, ptr}; unsafe { let p = &mut *self.ptr; // FIXME(#5016) this shouldn't need to zero to be safe. - mem::move_val_init(p, f(ptr::read_and_zero(p))); + ptr::write(p, f(ptr::read_and_zero(p))); } self } diff --git a/src/libsyntax/std_inject.rs b/src/libsyntax/std_inject.rs index 8a7e14643c1..0f86fb751da 100644 --- a/src/libsyntax/std_inject.rs +++ b/src/libsyntax/std_inject.rs @@ -100,7 +100,7 @@ impl<'a> fold::Folder for StandardLibraryInjector<'a> { // `extern crate` must be precede `use` items mem::swap(&mut vis, &mut krate.module.view_items); - krate.module.view_items.push_all_move(vis); + krate.module.view_items.extend(vis.into_iter()); // don't add #![no_std] here, that will block the prelude injection later. // Add it during the prelude injection instead. @@ -219,7 +219,7 @@ impl<'a> fold::Folder for PreludeInjector<'a> { vis: ast::Inherited, span: DUMMY_SP, }); - view_items.push_all_move(uses); + view_items.extend(uses.into_iter()); fold::noop_fold_mod(ast::Mod { inner: inner, diff --git a/src/libsyntax/util/interner.rs b/src/libsyntax/util/interner.rs index c22bdde74a4..ed2455d0a30 100644 --- a/src/libsyntax/util/interner.rs +++ b/src/libsyntax/util/interner.rs @@ -67,7 +67,7 @@ impl Interner { pub fn get(&self, idx: Name) -> T { let vect = self.vect.borrow(); - (*(*vect).get(idx.uint())).clone() + (*vect)[idx.uint()].clone() } pub fn len(&self) -> uint { @@ -182,13 +182,13 @@ impl StrInterner { let new_idx = Name(self.len() as u32); // leave out of map to avoid colliding let mut vect = self.vect.borrow_mut(); - let existing = (*vect.get(idx.uint())).clone(); + let existing = (*vect)[idx.uint()].clone(); vect.push(existing); new_idx } pub fn get(&self, idx: Name) -> RcStr { - (*self.vect.borrow().get(idx.uint())).clone() + (*self.vect.borrow())[idx.uint()].clone() } pub fn len(&self) -> uint { diff --git a/src/libsyntax/util/small_vector.rs b/src/libsyntax/util/small_vector.rs index a3f081e7be4..60ba5f6615b 100644 --- a/src/libsyntax/util/small_vector.rs +++ b/src/libsyntax/util/small_vector.rs @@ -98,7 +98,7 @@ impl SmallVector { pub fn get<'a>(&'a self, idx: uint) -> &'a T { match self.repr { One(ref v) if idx == 0 => v, - Many(ref vs) => vs.get(idx), + Many(ref vs) => &vs[idx], _ => fail!("out of bounds access") } } diff --git a/src/liburl/lib.rs b/src/liburl/lib.rs deleted file mode 100644 index bf9a959afff..00000000000 --- a/src/liburl/lib.rs +++ /dev/null @@ -1,1243 +0,0 @@ -// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -//! Types/fns concerning URLs (see RFC 3986) - -#![crate_name = "url"] -#![deprecated="This is being removed. Use rust-url instead. http://servo.github.io/rust-url/"] -#![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/")] -#![feature(default_type_params)] - -use std::collections::HashMap; -use std::collections::hashmap::{Occupied, Vacant}; -use std::fmt; -use std::from_str::FromStr; -use std::hash; -use std::uint; -use std::path::BytesContainer; - -/// A Uniform Resource Locator (URL). A URL is a form of URI (Uniform Resource -/// Identifier) that includes network location information, such as hostname or -/// port number. -/// -/// # Example -/// -/// ```rust -/// # #![allow(deprecated)] -/// use url::Url; -/// -/// let raw = "https://username@example.com:8080/foo/bar?baz=qux#quz"; -/// match Url::parse(raw) { -/// Ok(u) => println!("Parsed '{}'", u), -/// Err(e) => println!("Couldn't parse '{}': {}", raw, e), -/// } -/// ``` -#[deriving(Clone, PartialEq, Eq)] -pub struct Url { - /// The scheme part of a URL, such as `https` in the above example. - pub scheme: String, - /// A URL subcomponent for user authentication. `username` in the above example. - pub user: Option, - /// A domain name or IP address. For example, `example.com`. - pub host: String, - /// A TCP port number, for example `8080`. - pub port: Option, - /// The path component of a URL, for example `/foo/bar?baz=qux#quz`. - pub path: Path, -} - -#[deriving(Clone, PartialEq, Eq)] -pub struct Path { - /// The path component of a URL, for example `/foo/bar`. - pub path: String, - /// The query component of a URL. - /// `vec![("baz".to_string(), "qux".to_string())]` represents the fragment - /// `baz=qux` in the above example. - pub query: Query, - /// The fragment component, such as `quz`. Not including the leading `#` character. - pub fragment: Option -} - -/// An optional subcomponent of a URI authority component. -#[deriving(Clone, PartialEq, Eq)] -pub struct UserInfo { - /// The user name. - pub user: String, - /// Password or other scheme-specific authentication information. - pub pass: Option -} - -/// Represents the query component of a URI. -pub type Query = Vec<(String, String)>; - -impl Url { - pub fn new(scheme: String, - user: Option, - host: String, - port: Option, - path: String, - query: Query, - fragment: Option) - -> Url { - Url { - scheme: scheme, - user: user, - host: host, - port: port, - path: Path::new(path, query, fragment) - } - } - - /// Parses a URL, converting it from a string to a `Url` representation. - /// - /// # Arguments - /// * rawurl - a string representing the full URL, including scheme. - /// - /// # Return value - /// - /// `Err(e)` if the string did not represent a valid URL, where `e` is a - /// `String` error message. Otherwise, `Ok(u)` where `u` is a `Url` struct - /// representing the URL. - pub fn parse(rawurl: &str) -> DecodeResult { - // scheme - let (scheme, rest) = try!(get_scheme(rawurl)); - - // authority - let (userinfo, host, port, rest) = try!(get_authority(rest)); - - // path - let has_authority = host.len() > 0; - let (path, rest) = try!(get_path(rest, has_authority)); - - // query and fragment - let (query, fragment) = try!(get_query_fragment(rest)); - - let url = Url::new(scheme.to_string(), - userinfo, - host.to_string(), - port, - path, - query, - fragment); - Ok(url) - } -} - -#[deprecated="use `Url::parse`"] -pub fn from_str(s: &str) -> Result { - Url::parse(s) -} - -impl Path { - pub fn new(path: String, - query: Query, - fragment: Option) - -> Path { - Path { - path: path, - query: query, - fragment: fragment, - } - } - - /// Parses a URL path, converting it from a string to a `Path` representation. - /// - /// # Arguments - /// * rawpath - a string representing the path component of a URL. - /// - /// # Return value - /// - /// `Err(e)` if the string did not represent a valid URL path, where `e` is a - /// `String` error message. Otherwise, `Ok(p)` where `p` is a `Path` struct - /// representing the URL path. - pub fn parse(rawpath: &str) -> DecodeResult { - let (path, rest) = try!(get_path(rawpath, false)); - - // query and fragment - let (query, fragment) = try!(get_query_fragment(rest.as_slice())); - - Ok(Path{ path: path, query: query, fragment: fragment }) - } -} - -#[deprecated="use `Path::parse`"] -pub fn path_from_str(s: &str) -> Result { - Path::parse(s) -} - -impl UserInfo { - #[inline] - pub fn new(user: String, pass: Option) -> UserInfo { - UserInfo { user: user, pass: pass } - } -} - -fn encode_inner(c: T, full_url: bool) -> String { - c.container_as_bytes().iter().fold(String::new(), |mut out, &b| { - match b as char { - // unreserved: - 'A' ... 'Z' - | 'a' ... 'z' - | '0' ... '9' - | '-' | '.' | '_' | '~' => out.push_char(b as char), - - // gen-delims: - ':' | '/' | '?' | '#' | '[' | ']' | '@' | - // sub-delims: - '!' | '$' | '&' | '"' | '(' | ')' | '*' | - '+' | ',' | ';' | '=' - if full_url => out.push_char(b as char), - - ch => out.push_str(format!("%{:02X}", ch as uint).as_slice()), - }; - - out - }) -} - -/// Encodes a URI by replacing reserved characters with percent-encoded -/// character sequences. -/// -/// This function is compliant with RFC 3986. -/// -/// # Example -/// -/// ```rust -/// # #![allow(deprecated)] -/// use url::encode; -/// -/// let url = encode("https://example.com/Rust (programming language)"); -/// println!("{}", url); // https://example.com/Rust%20(programming%20language) -/// ``` -pub fn encode(container: T) -> String { - encode_inner(container, true) -} - - -/// Encodes a URI component by replacing reserved characters with percent- -/// encoded character sequences. -/// -/// This function is compliant with RFC 3986. -pub fn encode_component(container: T) -> String { - encode_inner(container, false) -} - -pub type DecodeResult = Result; - -/// Decodes a percent-encoded string representing a URI. -/// -/// This will only decode escape sequences generated by `encode`. -/// -/// # Example -/// -/// ```rust -/// # #![allow(deprecated)] -/// use url::decode; -/// -/// let url = decode("https://example.com/Rust%20(programming%20language)"); -/// println!("{}", url); // https://example.com/Rust (programming language) -/// ``` -pub fn decode(container: T) -> DecodeResult { - decode_inner(container, true) -} - -/// Decode a string encoded with percent encoding. -pub fn decode_component(container: T) -> DecodeResult { - decode_inner(container, false) -} - -fn decode_inner(c: T, full_url: bool) -> DecodeResult { - let mut out = String::new(); - let mut iter = c.container_as_bytes().iter().map(|&b| b); - - loop { - match iter.next() { - Some(b) => match b as char { - '%' => { - let bytes = match (iter.next(), iter.next()) { - (Some(one), Some(two)) => [one as u8, two as u8], - _ => return Err(format!("Malformed input: found '%' \ - without two trailing bytes")), - }; - - // Only decode some characters if full_url: - match uint::parse_bytes(bytes, 16u).unwrap() as u8 as char { - // gen-delims: - ':' | '/' | '?' | '#' | '[' | ']' | '@' | - - // sub-delims: - '!' | '$' | '&' | '"' | '(' | ')' | '*' | - '+' | ',' | ';' | '=' - if full_url => { - out.push_char('%'); - out.push_char(bytes[0u] as char); - out.push_char(bytes[1u] as char); - } - - ch => out.push_char(ch) - } - } - ch => out.push_char(ch) - }, - None => return Ok(out), - } - } -} - -/// Encode a hashmap to the 'application/x-www-form-urlencoded' media type. -pub fn encode_form_urlencoded(m: &HashMap>) -> String { - fn encode_plus(s: &T) -> String { - s.as_slice().bytes().fold(String::new(), |mut out, b| { - match b as char { - 'A' ... 'Z' - | 'a' ... 'z' - | '0' ... '9' - | '_' | '.' | '-' => out.push_char(b as char), - ' ' => out.push_char('+'), - ch => out.push_str(format!("%{:X}", ch as uint).as_slice()) - } - - out - }) - } - - let mut first = true; - m.iter().fold(String::new(), |mut out, (key, values)| { - let key = encode_plus(key); - - for value in values.iter() { - if first { - first = false; - } else { - out.push_char('&'); - } - - out.push_str(key.as_slice()); - out.push_char('='); - out.push_str(encode_plus(value).as_slice()); - } - - out - }) -} - -/// Decode a string encoded with the 'application/x-www-form-urlencoded' media -/// type into a hashmap. -pub fn decode_form_urlencoded(s: &[u8]) - -> DecodeResult>> { - fn maybe_push_value(map: &mut HashMap>, - key: String, - value: String) { - if key.len() > 0 && value.len() > 0 { - match map.entry(key) { - Vacant(entry) => { entry.set(vec![value]); }, - Occupied(mut entry) => { entry.get_mut().push(value); }, - } - } - } - - let mut out = HashMap::new(); - let mut iter = s.iter().map(|&x| x); - - let mut key = String::new(); - let mut value = String::new(); - let mut parsing_key = true; - - loop { - match iter.next() { - Some(b) => match b as char { - '&' | ';' => { - maybe_push_value(&mut out, key, value); - - parsing_key = true; - key = String::new(); - value = String::new(); - } - '=' => parsing_key = false, - ch => { - let ch = match ch { - '%' => { - let bytes = match (iter.next(), iter.next()) { - (Some(one), Some(two)) => [one as u8, two as u8], - _ => return Err(format!("Malformed input: found \ - '%' without two trailing bytes")) - }; - - uint::parse_bytes(bytes, 16u).unwrap() as u8 as char - } - '+' => ' ', - ch => ch - }; - - if parsing_key { - key.push_char(ch) - } else { - value.push_char(ch) - } - } - }, - None => { - maybe_push_value(&mut out, key, value); - return Ok(out) - } - } - } -} - -fn split_char_first(s: &str, c: char) -> (&str, &str) { - let mut iter = s.splitn(1, c); - - match (iter.next(), iter.next()) { - (Some(a), Some(b)) => (a, b), - (Some(a), None) => (a, ""), - (None, _) => unreachable!(), - } -} - -impl fmt::Show for UserInfo { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.pass { - Some(ref pass) => write!(f, "{}:{}@", self.user, *pass), - None => write!(f, "{}@", self.user), - } - } -} - -fn query_from_str(rawquery: &str) -> DecodeResult { - let mut query: Query = vec!(); - if !rawquery.is_empty() { - for p in rawquery.split('&') { - let (k, v) = split_char_first(p, '='); - query.push((try!(decode_component(k)), - try!(decode_component(v)))); - } - } - - Ok(query) -} - -/// Converts an instance of a URI `Query` type to a string. -/// -/// # Example -/// -/// ```rust -/// # #![allow(deprecated)] -/// let query = vec![("title".to_string(), "The Village".to_string()), -/// ("north".to_string(), "52.91".to_string()), -/// ("west".to_string(), "4.10".to_string())]; -/// println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10 -/// ``` -pub fn query_to_str(query: &Query) -> String { - query.iter().enumerate().fold(String::new(), |mut out, (i, &(ref k, ref v))| { - if i != 0 { - out.push_char('&'); - } - - out.push_str(encode_component(k.as_slice()).as_slice()); - out.push_char('='); - out.push_str(encode_component(v.as_slice()).as_slice()); - out - }) -} - -/// Returns a tuple of the URI scheme and the rest of the URI, or a parsing error. -/// -/// Does not include the separating `:` character. -/// -/// # Example -/// -/// ```rust -/// # #![allow(deprecated)] -/// use url::get_scheme; -/// -/// let scheme = match get_scheme("https://example.com/") { -/// Ok((sch, _)) => sch, -/// Err(_) => "(None)", -/// }; -/// println!("Scheme in use: {}.", scheme); // Scheme in use: https. -/// ``` -pub fn get_scheme(rawurl: &str) -> DecodeResult<(&str, &str)> { - for (i,c) in rawurl.chars().enumerate() { - let result = match c { - 'A' ... 'Z' - | 'a' ... 'z' => continue, - '0' ... '9' | '+' | '-' | '.' => { - if i != 0 { continue } - - Err("url: Scheme must begin with a letter.".to_string()) - } - ':' => { - if i == 0 { - Err("url: Scheme cannot be empty.".to_string()) - } else { - Ok((rawurl.slice(0,i), rawurl.slice(i+1,rawurl.len()))) - } - } - _ => Err("url: Invalid character in scheme.".to_string()), - }; - - return result; - } - - Err("url: Scheme must be terminated with a colon.".to_string()) -} - -// returns userinfo, host, port, and unparsed part, or an error -fn get_authority(rawurl: &str) -> - DecodeResult<(Option, &str, Option, &str)> { - enum State { - Start, // starting state - PassHostPort, // could be in user or port - Ip6Port, // either in ipv6 host or port - Ip6Host, // are in an ipv6 host - InHost, // are in a host - may be ipv6, but don't know yet - InPort // are in port - } - - #[deriving(Clone, PartialEq)] - enum Input { - Digit, // all digits - Hex, // digits and letters a-f - Unreserved // all other legal characters - } - - if !rawurl.starts_with("//") { - // there is no authority. - return Ok((None, "", None, rawurl)); - } - - let len = rawurl.len(); - let mut st = Start; - let mut input = Digit; // most restricted, start here. - - let mut userinfo = None; - let mut host = ""; - let mut port = None; - - let mut colon_count = 0u; - let mut pos = 0; - let mut begin = 2; - let mut end = len; - - for (i,c) in rawurl.chars().enumerate() - // ignore the leading '//' handled by early return - .skip(2) { - // deal with input class first - match c { - '0' ... '9' => (), - 'A' ... 'F' - | 'a' ... 'f' => { - if input == Digit { - input = Hex; - } - } - 'G' ... 'Z' - | 'g' ... 'z' - | '-' | '.' | '_' | '~' | '%' - | '&' |'\'' | '(' | ')' | '+' - | '!' | '*' | ',' | ';' | '=' => input = Unreserved, - ':' | '@' | '?' | '#' | '/' => { - // separators, don't change anything - } - _ => return Err("Illegal character in authority".to_string()), - } - - // now process states - match c { - ':' => { - colon_count += 1; - match st { - Start => { - pos = i; - st = PassHostPort; - } - PassHostPort => { - // multiple colons means ipv6 address. - if input == Unreserved { - return Err( - "Illegal characters in IPv6 address.".to_string()); - } - st = Ip6Host; - } - InHost => { - pos = i; - if input == Unreserved { - // must be port - host = rawurl.slice(begin, i); - st = InPort; - } else { - // can't be sure whether this is an ipv6 address or a port - st = Ip6Port; - } - } - Ip6Port => { - if input == Unreserved { - return Err("Illegal characters in authority.".to_string()); - } - st = Ip6Host; - } - Ip6Host => { - if colon_count > 7 { - host = rawurl.slice(begin, i); - pos = i; - st = InPort; - } - } - _ => return Err("Invalid ':' in authority.".to_string()), - } - input = Digit; // reset input class - } - - '@' => { - input = Digit; // reset input class - colon_count = 0; // reset count - match st { - Start => { - let user = rawurl.slice(begin, i).to_string(); - userinfo = Some(UserInfo::new(user, None)); - st = InHost; - } - PassHostPort => { - let user = rawurl.slice(begin, pos).to_string(); - let pass = rawurl.slice(pos+1, i).to_string(); - userinfo = Some(UserInfo::new(user, Some(pass))); - st = InHost; - } - _ => return Err("Invalid '@' in authority.".to_string()), - } - begin = i+1; - } - - '?' | '#' | '/' => { - end = i; - break; - } - _ => () - } - } - - // finish up - match st { - Start => host = rawurl.slice(begin, end), - PassHostPort - | Ip6Port => { - if input != Digit { - return Err("Non-digit characters in port.".to_string()); - } - host = rawurl.slice(begin, pos); - port = Some(rawurl.slice(pos+1, end)); - } - Ip6Host - | InHost => host = rawurl.slice(begin, end), - InPort => { - if input != Digit { - return Err("Non-digit characters in port.".to_string()); - } - port = Some(rawurl.slice(pos+1, end)); - } - } - - let rest = rawurl.slice(end, len); - // If we have a port string, ensure it parses to u16. - let port = match port { - None => None, - opt => match opt.and_then(|p| FromStr::from_str(p)) { - None => return Err(format!("Failed to parse port: {}", port)), - opt => opt - } - }; - - Ok((userinfo, host, port, rest)) -} - - -// returns the path and unparsed part of url, or an error -fn get_path(rawurl: &str, is_authority: bool) -> DecodeResult<(String, &str)> { - let len = rawurl.len(); - let mut end = len; - for (i,c) in rawurl.chars().enumerate() { - match c { - 'A' ... 'Z' - | 'a' ... 'z' - | '0' ... '9' - | '&' |'\'' | '(' | ')' | '.' - | '@' | ':' | '%' | '/' | '+' - | '!' | '*' | ',' | ';' | '=' - | '_' | '-' | '~' => continue, - '?' | '#' => { - end = i; - break; - } - _ => return Err("Invalid character in path.".to_string()) - } - } - - if is_authority && end != 0 && !rawurl.starts_with("/") { - Err("Non-empty path must begin with \ - '/' in presence of authority.".to_string()) - } else { - Ok((try!(decode_component(rawurl.slice(0, end))), - rawurl.slice(end, len))) - } -} - -// returns the parsed query and the fragment, if present -fn get_query_fragment(rawurl: &str) -> DecodeResult<(Query, Option)> { - let (before_fragment, raw_fragment) = split_char_first(rawurl, '#'); - - // Parse the fragment if available - let fragment = match raw_fragment { - "" => None, - raw => Some(try!(decode_component(raw))) - }; - - match before_fragment.slice_shift_char() { - (Some('?'), rest) => Ok((try!(query_from_str(rest)), fragment)), - (None, "") => Ok((vec!(), fragment)), - _ => Err(format!("Query didn't start with '?': '{}..'", before_fragment)), - } -} - -impl FromStr for Url { - fn from_str(s: &str) -> Option { - Url::parse(s).ok() - } -} - -impl FromStr for Path { - fn from_str(s: &str) -> Option { - Path::parse(s).ok() - } -} - -impl fmt::Show for Url { - /// Converts a URL from `Url` to string representation. - /// - /// # Returns - /// - /// A string that contains the formatted URL. Note that this will usually - /// be an inverse of `from_str` but might strip out unneeded separators; - /// for example, "http://somehost.com?", when parsed and formatted, will - /// result in just "http://somehost.com". - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}:", self.scheme)); - - if !self.host.is_empty() { - try!(write!(f, "//")); - match self.user { - Some(ref user) => try!(write!(f, "{}", *user)), - None => {} - } - match self.port { - Some(ref port) => try!(write!(f, "{}:{}", self.host, - *port)), - None => try!(write!(f, "{}", self.host)), - } - } - - write!(f, "{}", self.path) - } -} - -impl fmt::Show for Path { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{}", self.path)); - if !self.query.is_empty() { - try!(write!(f, "?{}", query_to_str(&self.query))) - } - - match self.fragment { - Some(ref fragment) => { - write!(f, "#{}", encode_component(fragment.as_slice())) - } - None => Ok(()) - } - } -} - -impl hash::Hash for Url { - fn hash(&self, state: &mut S) { - self.to_string().hash(state) - } -} - -impl hash::Hash for Path { - fn hash(&self, state: &mut S) { - self.to_string().hash(state) - } -} - -// Put a few tests outside of the 'test' module so they can test the internal -// functions and those functions don't need 'pub' - -#[test] -fn test_split_char_first() { - let (u,v) = split_char_first("hello, sweet world", ','); - assert_eq!(u, "hello"); - assert_eq!(v, " sweet world"); - - let (u,v) = split_char_first("hello sweet world", ','); - assert_eq!(u, "hello sweet world"); - assert_eq!(v, ""); -} - -#[test] -fn test_get_authority() { - let (u, h, p, r) = get_authority( - "//user:pass@rust-lang.org/something").unwrap(); - assert_eq!(u, Some(UserInfo::new("user".to_string(), Some("pass".to_string())))); - assert_eq!(h, "rust-lang.org"); - assert!(p.is_none()); - assert_eq!(r, "/something"); - - let (u, h, p, r) = get_authority( - "//rust-lang.org:8000?something").unwrap(); - assert!(u.is_none()); - assert_eq!(h, "rust-lang.org"); - assert_eq!(p, Some(8000)); - assert_eq!(r, "?something"); - - let (u, h, p, r) = get_authority("//rust-lang.org#blah").unwrap(); - assert!(u.is_none()); - assert_eq!(h, "rust-lang.org"); - assert!(p.is_none()); - assert_eq!(r, "#blah"); - - // ipv6 tests - let (_, h, _, _) = get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap(); - assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334"); - - let (_, h, p, _) = get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap(); - assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334"); - assert_eq!(p, Some(8000)); - - let (u, h, p, _) = get_authority( - "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah" - ).unwrap(); - assert_eq!(u, Some(UserInfo::new("us".to_string(), Some("p".to_string())))); - assert_eq!(h, "2001:0db8:85a3:0042:0000:8a2e:0370:7334"); - assert_eq!(p, Some(8000)); - - // invalid authorities; - assert!(get_authority("//user:pass@rust-lang:something").is_err()); - assert!(get_authority("//user@rust-lang:something:/path").is_err()); - assert!(get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:800a").is_err()); - assert!(get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err()); - // outside u16 range - assert!(get_authority("//user:pass@rust-lang:65536").is_err()); - - // these parse as empty, because they don't start with '//' - let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap(); - assert_eq!(h, ""); - let (_, h, _, _) = get_authority("rust-lang.org").unwrap(); - assert_eq!(h, ""); -} - -#[test] -fn test_get_path() { - let (p, r) = get_path("/something+%20orother", true).unwrap(); - assert_eq!(p, "/something+ orother".to_string()); - assert_eq!(r, ""); - let (p, r) = get_path("test@email.com#fragment", false).unwrap(); - assert_eq!(p, "test@email.com".to_string()); - assert_eq!(r, "#fragment"); - let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap(); - assert_eq!(p, "/gen/:addr=".to_string()); - assert_eq!(r, "?q=v"); - - //failure cases - assert!(get_path("something?q", true).is_err()); -} - -#[cfg(test)] -mod tests { - use {encode_form_urlencoded, decode_form_urlencoded, decode, encode, - encode_component, decode_component, UserInfo, get_scheme, Url, Path}; - - use std::collections::HashMap; - use std::path::BytesContainer; - - #[test] - fn test_url_parse() { - let url = "http://user:pass@rust-lang.org:8080/doc/~u?s=v#something"; - let u = from_str::(url).unwrap(); - - assert_eq!(u.scheme, "http".to_string()); - assert_eq!(u.user, Some(UserInfo::new("user".to_string(), Some("pass".to_string())))); - assert_eq!(u.host, "rust-lang.org".to_string()); - assert_eq!(u.port, Some(8080)); - assert_eq!(u.path.path, "/doc/~u".to_string()); - assert_eq!(u.path.query, vec!(("s".to_string(), "v".to_string()))); - assert_eq!(u.path.fragment, Some("something".to_string())); - } - - #[test] - fn test_path_parse() { - let path = "/doc/~u?s=v#something"; - let u = from_str::(path).unwrap(); - - assert_eq!(u.path, "/doc/~u".to_string()); - assert_eq!(u.query, vec!(("s".to_string(), "v".to_string()))); - assert_eq!(u.fragment, Some("something".to_string())); - } - - #[test] - fn test_url_parse_host_slash() { - let urlstr = "http://0.42.42.42/"; - let url = from_str::(urlstr).unwrap(); - assert_eq!(url.host, "0.42.42.42".to_string()); - assert_eq!(url.path.path, "/".to_string()); - } - - #[test] - fn test_path_parse_host_slash() { - let pathstr = "/"; - let path = from_str::(pathstr).unwrap(); - assert_eq!(path.path, "/".to_string()); - } - - #[test] - fn test_url_host_with_port() { - let urlstr = "scheme://host:1234"; - let url = from_str::(urlstr).unwrap(); - assert_eq!(url.scheme, "scheme".to_string()); - assert_eq!(url.host, "host".to_string()); - assert_eq!(url.port, Some(1234)); - // is empty path really correct? Other tests think so - assert_eq!(url.path.path, "".to_string()); - - let urlstr = "scheme://host:1234/"; - let url = from_str::(urlstr).unwrap(); - assert_eq!(url.scheme, "scheme".to_string()); - assert_eq!(url.host, "host".to_string()); - assert_eq!(url.port, Some(1234)); - assert_eq!(url.path.path, "/".to_string()); - } - - #[test] - fn test_url_with_underscores() { - let urlstr = "http://dotcom.com/file_name.html"; - let url = from_str::(urlstr).unwrap(); - assert_eq!(url.path.path, "/file_name.html".to_string()); - } - - #[test] - fn test_path_with_underscores() { - let pathstr = "/file_name.html"; - let path = from_str::(pathstr).unwrap(); - assert_eq!(path.path, "/file_name.html".to_string()); - } - - #[test] - fn test_url_with_dashes() { - let urlstr = "http://dotcom.com/file-name.html"; - let url = from_str::(urlstr).unwrap(); - assert_eq!(url.path.path, "/file-name.html".to_string()); - } - - #[test] - fn test_path_with_dashes() { - let pathstr = "/file-name.html"; - let path = from_str::(pathstr).unwrap(); - assert_eq!(path.path, "/file-name.html".to_string()); - } - - #[test] - fn test_no_scheme() { - assert!(get_scheme("noschemehere.html").is_err()); - } - - #[test] - fn test_invalid_scheme_errors() { - assert!(Url::parse("99://something").is_err()); - assert!(Url::parse("://something").is_err()); - } - - #[test] - fn test_full_url_parse_and_format() { - let url = "http://user:pass@rust-lang.org/doc?s=v#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_userless_url_parse_and_format() { - let url = "http://rust-lang.org/doc?s=v#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_queryless_url_parse_and_format() { - let url = "http://user:pass@rust-lang.org/doc#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_empty_query_url_parse_and_format() { - let url = "http://user:pass@rust-lang.org/doc?#something"; - let should_be = "http://user:pass@rust-lang.org/doc#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), should_be); - } - - #[test] - fn test_fragmentless_url_parse_and_format() { - let url = "http://user:pass@rust-lang.org/doc?q=v"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_minimal_url_parse_and_format() { - let url = "http://rust-lang.org/doc"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_url_with_port_parse_and_format() { - let url = "http://rust-lang.org:80/doc"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_scheme_host_only_url_parse_and_format() { - let url = "http://rust-lang.org"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_pathless_url_parse_and_format() { - let url = "http://user:pass@rust-lang.org?q=v#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_scheme_host_fragment_only_url_parse_and_format() { - let url = "http://rust-lang.org#something"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_url_component_encoding() { - let url = "http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B"; - let u = from_str::(url).unwrap(); - assert!(u.path.path == "/doc uments".to_string()); - assert!(u.path.query == vec!(("ba%d ".to_string(), "#&+".to_string()))); - } - - #[test] - fn test_path_component_encoding() { - let path = "/doc%20uments?ba%25d%20=%23%26%2B"; - let p = from_str::(path).unwrap(); - assert!(p.path == "/doc uments".to_string()); - assert!(p.query == vec!(("ba%d ".to_string(), "#&+".to_string()))); - } - - #[test] - fn test_url_without_authority() { - let url = "mailto:test@email.com"; - let u = from_str::(url).unwrap(); - assert_eq!(format!("{}", u).as_slice(), url); - } - - #[test] - fn test_encode() { - fn t(input: T, expected: &str) { - assert_eq!(encode(input), expected.to_string()) - } - - t("", ""); - t("http://example.com", "http://example.com"); - t("foo bar% baz", "foo%20bar%25%20baz"); - t(" ", "%20"); - t("!", "!"); - t("\"", "\""); - t("#", "#"); - t("$", "$"); - t("%", "%25"); - t("&", "&"); - t("'", "%27"); - t("(", "("); - t(")", ")"); - t("*", "*"); - t("+", "+"); - t(",", ","); - t("/", "/"); - t(":", ":"); - t(";", ";"); - t("=", "="); - t("?", "?"); - t("@", "@"); - t("[", "["); - t("]", "]"); - t("\0", "%00"); - t("\n", "%0A"); - - let a: &[_] = &[0u8, 10, 37]; - t(a, "%00%0A%25"); - } - - #[test] - fn test_encode_component() { - fn t(input: T, expected: &str) { - assert_eq!(encode_component(input), expected.to_string()) - } - - t("", ""); - t("http://example.com", "http%3A%2F%2Fexample.com"); - t("foo bar% baz", "foo%20bar%25%20baz"); - t(" ", "%20"); - t("!", "%21"); - t("#", "%23"); - t("$", "%24"); - t("%", "%25"); - t("&", "%26"); - t("'", "%27"); - t("(", "%28"); - t(")", "%29"); - t("*", "%2A"); - t("+", "%2B"); - t(",", "%2C"); - t("/", "%2F"); - t(":", "%3A"); - t(";", "%3B"); - t("=", "%3D"); - t("?", "%3F"); - t("@", "%40"); - t("[", "%5B"); - t("]", "%5D"); - t("\0", "%00"); - t("\n", "%0A"); - - let a: &[_] = &[0u8, 10, 37]; - t(a, "%00%0A%25"); - } - - #[test] - fn test_decode() { - fn t(input: T, expected: &str) { - assert_eq!(decode(input), Ok(expected.to_string())) - } - - assert!(decode("sadsadsda%").is_err()); - assert!(decode("waeasd%4").is_err()); - t("", ""); - t("abc/def 123", "abc/def 123"); - t("abc%2Fdef%20123", "abc%2Fdef 123"); - t("%20", " "); - t("%21", "%21"); - t("%22", "%22"); - t("%23", "%23"); - t("%24", "%24"); - t("%25", "%"); - t("%26", "%26"); - t("%27", "'"); - t("%28", "%28"); - t("%29", "%29"); - t("%2A", "%2A"); - t("%2B", "%2B"); - t("%2C", "%2C"); - t("%2F", "%2F"); - t("%3A", "%3A"); - t("%3B", "%3B"); - t("%3D", "%3D"); - t("%3F", "%3F"); - t("%40", "%40"); - t("%5B", "%5B"); - t("%5D", "%5D"); - - t("%00%0A%25".as_bytes(), "\0\n%"); - } - - #[test] - fn test_decode_component() { - fn t(input: T, expected: &str) { - assert_eq!(decode_component(input), Ok(expected.to_string())) - } - - assert!(decode_component("asacsa%").is_err()); - assert!(decode_component("acsas%4").is_err()); - t("", ""); - t("abc/def 123", "abc/def 123"); - t("abc%2Fdef%20123", "abc/def 123"); - t("%20", " "); - t("%21", "!"); - t("%22", "\""); - t("%23", "#"); - t("%24", "$"); - t("%25", "%"); - t("%26", "&"); - t("%27", "'"); - t("%28", "("); - t("%29", ")"); - t("%2A", "*"); - t("%2B", "+"); - t("%2C", ","); - t("%2F", "/"); - t("%3A", ":"); - t("%3B", ";"); - t("%3D", "="); - t("%3F", "?"); - t("%40", "@"); - t("%5B", "["); - t("%5D", "]"); - - t("%00%0A%25".as_bytes(), "\0\n%"); - } - - #[test] - fn test_encode_form_urlencoded() { - let mut m = HashMap::new(); - assert_eq!(encode_form_urlencoded(&m), "".to_string()); - - m.insert("".to_string(), vec!()); - m.insert("foo".to_string(), vec!()); - assert_eq!(encode_form_urlencoded(&m), "".to_string()); - - let mut m = HashMap::new(); - m.insert("foo".to_string(), vec!("bar".to_string(), "123".to_string())); - assert_eq!(encode_form_urlencoded(&m), "foo=bar&foo=123".to_string()); - - let mut m = HashMap::new(); - m.insert("foo bar".to_string(), vec!("abc".to_string(), "12 = 34".to_string())); - assert_eq!(encode_form_urlencoded(&m), - "foo+bar=abc&foo+bar=12+%3D+34".to_string()); - } - - #[test] - fn test_decode_form_urlencoded() { - assert_eq!(decode_form_urlencoded([]).unwrap().len(), 0); - - let s = "a=1&foo+bar=abc&foo+bar=12+%3D+34".as_bytes(); - let form = decode_form_urlencoded(s).unwrap(); - assert_eq!(form.len(), 2); - assert_eq!(form.get(&"a".to_string()), &vec!("1".to_string())); - assert_eq!(form.get(&"foo bar".to_string()), - &vec!("abc".to_string(), "12 = 34".to_string())); - } -} diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs deleted file mode 100644 index c041ca3799d..00000000000 --- a/src/libuuid/lib.rs +++ /dev/null @@ -1,865 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -/*! -Generate and parse UUIDs - -Provides support for Universally Unique Identifiers (UUIDs). A UUID is a -unique 128-bit number, stored as 16 octets. UUIDs are used to assign unique -identifiers to entities without requiring a central allocating authority. - -They are particularly useful in distributed systems, though can be used in -disparate areas, such as databases and network protocols. Typically a UUID is -displayed in a readable string form as a sequence of hexadecimal digits, -separated into groups by hyphens. - -The uniqueness property is not strictly guaranteed, however for all practical -purposes, it can be assumed that an unintentional collision would be extremely -unlikely. - -# Examples - -To create a new random (V4) UUID and print it out in hexadecimal form: - -```rust -# #![allow(deprecated)] -# extern crate uuid; -use uuid::Uuid; - -fn main() { - let uuid1 = Uuid::new_v4(); - println!("{}", uuid1.to_string()); -} -``` - -# Strings - -Examples of string representations: - -* simple: `936DA01F9ABD4d9d80C702AF85C822A8` -* hyphenated: `550e8400-e29b-41d4-a716-446655440000` -* urn: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4` - -# References - -* [Wikipedia: Universally Unique Identifier]( - http://en.wikipedia.org/wiki/Universally_unique_identifier) -* [RFC4122: A Universally Unique IDentifier (UUID) URN Namespace]( - http://tools.ietf.org/html/rfc4122) - -*/ - -#![crate_name = "uuid"] -#![deprecated = "This is now a cargo package located at: \ - https://github.com/rust-lang/uuid"] -#![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/")] - -#![feature(default_type_params)] - -// test harness access -#[cfg(test)] -extern crate test; -extern crate serialize; - -use std::char::Char; -use std::default::Default; -use std::fmt; -use std::from_str::FromStr; -use std::hash; -use std::mem::{transmute,transmute_copy}; -use std::num::FromStrRadix; -use std::rand; -use std::rand::Rng; -use std::slice; - -use serialize::{Encoder, Encodable, Decoder, Decodable}; - -/// A 128-bit (16 byte) buffer containing the ID -pub type UuidBytes = [u8, ..16]; - -/// The version of the UUID, denoting the generating algorithm -#[deriving(PartialEq)] -pub enum UuidVersion { - /// Version 1: MAC address - Version1Mac = 1, - /// Version 2: DCE Security - Version2Dce = 2, - /// Version 3: MD5 hash - Version3Md5 = 3, - /// Version 4: Random - Version4Random = 4, - /// Version 5: SHA-1 hash - Version5Sha1 = 5, -} - -/// The reserved variants of UUIDs -#[deriving(PartialEq)] -pub enum UuidVariant { - /// Reserved by the NCS for backward compatibility - VariantNCS, - /// As described in the RFC4122 Specification (default) - VariantRFC4122, - /// Reserved by Microsoft for backward compatibility - VariantMicrosoft, - /// Reserved for future expansion - VariantFuture, -} - -/// A Universally Unique Identifier (UUID) -pub struct Uuid { - /// The 128-bit number stored in 16 bytes - bytes: UuidBytes -} - -impl hash::Hash for Uuid { - fn hash(&self, state: &mut S) { - self.bytes.hash(state) - } -} - -/// A UUID stored as fields (identical to UUID, used only for conversions) -struct UuidFields { - /// First field, 32-bit word - data1: u32, - /// Second field, 16-bit short - data2: u16, - /// Third field, 16-bit short - data3: u16, - /// Fourth field, 8 bytes - data4: [u8, ..8] -} - -/// Error details for string parsing failures -#[allow(missing_doc)] -pub enum ParseError { - ErrorInvalidLength(uint), - ErrorInvalidCharacter(char, uint), - ErrorInvalidGroups(uint), - ErrorInvalidGroupLength(uint, uint, uint), -} - -/// Converts a ParseError to a string -impl fmt::Show for ParseError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - ErrorInvalidLength(found) => - write!(f, "Invalid length; expecting 32, 36 or 45 chars, \ - found {}", found), - ErrorInvalidCharacter(found, pos) => - write!(f, "Invalid character; found `{}` (0x{:02x}) at \ - offset {}", found, found as uint, pos), - ErrorInvalidGroups(found) => - write!(f, "Malformed; wrong number of groups: expected 1 \ - or 5, found {}", found), - ErrorInvalidGroupLength(group, found, expecting) => - write!(f, "Malformed; length of group {} was {}, \ - expecting {}", group, found, expecting), - } - } -} - -// Length of each hyphenated group in hex digits -#[allow(non_uppercase_statics)] -static UuidGroupLens: [uint, ..5] = [8u, 4u, 4u, 4u, 12u]; - -/// UUID support -impl Uuid { - /// Returns a nil or empty UUID (containing all zeroes) - pub fn nil() -> Uuid { - let uuid = Uuid{ bytes: [0, .. 16] }; - uuid - } - - /// Create a new UUID of the specified version - pub fn new(v: UuidVersion) -> Option { - match v { - Version4Random => Some(Uuid::new_v4()), - _ => None - } - } - - /// Creates a new random UUID - /// - /// Uses the `rand` module's default RNG task as the source - /// of random numbers. Use the rand::Rand trait to supply - /// a custom generator if required. - pub fn new_v4() -> Uuid { - let ub = rand::task_rng().gen_iter::().take(16).collect::>(); - let mut uuid = Uuid{ bytes: [0, .. 16] }; - slice::bytes::copy_memory(uuid.bytes, ub.as_slice()); - uuid.set_variant(VariantRFC4122); - uuid.set_version(Version4Random); - uuid - } - - /// Creates a UUID using the supplied field values - /// - /// # Arguments - /// * `d1` A 32-bit word - /// * `d2` A 16-bit word - /// * `d3` A 16-bit word - /// * `d4` Array of 8 octets - pub fn from_fields(d1: u32, d2: u16, d3: u16, d4: &[u8]) -> Uuid { - // First construct a temporary field-based struct - let mut fields = UuidFields { - data1: 0, - data2: 0, - data3: 0, - data4: [0, ..8] - }; - - fields.data1 = d1.to_be(); - fields.data2 = d2.to_be(); - fields.data3 = d3.to_be(); - slice::bytes::copy_memory(fields.data4, d4); - - unsafe { - transmute(fields) - } - } - - /// Creates a UUID using the supplied bytes - /// - /// # Arguments - /// * `b` An array or slice of 16 bytes - pub fn from_bytes(b: &[u8]) -> Option { - if b.len() != 16 { - return None - } - - let mut uuid = Uuid{ bytes: [0, .. 16] }; - slice::bytes::copy_memory(uuid.bytes, b); - Some(uuid) - } - - /// Specifies the variant of the UUID structure - fn set_variant(&mut self, v: UuidVariant) { - // Octet 8 contains the variant in the most significant 3 bits - match v { - VariantNCS => // b0xx... - self.bytes[8] = self.bytes[8] & 0x7f, - VariantRFC4122 => // b10x... - self.bytes[8] = (self.bytes[8] & 0x3f) | 0x80, - VariantMicrosoft => // b110... - self.bytes[8] = (self.bytes[8] & 0x1f) | 0xc0, - VariantFuture => // b111... - self.bytes[8] = (self.bytes[8] & 0x1f) | 0xe0, - } - } - - /// Returns the variant of the UUID structure - /// - /// This determines the interpretation of the structure of the UUID. - /// Currently only the RFC4122 variant is generated by this module. - /// - /// * [Variant Reference](http://tools.ietf.org/html/rfc4122#section-4.1.1) - pub fn get_variant(&self) -> Option { - if self.bytes[8] & 0x80 == 0x00 { - Some(VariantNCS) - } else if self.bytes[8] & 0xc0 == 0x80 { - Some(VariantRFC4122) - } else if self.bytes[8] & 0xe0 == 0xc0 { - Some(VariantMicrosoft) - } else if self.bytes[8] & 0xe0 == 0xe0 { - Some(VariantFuture) - } else { - None - } - } - - /// Specifies the version number of the UUID - fn set_version(&mut self, v: UuidVersion) { - self.bytes[6] = (self.bytes[6] & 0xF) | ((v as u8) << 4); - } - - /// Returns the version number of the UUID - /// - /// This represents the algorithm used to generate the contents. - /// - /// Currently only the Random (V4) algorithm is supported by this - /// module. There are security and privacy implications for using - /// older versions - see [Wikipedia: Universally Unique Identifier]( - /// http://en.wikipedia.org/wiki/Universally_unique_identifier) for - /// details. - /// - /// * [Version Reference](http://tools.ietf.org/html/rfc4122#section-4.1.3) - pub fn get_version_num(&self) -> uint { - (self.bytes[6] >> 4) as uint - } - - /// Returns the version of the UUID - /// - /// This represents the algorithm used to generate the contents - pub fn get_version(&self) -> Option { - let v = self.bytes[6] >> 4; - match v { - 1 => Some(Version1Mac), - 2 => Some(Version2Dce), - 3 => Some(Version3Md5), - 4 => Some(Version4Random), - 5 => Some(Version5Sha1), - _ => None - } - } - - /// Return an array of 16 octets containing the UUID data - pub fn as_bytes(&self) -> &[u8] { - self.bytes.as_slice() - } - - /// Returns the UUID as a string of 16 hexadecimal digits - /// - /// Example: `936DA01F9ABD4d9d80C702AF85C822A8` - pub fn to_simple_str(&self) -> String { - let mut s: Vec = Vec::from_elem(32, 0u8); - for i in range(0u, 16u) { - let digit = format!("{:02x}", self.bytes[i] as uint); - *s.get_mut(i*2+0) = digit.as_bytes()[0]; - *s.get_mut(i*2+1) = digit.as_bytes()[1]; - } - String::from_utf8(s).unwrap() - } - - /// Returns a string of hexadecimal digits, separated into groups with a hyphen. - /// - /// Example: `550e8400-e29b-41d4-a716-446655440000` - pub fn to_hyphenated_str(&self) -> String { - // Convert to field-based struct as it matches groups in output. - // Ensure fields are in network byte order, as per RFC. - let mut uf: UuidFields; - unsafe { - uf = transmute_copy(&self.bytes); - } - uf.data1 = uf.data1.to_be(); - uf.data2 = uf.data2.to_be(); - uf.data3 = uf.data3.to_be(); - let s = format!("{:08x}-{:04x}-{:04x}-{:02x}{:02x}-\ - {:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", - uf.data1, - uf.data2, uf.data3, - uf.data4[0], uf.data4[1], - uf.data4[2], uf.data4[3], uf.data4[4], - uf.data4[5], uf.data4[6], uf.data4[7]); - s - } - - /// Returns the UUID formatted as a full URN string - /// - /// This is the same as the hyphenated format, but with the "urn:uuid:" prefix. - /// - /// Example: `urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4` - pub fn to_urn_str(&self) -> String { - format!("urn:uuid:{}", self.to_hyphenated_str()) - } - - /// Parses a UUID from a string of hexadecimal digits with optional hyphens - /// - /// Any of the formats generated by this module (simple, hyphenated, urn) are - /// supported by this parsing function. - pub fn parse_string(us: &str) -> Result { - - let mut us = us.clone(); - let orig_len = us.len(); - - // Ensure length is valid for any of the supported formats - if orig_len != 32 && orig_len != 36 && orig_len != 45 { - return Err(ErrorInvalidLength(orig_len)); - } - - // Strip off URN prefix if present - if us.starts_with("urn:uuid:") { - us = us.slice(9, orig_len); - } - - // Make sure all chars are either hex digits or hyphen - for (i, c) in us.chars().enumerate() { - match c { - '0'...'9' | 'A'...'F' | 'a'...'f' | '-' => {}, - _ => return Err(ErrorInvalidCharacter(c, i)), - } - } - - // Split string up by hyphens into groups - let hex_groups: Vec<&str> = us.split_str("-").collect(); - - // Get the length of each group - let group_lens: Vec = hex_groups.iter().map(|&v| v.len()).collect(); - - // Ensure the group lengths are valid - match group_lens.len() { - // Single group, no hyphens - 1 => { - if group_lens[0] != 32 { - return Err(ErrorInvalidLength(group_lens[0])); - } - }, - // Five groups, hyphens in between each - 5 => { - // Ensure each group length matches the expected - for (i, (&gl, &expected)) in - group_lens.iter().zip(UuidGroupLens.iter()).enumerate() { - if gl != expected { - return Err(ErrorInvalidGroupLength(i, gl, expected)) - } - } - }, - _ => { - return Err(ErrorInvalidGroups(group_lens.len())); - } - } - - // Normalise into one long hex string - let vs = hex_groups.concat(); - - // At this point, we know we have a valid hex string, without hyphens - assert!(vs.len() == 32); - assert!(vs.as_slice().chars().all(|c| c.is_digit_radix(16))); - - // Allocate output UUID buffer - let mut ub = [0u8, ..16]; - - // Extract each hex digit from the string - for i in range(0u, 16u) { - ub[i] = FromStrRadix::from_str_radix(vs.as_slice() - .slice(i*2, (i+1)*2), - 16).unwrap(); - } - - Ok(Uuid::from_bytes(ub).unwrap()) - } - - /// Tests if the UUID is nil - pub fn is_nil(&self) -> bool { - return self.bytes.iter().all(|&b| b == 0); - } -} - -impl Default for Uuid { - /// Returns the nil UUID, which is all zeroes - fn default() -> Uuid { - Uuid::nil() - } -} - -impl Clone for Uuid { - /// Returns a copy of the UUID - fn clone(&self) -> Uuid { *self } -} - -impl FromStr for Uuid { - /// Parse a hex string and interpret as a UUID - /// - /// Accepted formats are a sequence of 32 hexadecimal characters, - /// with or without hyphens (grouped as 8, 4, 4, 4, 12). - fn from_str(us: &str) -> Option { - let result = Uuid::parse_string(us); - match result { - Ok(u) => Some(u), - Err(_) => None - } - } -} - -/// Convert the UUID to a hexadecimal-based string representation -impl fmt::Show for Uuid { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.to_simple_str()) - } -} - -/// Test two UUIDs for equality -/// -/// UUIDs are equal only when they are byte-for-byte identical -impl PartialEq for Uuid { - fn eq(&self, other: &Uuid) -> bool { - self.bytes == other.bytes - } -} - -impl Eq for Uuid {} - -// FIXME #9845: Test these more thoroughly -impl, E> Encodable for Uuid { - /// Encode a UUID as a hyphenated string - fn encode(&self, e: &mut T) -> Result<(), E> { - e.emit_str(self.to_hyphenated_str().as_slice()) - } -} - -impl, E> Decodable for Uuid { - /// Decode a UUID from a string - fn decode(d: &mut T) -> Result { - match from_str(try!(d.read_str()).as_slice()) { - Some(decode) => Ok(decode), - None => Err(d.error("Unable to decode UUID")) - } - } -} - -/// Generates a random instance of UUID (V4 conformant) -impl rand::Rand for Uuid { - #[inline] - fn rand(rng: &mut R) -> Uuid { - let ub = rng.gen_iter::().take(16).collect::>(); - let mut uuid = Uuid{ bytes: [0, .. 16] }; - slice::bytes::copy_memory(uuid.bytes, ub.as_slice()); - uuid.set_variant(VariantRFC4122); - uuid.set_version(Version4Random); - uuid - } -} - -#[cfg(test)] -mod uuidtest { - use super::{Uuid, VariantMicrosoft, VariantNCS, VariantRFC4122, - Version1Mac, Version2Dce, Version3Md5, Version4Random, - Version5Sha1}; - use std::rand; - - #[test] - fn test_nil() { - let nil = Uuid::nil(); - let not_nil = Uuid::new_v4(); - - assert!(nil.is_nil()); - assert!(!not_nil.is_nil()); - } - - #[test] - fn test_new() { - // Supported - let uuid1 = Uuid::new(Version4Random).unwrap(); - let s = uuid1.to_simple_str(); - - assert!(s.len() == 32); - assert!(uuid1.get_version().unwrap() == Version4Random); - - // Test unsupported versions - assert!(Uuid::new(Version1Mac) == None); - assert!(Uuid::new(Version2Dce) == None); - assert!(Uuid::new(Version3Md5) == None); - assert!(Uuid::new(Version5Sha1) == None); - } - - #[test] - fn test_new_v4() { - let uuid1 = Uuid::new_v4(); - - assert!(uuid1.get_version().unwrap() == Version4Random); - assert!(uuid1.get_variant().unwrap() == VariantRFC4122); - } - - #[test] - fn test_get_version() { - let uuid1 = Uuid::new_v4(); - - assert!(uuid1.get_version().unwrap() == Version4Random); - assert!(uuid1.get_version_num() == 4); - } - - #[test] - fn test_get_variant() { - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::parse_string("550e8400-e29b-41d4-a716-446655440000").unwrap(); - let uuid3 = Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").unwrap(); - let uuid4 = Uuid::parse_string("936DA01F9ABD4d9dC0C702AF85C822A8").unwrap(); - let uuid5 = Uuid::parse_string("F9168C5E-CEB2-4faa-D6BF-329BF39FA1E4").unwrap(); - let uuid6 = Uuid::parse_string("f81d4fae-7dec-11d0-7765-00a0c91e6bf6").unwrap(); - - assert!(uuid1.get_variant().unwrap() == VariantRFC4122); - assert!(uuid2.get_variant().unwrap() == VariantRFC4122); - assert!(uuid3.get_variant().unwrap() == VariantRFC4122); - assert!(uuid4.get_variant().unwrap() == VariantMicrosoft); - assert!(uuid5.get_variant().unwrap() == VariantMicrosoft); - assert!(uuid6.get_variant().unwrap() == VariantNCS); - } - - #[test] - fn test_parse_uuid_v4() { - use super::{ErrorInvalidCharacter, ErrorInvalidGroups, - ErrorInvalidGroupLength, ErrorInvalidLength}; - - // Invalid - assert!(Uuid::parse_string("").is_err()); - assert!(Uuid::parse_string("!").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E45").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-BBF-329BF39FA1E4").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-BGBF-329BF39FA1E4").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BFF329BF39FA1E4").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faaXB6BFF329BF39FA1E4").is_err()); - assert!(Uuid::parse_string("F9168C5E-CEB-24fa-eB6BFF32-BF39FA1E4").is_err()); - assert!(Uuid::parse_string("01020304-1112-2122-3132-41424344").is_err()); - assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c").is_err()); - assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c88").is_err()); - assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0cg8").is_err()); - assert!(Uuid::parse_string("67e5504410b1426%9247bb680e5fe0c8").is_err()); - - // Valid - assert!(Uuid::parse_string("00000000000000000000000000000000").is_ok()); - assert!(Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok()); - assert!(Uuid::parse_string("67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok()); - assert!(Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4").is_ok()); - assert!(Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c8").is_ok()); - assert!(Uuid::parse_string("01020304-1112-2122-3132-414243444546").is_ok()); - assert!(Uuid::parse_string("urn:uuid:67e55044-10b1-426f-9247-bb680e5fe0c8").is_ok()); - - // Nil - let nil = Uuid::nil(); - assert!(Uuid::parse_string("00000000000000000000000000000000").unwrap() == nil); - assert!(Uuid::parse_string("00000000-0000-0000-0000-000000000000").unwrap() == nil); - - // Round-trip - let uuid_orig = Uuid::new_v4(); - let orig_str = uuid_orig.to_string(); - let uuid_out = Uuid::parse_string(orig_str.as_slice()).unwrap(); - assert!(uuid_orig == uuid_out); - - // Test error reporting - let e = Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c").unwrap_err(); - assert!(match e { ErrorInvalidLength(n) => n==31, _ => false }); - - let e = Uuid::parse_string("67e550X410b1426f9247bb680e5fe0cd").unwrap_err(); - assert!(match e { ErrorInvalidCharacter(c, n) => c=='X' && n==6, _ => false }); - - let e = Uuid::parse_string("67e550-4105b1426f9247bb680e5fe0c").unwrap_err(); - assert!(match e { ErrorInvalidGroups(n) => n==2, _ => false }); - - let e = Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4").unwrap_err(); - assert!(match e { ErrorInvalidGroupLength(g, n, e) => g==3 && n==5 && e==4, _ => false }); - } - - #[test] - fn test_to_simple_str() { - let uuid1 = Uuid::new_v4(); - let s = uuid1.to_simple_str(); - - assert!(s.len() == 32); - assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16))); - } - - #[test] - fn test_to_string() { - let uuid1 = Uuid::new_v4(); - let s = uuid1.to_string(); - - assert!(s.len() == 32); - assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16))); - } - - #[test] - fn test_to_hyphenated_str() { - let uuid1 = Uuid::new_v4(); - let s = uuid1.to_hyphenated_str(); - - assert!(s.len() == 36); - assert!(s.as_slice().chars().all(|c| c.is_digit_radix(16) || c == '-')); - } - - #[test] - fn test_to_urn_str() { - let uuid1 = Uuid::new_v4(); - let ss = uuid1.to_urn_str(); - let s = ss.as_slice().slice(9, ss.len()); - - assert!(ss.as_slice().starts_with("urn:uuid:")); - assert!(s.len() == 36); - assert!(s.as_slice() - .chars() - .all(|c| c.is_digit_radix(16) || c == '-')); - } - - #[test] - fn test_to_str_matching() { - let uuid1 = Uuid::new_v4(); - - let hs = uuid1.to_hyphenated_str(); - let ss = uuid1.to_string(); - - let hsn = String::from_chars(hs.as_slice() - .chars() - .filter(|&c| c != '-') - .collect::>() - .as_slice()); - - assert!(hsn == ss); - } - - #[test] - fn test_string_roundtrip() { - let uuid = Uuid::new_v4(); - - let hs = uuid.to_hyphenated_str(); - let uuid_hs = Uuid::parse_string(hs.as_slice()).unwrap(); - assert!(uuid_hs == uuid); - - let ss = uuid.to_string(); - let uuid_ss = Uuid::parse_string(ss.as_slice()).unwrap(); - assert!(uuid_ss == uuid); - } - - #[test] - fn test_compare() { - let uuid1 = Uuid::new_v4(); - let uuid2 = Uuid::new_v4(); - - assert!(uuid1 == uuid1); - assert!(uuid2 == uuid2); - assert!(uuid1 != uuid2); - assert!(uuid2 != uuid1); - } - - #[test] - fn test_from_fields() { - let d1: u32 = 0xa1a2a3a4; - let d2: u16 = 0xb1b2; - let d3: u16 = 0xc1c2; - let d4: Vec = vec!(0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8); - - let u = Uuid::from_fields(d1, d2, d3, d4.as_slice()); - - let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string(); - let result = u.to_simple_str(); - assert!(result == expected); - } - - #[test] - fn test_from_bytes() { - let b = vec!( 0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, - 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 ); - - let u = Uuid::from_bytes(b.as_slice()).unwrap(); - let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8".to_string(); - - assert!(u.to_simple_str() == expected); - } - - #[test] - fn test_as_bytes() { - let u = Uuid::new_v4(); - let ub = u.as_bytes(); - - assert!(ub.len() == 16); - assert!(! ub.iter().all(|&b| b == 0)); - } - - #[test] - fn test_bytes_roundtrip() { - let b_in: [u8, ..16] = [ 0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, - 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8 ]; - - let u = Uuid::from_bytes(b_in.clone()).unwrap(); - - let b_out = u.as_bytes(); - - assert!(b_in == b_out); - } - - #[test] - fn test_operator_eq() { - let u1 = Uuid::new_v4(); - let u2 = u1.clone(); - let u3 = Uuid::new_v4(); - - assert!(u1 == u1); - assert!(u1 == u2); - assert!(u2 == u1); - - assert!(u1 != u3); - assert!(u3 != u1); - assert!(u2 != u3); - assert!(u3 != u2); - } - - #[test] - fn test_rand_rand() { - let mut rng = rand::task_rng(); - let u: Uuid = rand::Rand::rand(&mut rng); - let ub = u.as_bytes(); - - assert!(ub.len() == 16); - assert!(! ub.iter().all(|&b| b == 0)); - } - - #[test] - fn test_serialize_round_trip() { - use serialize::json; - - let u = Uuid::new_v4(); - let s = json::encode(&u); - let u2 = json::decode(s.as_slice()).unwrap(); - assert_eq!(u, u2); - } - - #[test] - fn test_bad_decode() { - use serialize::json; - use serialize::{Decodable}; - - let js_good = json::String("a1a2a3a4a5a6a7a8a1a2a3a4a5a6a7a8".to_string()); - let js_bad1 = json::String("a1a2a3a4a5a6a7a8a1a2a3a4a5a6a7ah".to_string()); - let js_bad2 = json::String("a1a2a3a4a5a6a7a8a1a2a3a4a5a6a7a".to_string()); - - let u_good: Result = Decodable::decode(&mut json::Decoder::new(js_good)); - let u_bad1: Result = Decodable::decode(&mut json::Decoder::new(js_bad1)); - let u_bad2: Result = Decodable::decode(&mut json::Decoder::new(js_bad2)); - assert!(u_good.is_ok()); - assert!(u_bad1.is_err()); - assert!(u_bad2.is_err()); - } - - #[test] - fn test_iterbytes_impl_for_uuid() { - use std::collections::HashSet; - let mut set = HashSet::new(); - let id1 = Uuid::new_v4(); - let id2 = Uuid::new_v4(); - set.insert(id1); - assert!(set.contains(&id1)); - assert!(!set.contains(&id2)); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use super::Uuid; - - #[bench] - pub fn create_uuids(b: &mut Bencher) { - b.iter(|| { - Uuid::new_v4(); - }) - } - - #[bench] - pub fn uuid_to_string(b: &mut Bencher) { - let u = Uuid::new_v4(); - b.iter(|| { - u.to_string(); - }) - } - - #[bench] - pub fn parse_str(b: &mut Bencher) { - let s = "urn:uuid:F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4"; - b.iter(|| { - Uuid::parse_string(s).unwrap(); - }) - } -} diff --git a/src/test/auxiliary/anon-extern-mod-cross-crate-1.rs b/src/test/auxiliary/anon-extern-mod-cross-crate-1.rs index 049a91cfdeb..12ab62267a3 100644 --- a/src/test/auxiliary/anon-extern-mod-cross-crate-1.rs +++ b/src/test/auxiliary/anon-extern-mod-cross-crate-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="anonexternmod#0.1"] +#![crate_name="anonexternmod"] extern crate libc; diff --git a/src/test/auxiliary/cci_impl_lib.rs b/src/test/auxiliary/cci_impl_lib.rs index ec48862ff39..40a9a52061f 100644 --- a/src/test/auxiliary/cci_impl_lib.rs +++ b/src/test/auxiliary/cci_impl_lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="cci_impl_lib"] +#![crate_name="cci_impl_lib"] pub trait uint_helpers { fn to(&self, v: uint, f: |uint|); diff --git a/src/test/auxiliary/cci_iter_lib.rs b/src/test/auxiliary/cci_iter_lib.rs index 2619ac71d99..84ade3572f9 100644 --- a/src/test/auxiliary/cci_iter_lib.rs +++ b/src/test/auxiliary/cci_iter_lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="cci_iter_lib"] +#![crate_name="cci_iter_lib"] #[inline] pub fn iter(v: &[T], f: |&T|) { diff --git a/src/test/auxiliary/cci_no_inline_lib.rs b/src/test/auxiliary/cci_no_inline_lib.rs index e9f82ef9413..67f55cca1e1 100644 --- a/src/test/auxiliary/cci_no_inline_lib.rs +++ b/src/test/auxiliary/cci_no_inline_lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="cci_no_inline_lib"] +#![crate_name="cci_no_inline_lib"] // same as cci_iter_lib, more-or-less, but not marked inline @@ -16,7 +16,7 @@ pub fn iter(v: Vec , f: |uint|) { let mut i = 0u; let n = v.len(); while i < n { - f(*v.get(i)); + f(v[i]); i += 1u; } } diff --git a/src/test/auxiliary/changing-crates-a1.rs b/src/test/auxiliary/changing-crates-a1.rs index 360ab79c5b4..18162c5f756 100644 --- a/src/test/auxiliary/changing-crates-a1.rs +++ b/src/test/auxiliary/changing-crates-a1.rs @@ -8,6 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id = "a"] +#![crate_name = "a"] pub fn foo() {} diff --git a/src/test/auxiliary/changing-crates-a2.rs b/src/test/auxiliary/changing-crates-a2.rs index 650b3ac7dca..a54dcbbbfc2 100644 --- a/src/test/auxiliary/changing-crates-a2.rs +++ b/src/test/auxiliary/changing-crates-a2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id = "a"] +#![crate_name = "a"] pub fn foo() { println!("hello!"); } diff --git a/src/test/auxiliary/changing-crates-b.rs b/src/test/auxiliary/changing-crates-b.rs index 63bdb889fd0..81f924e29da 100644 --- a/src/test/auxiliary/changing-crates-b.rs +++ b/src/test/auxiliary/changing-crates-b.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id = "b"] +#![crate_name = "b"] extern crate a; diff --git a/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs b/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs index 5e2a04001b5..f3d5bf2d65e 100644 --- a/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs +++ b/src/test/auxiliary/crate-method-reexport-grrrrrrr2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crate_method_reexport_grrrrrrr2"] +#![crate_name="crate_method_reexport_grrrrrrr2"] pub use name_pool::add; diff --git a/src/test/auxiliary/crateresolve3-1.rs b/src/test/auxiliary/crateresolve3-1.rs index 9d00b92182e..473528c681e 100644 --- a/src/test/auxiliary/crateresolve3-1.rs +++ b/src/test/auxiliary/crateresolve3-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve3#0.1"] +#![crate_name="crateresolve3#0.1"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/crateresolve3-2.rs b/src/test/auxiliary/crateresolve3-2.rs index 117e585e9ad..1e95fa6b639 100644 --- a/src/test/auxiliary/crateresolve3-2.rs +++ b/src/test/auxiliary/crateresolve3-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve3#0.2"] +#![crate_name="crateresolve3#0.2"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/crateresolve4a-1.rs b/src/test/auxiliary/crateresolve4a-1.rs index dfe1d92c593..68a69f6dc90 100644 --- a/src/test/auxiliary/crateresolve4a-1.rs +++ b/src/test/auxiliary/crateresolve4a-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve4a#0.1"] +#![crate_name="crateresolve4a#0.1"] #![crate_type = "lib"] pub fn f() -> int { 10 } diff --git a/src/test/auxiliary/crateresolve4a-2.rs b/src/test/auxiliary/crateresolve4a-2.rs index 196751e99fa..6e23fddbce7 100644 --- a/src/test/auxiliary/crateresolve4a-2.rs +++ b/src/test/auxiliary/crateresolve4a-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve4a#0.2"] +#![crate_name="crateresolve4a#0.2"] #![crate_type = "lib"] pub fn g() -> int { 20 } diff --git a/src/test/auxiliary/crateresolve4b-1.rs b/src/test/auxiliary/crateresolve4b-1.rs index 54ee9c2d5a2..843fd57ee40 100644 --- a/src/test/auxiliary/crateresolve4b-1.rs +++ b/src/test/auxiliary/crateresolve4b-1.rs @@ -10,7 +10,7 @@ // aux-build:crateresolve4a-1.rs // aux-build:crateresolve4a-2.rs -#![crate_id="crateresolve4b#0.1"] +#![crate_name="crateresolve4b#0.1"] #![crate_type = "lib"] extern crate "crateresolve4a#0.2" as crateresolve4a; diff --git a/src/test/auxiliary/crateresolve4b-2.rs b/src/test/auxiliary/crateresolve4b-2.rs index 9221ecc697b..28c89c79316 100644 --- a/src/test/auxiliary/crateresolve4b-2.rs +++ b/src/test/auxiliary/crateresolve4b-2.rs @@ -10,7 +10,7 @@ // aux-build:crateresolve4a-1.rs // aux-build:crateresolve4a-2.rs -#![crate_id="crateresolve4b#0.2"] +#![crate_name="crateresolve4b#0.2"] #![crate_type = "lib"] extern crate "crateresolve4a#0.1" as crateresolve4a; diff --git a/src/test/auxiliary/crateresolve5-1.rs b/src/test/auxiliary/crateresolve5-1.rs index de48981ed3e..223e4f50ae8 100644 --- a/src/test/auxiliary/crateresolve5-1.rs +++ b/src/test/auxiliary/crateresolve5-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve5#0.1"] +#![crate_name="crateresolve5#0.1"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/crateresolve5-2.rs b/src/test/auxiliary/crateresolve5-2.rs index f8727605c3d..38740886b37 100644 --- a/src/test/auxiliary/crateresolve5-2.rs +++ b/src/test/auxiliary/crateresolve5-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve5#0.2"] +#![crate_name="crateresolve5#0.2"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/crateresolve8-1.rs b/src/test/auxiliary/crateresolve8-1.rs index 062d606a4c1..5262d662971 100644 --- a/src/test/auxiliary/crateresolve8-1.rs +++ b/src/test/auxiliary/crateresolve8-1.rs @@ -9,7 +9,7 @@ // except according to those terms. // default link meta for 'package_id' will be equal to filestem -#![crate_id="crateresolve8#0.1"] +#![crate_name="crateresolve8#0.1"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/crateresolve_calories-1.rs b/src/test/auxiliary/crateresolve_calories-1.rs index a0d7ae7cd2f..4dba722971e 100644 --- a/src/test/auxiliary/crateresolve_calories-1.rs +++ b/src/test/auxiliary/crateresolve_calories-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve_calories#0.1"] +#![crate_name="crateresolve_calories#0.1"] #![crate_type = "lib"] pub fn f() -> int { 100 } diff --git a/src/test/auxiliary/crateresolve_calories-2.rs b/src/test/auxiliary/crateresolve_calories-2.rs index bbad91625cc..c7e26c8f506 100644 --- a/src/test/auxiliary/crateresolve_calories-2.rs +++ b/src/test/auxiliary/crateresolve_calories-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateresolve_calories#0.1"] +#![crate_name="crateresolve_calories#0.1"] #![crate_type = "lib"] pub fn f() -> int { 200 } diff --git a/src/test/auxiliary/foreign_lib.rs b/src/test/auxiliary/foreign_lib.rs index 500475091e0..a5d672e3c0c 100644 --- a/src/test/auxiliary/foreign_lib.rs +++ b/src/test/auxiliary/foreign_lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="foreign_lib"] +#![crate_name="foreign_lib"] pub mod rustrt { extern crate libc; diff --git a/src/test/auxiliary/inherited_stability.rs b/src/test/auxiliary/inherited_stability.rs index af3dd94fe1d..4016a76206b 100644 --- a/src/test/auxiliary/inherited_stability.rs +++ b/src/test/auxiliary/inherited_stability.rs @@ -7,7 +7,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="inherited_stability#0.1"] +#![crate_name="inherited_stability"] #![crate_type = "lib"] #![experimental] diff --git a/src/test/auxiliary/inline_dtor.rs b/src/test/auxiliary/inline_dtor.rs index fa0d447a8ed..dd1fdc2e498 100644 --- a/src/test/auxiliary/inline_dtor.rs +++ b/src/test/auxiliary/inline_dtor.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="inline_dtor#0.1"] +#![crate_name="inline_dtor"] pub struct Foo; diff --git a/src/test/auxiliary/iss.rs b/src/test/auxiliary/iss.rs index 3a9d76406e1..37edcdf7628 100644 --- a/src/test/auxiliary/iss.rs +++ b/src/test/auxiliary/iss.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="issue6919_3#0.1"] +#![crate_name="issue6919_3"] // part of issue-6919.rs diff --git a/src/test/auxiliary/issue-2380.rs b/src/test/auxiliary/issue-2380.rs index 1cba738c564..af6bb050ef5 100644 --- a/src/test/auxiliary/issue-2380.rs +++ b/src/test/auxiliary/issue-2380.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="a"] +#![crate_name="a"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/issue-2414-a.rs b/src/test/auxiliary/issue-2414-a.rs index 08eaec2ed35..fe1ef549d06 100644 --- a/src/test/auxiliary/issue-2414-a.rs +++ b/src/test/auxiliary/issue-2414-a.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="a#0.1"] +#![crate_name="a"] #![crate_type = "lib"] type t1 = uint; diff --git a/src/test/auxiliary/issue-2414-b.rs b/src/test/auxiliary/issue-2414-b.rs index 51fd979f961..b1c95bcb430 100644 --- a/src/test/auxiliary/issue-2414-b.rs +++ b/src/test/auxiliary/issue-2414-b.rs @@ -9,7 +9,7 @@ // except according to those terms. -#![crate_id="b#0.1"] +#![crate_name="b"] #![crate_type = "lib"] extern crate a; diff --git a/src/test/auxiliary/issue-2526.rs b/src/test/auxiliary/issue-2526.rs index c2e1dd69a90..e3ce4e8f656 100644 --- a/src/test/auxiliary/issue-2526.rs +++ b/src/test/auxiliary/issue-2526.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="issue_2526#0.2"] +#![crate_name="issue_2526"] #![crate_type = "lib"] #![feature(unsafe_destructor)] diff --git a/src/test/auxiliary/issue-2631-a.rs b/src/test/auxiliary/issue-2631-a.rs index 3bedbd9089c..e340331dbfd 100644 --- a/src/test/auxiliary/issue-2631-a.rs +++ b/src/test/auxiliary/issue-2631-a.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="req"] +#![crate_name="req"] #![crate_type = "lib"] use std::cell::RefCell; @@ -19,7 +19,5 @@ pub type header_map = HashMap>>>>; // the unused ty param is necessary so this gets monomorphized pub fn request(req: &header_map) { - let _x = (**((**req.get(&"METHOD".to_string())).clone()).borrow() - .clone() - .get(0)).clone(); + let _x = req["METHOD".to_string()].clone().borrow().clone()[0].clone(); } diff --git a/src/test/auxiliary/issue-3012-1.rs b/src/test/auxiliary/issue-3012-1.rs index dbb863da90a..25eb67e0423 100644 --- a/src/test/auxiliary/issue-3012-1.rs +++ b/src/test/auxiliary/issue-3012-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="socketlib"] +#![crate_name="socketlib"] #![crate_type = "lib"] pub mod socket { diff --git a/src/test/auxiliary/issue-4208-cc.rs b/src/test/auxiliary/issue-4208-cc.rs index cc75ca6f3af..a7c1633784d 100644 --- a/src/test/auxiliary/issue-4208-cc.rs +++ b/src/test/auxiliary/issue-4208-cc.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="numeric#0.1"] +#![crate_name="numeric"] #![crate_type = "lib"] pub trait Trig { diff --git a/src/test/auxiliary/issue_2242_a.rs b/src/test/auxiliary/issue_2242_a.rs index 4fae888c6ad..33b6d116c8a 100644 --- a/src/test/auxiliary/issue_2242_a.rs +++ b/src/test/auxiliary/issue_2242_a.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="a#0.1"] +#![crate_name="a#0.1"] #![crate_type = "lib"] trait to_strz { diff --git a/src/test/auxiliary/issue_2242_c.rs b/src/test/auxiliary/issue_2242_c.rs index 97d25568735..31d119b20be 100644 --- a/src/test/auxiliary/issue_2242_c.rs +++ b/src/test/auxiliary/issue_2242_c.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="c#0.1"] +#![crate_name="c#0.1"] #![crate_type = "lib"] extern crate a; diff --git a/src/test/auxiliary/issue_3979_traits.rs b/src/test/auxiliary/issue_3979_traits.rs index ef7e4d0fc09..91faace7a3f 100644 --- a/src/test/auxiliary/issue_3979_traits.rs +++ b/src/test/auxiliary/issue_3979_traits.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="issue_3979_traits#0.1"] +#![crate_name="issue_3979_traits"] #![crate_type = "lib"] diff --git a/src/test/auxiliary/lint_output_format.rs b/src/test/auxiliary/lint_output_format.rs index 00500da655f..181b651ef52 100755 --- a/src/test/auxiliary/lint_output_format.rs +++ b/src/test/auxiliary/lint_output_format.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="lint_output_format#0.1"] +#![crate_name="lint_output_format"] #![crate_type = "lib"] #[deprecated] diff --git a/src/test/auxiliary/lint_stability.rs b/src/test/auxiliary/lint_stability.rs index bae86f04b23..06031eb6c6c 100644 --- a/src/test/auxiliary/lint_stability.rs +++ b/src/test/auxiliary/lint_stability.rs @@ -7,7 +7,7 @@ // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="lint_stability#0.1"] +#![crate_name="lint_stability"] #![crate_type = "lib"] #![feature(macro_rules)] diff --git a/src/test/auxiliary/macro_crate_test.rs b/src/test/auxiliary/macro_crate_test.rs index befd33fca4e..1c26ac26d7c 100644 --- a/src/test/auxiliary/macro_crate_test.rs +++ b/src/test/auxiliary/macro_crate_test.rs @@ -51,7 +51,7 @@ fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), - cx.cfg(), Vec::from_slice(tts)); + cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacExpr::new(quote_expr!(&mut *cx, $expr)) } diff --git a/src/test/auxiliary/static-function-pointer-aux.rs b/src/test/auxiliary/static-function-pointer-aux.rs index c08f725ff0a..27befee6f07 100644 --- a/src/test/auxiliary/static-function-pointer-aux.rs +++ b/src/test/auxiliary/static-function-pointer-aux.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="static-function-pointer-aux"] +#![crate_name="static-function-pointer-aux"] pub fn f(x: int) -> int { -x } diff --git a/src/test/auxiliary/static-methods-crate.rs b/src/test/auxiliary/static-methods-crate.rs index afb35112fb8..eef2fdbfea9 100644 --- a/src/test/auxiliary/static-methods-crate.rs +++ b/src/test/auxiliary/static-methods-crate.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="static_methods_crate#0.1"] +#![crate_name="static_methods_crate"] #![crate_type = "lib"] use std::int; diff --git a/src/test/auxiliary/struct_variant_xc_aux.rs b/src/test/auxiliary/struct_variant_xc_aux.rs index 88b6b363222..4ef8701030f 100644 --- a/src/test/auxiliary/struct_variant_xc_aux.rs +++ b/src/test/auxiliary/struct_variant_xc_aux.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="struct_variant_xc_aux#0.1"] +#![crate_name="struct_variant_xc_aux"] #![crate_type = "lib"] #![feature(struct_variant)] diff --git a/src/test/auxiliary/svh-a-base.rs b/src/test/auxiliary/svh-a-base.rs index b83e96fc47d..c035f1203f8 100644 --- a/src/test/auxiliary/svh-a-base.rs +++ b/src/test/auxiliary/svh-a-base.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-lit.rs b/src/test/auxiliary/svh-a-change-lit.rs index 81c2c39bd52..614487c9817 100644 --- a/src/test/auxiliary/svh-a-change-lit.rs +++ b/src/test/auxiliary/svh-a-change-lit.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-significant-cfg.rs b/src/test/auxiliary/svh-a-change-significant-cfg.rs index 33dd3868566..99506309a59 100644 --- a/src/test/auxiliary/svh-a-change-significant-cfg.rs +++ b/src/test/auxiliary/svh-a-change-significant-cfg.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-trait-bound.rs b/src/test/auxiliary/svh-a-change-trait-bound.rs index 04c320d4016..8ec4eaebbe8 100644 --- a/src/test/auxiliary/svh-a-change-trait-bound.rs +++ b/src/test/auxiliary/svh-a-change-trait-bound.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-type-arg.rs b/src/test/auxiliary/svh-a-change-type-arg.rs index 33f2bf862ed..ad120e12f86 100644 --- a/src/test/auxiliary/svh-a-change-type-arg.rs +++ b/src/test/auxiliary/svh-a-change-type-arg.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-type-ret.rs b/src/test/auxiliary/svh-a-change-type-ret.rs index 3eea77fdb95..c68c13c0991 100644 --- a/src/test/auxiliary/svh-a-change-type-ret.rs +++ b/src/test/auxiliary/svh-a-change-type-ret.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-change-type-static.rs b/src/test/auxiliary/svh-a-change-type-static.rs index ff8b8d6db4c..6c13e84a7fe 100644 --- a/src/test/auxiliary/svh-a-change-type-static.rs +++ b/src/test/auxiliary/svh-a-change-type-static.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-comment.rs b/src/test/auxiliary/svh-a-comment.rs index 208f39ffedc..3d0973cb7ba 100644 --- a/src/test/auxiliary/svh-a-comment.rs +++ b/src/test/auxiliary/svh-a-comment.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-doc.rs b/src/test/auxiliary/svh-a-doc.rs index 667a3b28cea..1ad9e5e1c0e 100644 --- a/src/test/auxiliary/svh-a-doc.rs +++ b/src/test/auxiliary/svh-a-doc.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-macro.rs b/src/test/auxiliary/svh-a-macro.rs index f4279b44b4e..6bd36b5a9b1 100644 --- a/src/test/auxiliary/svh-a-macro.rs +++ b/src/test/auxiliary/svh-a-macro.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-no-change.rs b/src/test/auxiliary/svh-a-no-change.rs index b83e96fc47d..c035f1203f8 100644 --- a/src/test/auxiliary/svh-a-no-change.rs +++ b/src/test/auxiliary/svh-a-no-change.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-redundant-cfg.rs b/src/test/auxiliary/svh-a-redundant-cfg.rs index 203dadd633e..d67c8f4c181 100644 --- a/src/test/auxiliary/svh-a-redundant-cfg.rs +++ b/src/test/auxiliary/svh-a-redundant-cfg.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-a-whitespace.rs b/src/test/auxiliary/svh-a-whitespace.rs index 9b332a294d6..73798f37875 100644 --- a/src/test/auxiliary/svh-a-whitespace.rs +++ b/src/test/auxiliary/svh-a-whitespace.rs @@ -15,7 +15,7 @@ #![feature(macro_rules)] -#![crate_id = "a"] +#![crate_name = "a"] macro_rules! three { () => { 3 } diff --git a/src/test/auxiliary/svh-b.rs b/src/test/auxiliary/svh-b.rs index 713fed591c8..b8946fdc995 100644 --- a/src/test/auxiliary/svh-b.rs +++ b/src/test/auxiliary/svh-b.rs @@ -16,7 +16,7 @@ //! the change could affect the downstream crate content or not //! (#14132). -#![crate_id = "b"] +#![crate_name = "b"] extern crate a; diff --git a/src/test/auxiliary/svh-uta-base.rs b/src/test/auxiliary/svh-uta-base.rs index 5b4617c05ea..67fdac5df03 100644 --- a/src/test/auxiliary/svh-uta-base.rs +++ b/src/test/auxiliary/svh-uta-base.rs @@ -15,7 +15,7 @@ //! //! This is the upstream crate. -#![crate_id = "uta"] +#![crate_name = "uta"] mod traits { pub trait TraitA { fn val(&self) -> int { 2 } } diff --git a/src/test/auxiliary/svh-uta-change-use-trait.rs b/src/test/auxiliary/svh-uta-change-use-trait.rs index 1a2fb3cee1e..dfcf02c0ff5 100644 --- a/src/test/auxiliary/svh-uta-change-use-trait.rs +++ b/src/test/auxiliary/svh-uta-change-use-trait.rs @@ -15,7 +15,7 @@ //! //! This is the upstream crate. -#![crate_id = "uta"] +#![crate_name = "uta"] mod traits { pub trait TraitA { fn val(&self) -> int { 2 } } diff --git a/src/test/auxiliary/svh-utb.rs b/src/test/auxiliary/svh-utb.rs index ccc0bac5150..eb3da985242 100644 --- a/src/test/auxiliary/svh-utb.rs +++ b/src/test/auxiliary/svh-utb.rs @@ -15,7 +15,7 @@ //! //! This is the downstream crate. -#![crate_id = "utb"] +#![crate_name = "utb"] extern crate uta; diff --git a/src/test/auxiliary/trait_default_method_xc_aux.rs b/src/test/auxiliary/trait_default_method_xc_aux.rs index 159ecdcb42a..7424c21be3d 100644 --- a/src/test/auxiliary/trait_default_method_xc_aux.rs +++ b/src/test/auxiliary/trait_default_method_xc_aux.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="trait_default_method_xc_aux"] +#![crate_name="trait_default_method_xc_aux"] pub struct Something { pub x: int } diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index 9af3c0c6c8c..404e2e31b05 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -68,7 +68,7 @@ fn shift_push() { let mut v2 = Vec::new(); while v1.len() > 0 { - v2.push(v1.shift().unwrap()); + v2.push(v1.remove(0).unwrap()); } } @@ -93,9 +93,11 @@ fn vec_plus() { while i < 1500 { let rv = Vec::from_elem(r.gen_range(0u, i + 1), i); if r.gen() { - v.push_all_move(rv); + v.extend(rv.into_iter()); } else { - v = rv.clone().append(v.as_slice()); + let mut rv = rv.clone(); + rv.push_all(v.as_slice()); + v = rv; } i += 1; } @@ -109,10 +111,14 @@ fn vec_append() { while i < 1500 { let rv = Vec::from_elem(r.gen_range(0u, i + 1), i); if r.gen() { - v = v.clone().append(rv.as_slice()); + let mut t = v.clone(); + t.push_all(rv.as_slice()); + v = t; } else { - v = rv.clone().append(v.as_slice()); + let mut t = rv.clone(); + t.push_all(v.as_slice()); + v = t; } i += 1; } diff --git a/src/test/bench/core-uint-to-str.rs b/src/test/bench/core-uint-to-str.rs index 1f527e89eb2..98113cb8347 100644 --- a/src/test/bench/core-uint-to-str.rs +++ b/src/test/bench/core-uint-to-str.rs @@ -21,7 +21,7 @@ fn main() { args.into_iter().collect() }; - let n = from_str::(args.get(1).as_slice()).unwrap(); + let n = from_str::(args[1].as_slice()).unwrap(); for i in range(0u, n) { let x = i.to_string(); diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index d1a2dcf6d55..1a9ffd68284 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -72,8 +72,8 @@ fn main() { args.clone().into_iter().collect() }; - let num_tasks = from_str::(args.get(1).as_slice()).unwrap(); - let msg_per_task = from_str::(args.get(2).as_slice()).unwrap(); + let num_tasks = from_str::(args[1].as_slice()).unwrap(); + let msg_per_task = from_str::(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index c07656a5e4b..5e192a14793 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -72,8 +72,8 @@ fn main() { args.clone().into_iter().collect() }; - let num_tasks = from_str::(args.get(1).as_slice()).unwrap(); - let msg_per_task = from_str::(args.get(2).as_slice()).unwrap(); + let num_tasks = from_str::(args[1].as_slice()).unwrap(); + let msg_per_task = from_str::(args[2].as_slice()).unwrap(); let (mut num_chan, num_port) = init(); diff --git a/src/test/bench/shootout-ackermann.rs b/src/test/bench/shootout-ackermann.rs index 90d2c857858..e7a50382c94 100644 --- a/src/test/bench/shootout-ackermann.rs +++ b/src/test/bench/shootout-ackermann.rs @@ -31,6 +31,6 @@ fn main() { } else { args.into_iter().collect() }; - let n = from_str::(args.get(1).as_slice()).unwrap(); + let n = from_str::(args[1].as_slice()).unwrap(); println!("Ack(3,{}): {}\n", n, ack(3, n)); } diff --git a/src/test/bench/shootout-fibo.rs b/src/test/bench/shootout-fibo.rs index 1f42cc6e00c..10c0d0a8044 100644 --- a/src/test/bench/shootout-fibo.rs +++ b/src/test/bench/shootout-fibo.rs @@ -27,6 +27,6 @@ fn main() { } else { args.into_iter().collect() }; - let n = from_str::(args.get(1).as_slice()).unwrap(); + let n = from_str::(args[1].as_slice()).unwrap(); println!("{}\n", fib(n)); } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 1754df9bf44..5d77e27f948 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -83,7 +83,7 @@ fn find(mm: &HashMap , uint>, key: String) -> uint { // given a map, increment the counter for a key fn update_freq(mm: &mut HashMap , uint>, key: &[u8]) { - let key = Vec::from_slice(key); + let key = key.to_vec(); let newval = match mm.pop(&key) { Some(v) => v + 1, None => 1 @@ -103,7 +103,7 @@ fn windows_with_carry(bb: &[u8], nn: uint, it: |window: &[u8]|) -> Vec { ii += 1u; } - return Vec::from_slice(bb[len - (nn - 1u)..len]); + return bb[len - (nn - 1u)..len].to_vec(); } fn make_sequence_processor(sz: uint, @@ -117,15 +117,14 @@ fn make_sequence_processor(sz: uint, loop { - line = from_parent.recv(); - if line == Vec::new() { break; } + line = from_parent.recv(); + if line == Vec::new() { break; } - carry = windows_with_carry(carry.append(line.as_slice()).as_slice(), - sz, - |window| { - update_freq(&mut freqs, window); - total += 1u; - }); + carry.push_all(line.as_slice()); + carry = windows_with_carry(carry.as_slice(), sz, |window| { + update_freq(&mut freqs, window); + total += 1u; + }); } let buffer = match sz { @@ -149,7 +148,7 @@ fn main() { let rdr = if os::getenv("RUST_BENCH").is_some() { let foo = include_bin!("shootout-k-nucleotide.data"); - box MemReader::new(Vec::from_slice(foo)) as Box + box MemReader::new(foo.to_vec()) as Box } else { box stdio::stdin() as Box }; @@ -203,8 +202,8 @@ fn main() { let line_bytes = line.as_bytes(); for (ii, _sz) in sizes.iter().enumerate() { - let lb = Vec::from_slice(line_bytes); - to_child.get(ii).send(lb); + let lb = line_bytes.to_vec(); + to_child[ii].send(lb); } } @@ -215,11 +214,11 @@ fn main() { // finish... for (ii, _sz) in sizes.iter().enumerate() { - to_child.get(ii).send(Vec::new()); + to_child[ii].send(Vec::new()); } // now fetch and print result messages for (ii, _sz) in sizes.iter().enumerate() { - println!("{}", from_child.get(ii).recv()); + println!("{}", from_child[ii].recv()); } } diff --git a/src/test/bench/shootout-nbody.rs b/src/test/bench/shootout-nbody.rs index 3c8e8389564..8486fa5b034 100644 --- a/src/test/bench/shootout-nbody.rs +++ b/src/test/bench/shootout-nbody.rs @@ -102,7 +102,7 @@ fn advance(bodies: &mut [Planet, ..N_BODIES], dt: f64, steps: int) { for _ in range(0, steps) { let mut b_slice = bodies.as_mut_slice(); loop { - let bi = match b_slice.mut_shift_ref() { + let bi = match shift_mut_ref(&mut b_slice) { Some(bi) => bi, None => break }; @@ -183,3 +183,21 @@ fn main() { println!("{:.9f}", energy(&bodies)); } + +/// Pop a mutable reference off the head of a slice, mutating the slice to no +/// longer contain the mutable reference. This is a safe operation because the +/// two mutable borrows are entirely disjoint. +fn shift_mut_ref<'a, T>(r: &mut &'a mut [T]) -> Option<&'a mut T> { + use std::mem; + use std::raw::Repr; + + if r.len() == 0 { return None } + unsafe { + let mut raw = r.repr(); + let ret = raw.data as *mut T; + raw.data = raw.data.offset(1); + raw.len -= 1; + *r = mem::transmute(raw); + Some(unsafe { &mut *ret }) + } +} diff --git a/src/test/bench/shootout-pfib.rs b/src/test/bench/shootout-pfib.rs index 516bd99ab55..91b9e058e8f 100644 --- a/src/test/bench/shootout-pfib.rs +++ b/src/test/bench/shootout-pfib.rs @@ -102,7 +102,7 @@ fn main() { if opts.stress { stress(2); } else { - let max = uint::parse_bytes(args.get(1).as_bytes(), 10u).unwrap() as + let max = uint::parse_bytes(args[1].as_bytes(), 10u).unwrap() as int; let num_trials = 10; diff --git a/src/test/bench/std-smallintmap.rs b/src/test/bench/std-smallintmap.rs index c495e597ca6..2086980b016 100644 --- a/src/test/bench/std-smallintmap.rs +++ b/src/test/bench/std-smallintmap.rs @@ -25,7 +25,7 @@ fn append_sequential(min: uint, max: uint, map: &mut SmallIntMap) { fn check_sequential(min: uint, max: uint, map: &SmallIntMap) { for i in range(min, max) { - assert_eq!(*map.get(&i), i + 22u); + assert_eq!(map[i], i + 22u); } } @@ -38,8 +38,8 @@ fn main() { } else { args.into_iter().collect() }; - let max = from_str::(args.get(1).as_slice()).unwrap(); - let rep = from_str::(args.get(2).as_slice()).unwrap(); + let max = from_str::(args[1].as_slice()).unwrap(); + let rep = from_str::(args[2].as_slice()).unwrap(); let mut checkf = 0.0; let mut appendf = 0.0; diff --git a/src/test/bench/sudoku.rs b/src/test/bench/sudoku.rs index 728f6bd043a..01c412c6d31 100644 --- a/src/test/bench/sudoku.rs +++ b/src/test/bench/sudoku.rs @@ -55,8 +55,8 @@ impl Sudoku { pub fn equal(&self, other: &Sudoku) -> bool { for row in range(0u8, 9u8) { for col in range(0u8, 9u8) { - if *self.grid.get(row as uint).get(col as uint) != - *other.grid.get(row as uint).get(col as uint) { + if self.grid[row as uint][col as uint] != + other.grid[row as uint][col as uint] { return false; } } @@ -77,10 +77,10 @@ impl Sudoku { .collect(); if comps.len() == 3u { - let row = from_str::(*comps.get(0)).unwrap() as u8; - let col = from_str::(*comps.get(1)).unwrap() as u8; + let row = from_str::(comps[0]).unwrap() as u8; + let col = from_str::(comps[1]).unwrap() as u8; *g.get_mut(row as uint).get_mut(col as uint) = - from_str::(*comps.get(2)).unwrap() as u8; + from_str::(comps[2]).unwrap() as u8; } else { fail!("Invalid sudoku file"); @@ -91,11 +91,9 @@ impl Sudoku { pub fn write(&self, writer: &mut io::Writer) { for row in range(0u8, 9u8) { - write!(writer, "{}", *self.grid.get(row as uint).get(0)); + write!(writer, "{}", self.grid[row as uint][0]); for col in range(1u8, 9u8) { - write!(writer, " {}", *self.grid - .get(row as uint) - .get(col as uint)); + write!(writer, " {}", self.grid[row as uint][col as uint]); } write!(writer, "\n"); } @@ -106,7 +104,7 @@ impl Sudoku { let mut work: Vec<(u8, u8)> = Vec::new(); /* queue of uncolored fields */ for row in range(0u8, 9u8) { for col in range(0u8, 9u8) { - let color = *self.grid.get(row as uint).get(col as uint); + let color = self.grid[row as uint][col as uint]; if color == 0u8 { work.push((row, col)); } @@ -116,9 +114,9 @@ impl Sudoku { let mut ptr = 0u; let end = work.len(); while ptr < end { - let (row, col) = *work.get(ptr); + let (row, col) = work[ptr]; // is there another color to try? - let the_color = *self.grid.get(row as uint).get(col as uint) + + let the_color = self.grid[row as uint][col as uint] + (1 as u8); if self.next_color(row, col, the_color) { // yes: advance work list @@ -151,12 +149,10 @@ impl Sudoku { // find colors available in neighbourhood of (row, col) fn drop_colors(&mut self, avail: &mut Colors, row: u8, col: u8) { for idx in range(0u8, 9u8) { - avail.remove(*self.grid - .get(idx as uint) - .get(col as uint)); /* check same column fields */ - avail.remove(*self.grid - .get(row as uint) - .get(idx as uint)); /* check same row fields */ + /* check same column fields */ + avail.remove(self.grid[idx as uint][col as uint]); + /* check same row fields */ + avail.remove(self.grid[row as uint][idx as uint]); } // check same block fields @@ -164,9 +160,7 @@ impl Sudoku { let col0 = (col / 3u8) * 3u8; for alt_row in range(row0, row0 + 3u8) { for alt_col in range(col0, col0 + 3u8) { - avail.remove(*self.grid - .get(alt_row as uint) - .get(alt_col as uint)); + avail.remove(self.grid[alt_row as uint][alt_col as uint]); } } } diff --git a/src/test/bench/task-perf-alloc-unwind.rs b/src/test/bench/task-perf-alloc-unwind.rs index a86b797544a..bdeee5fb6e0 100644 --- a/src/test/bench/task-perf-alloc-unwind.rs +++ b/src/test/bench/task-perf-alloc-unwind.rs @@ -78,21 +78,22 @@ fn recurse_or_fail(depth: int, st: Option) { let depth = depth - 1; let st = match st { - None => { - State { - unique: box Nil, - vec: vec!(box Nil), - res: r(box Nil) + None => { + State { + unique: box Nil, + vec: vec!(box Nil), + res: r(box Nil) + } } - } - Some(st) => { - State { - unique: box Cons((), box *st.unique), - vec: st.vec.clone().append( - &[box Cons((), st.vec.last().unwrap().clone())]), - res: r(box Cons((), st.res._l.clone())) + Some(st) => { + let mut v = st.vec.clone(); + v.push_all(&[box Cons((), st.vec.last().unwrap().clone())]); + State { + unique: box Cons((), box *st.unique), + vec: v, + res: r(box Cons((), st.res._l.clone())), + } } - } }; recurse_or_fail(depth, Some(st)); diff --git a/src/test/bench/task-perf-jargon-metal-smoke.rs b/src/test/bench/task-perf-jargon-metal-smoke.rs index 17e1ad423f9..9ebdbf0682d 100644 --- a/src/test/bench/task-perf-jargon-metal-smoke.rs +++ b/src/test/bench/task-perf-jargon-metal-smoke.rs @@ -49,7 +49,7 @@ fn main() { }; let (tx, rx) = channel(); - child_generation(from_str::(args.get(1).as_slice()).unwrap(), tx); + child_generation(from_str::(args[1].as_slice()).unwrap(), tx); if rx.recv_opt().is_err() { fail!("it happened when we slumbered"); } diff --git a/src/test/bench/task-perf-spawnalot.rs b/src/test/bench/task-perf-spawnalot.rs index a871ac989f3..533005b1fb3 100644 --- a/src/test/bench/task-perf-spawnalot.rs +++ b/src/test/bench/task-perf-spawnalot.rs @@ -31,7 +31,7 @@ fn main() { } else { args.into_iter().collect() }; - let n = from_str::(args.get(1).as_slice()).unwrap(); + let n = from_str::(args[1].as_slice()).unwrap(); let mut i = 0u; while i < n { task::spawn(proc() f(n) ); i += 1u; } } diff --git a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-bad-len.rs b/src/test/compile-fail-fulldeps/syntax-extension-fourcc-bad-len.rs deleted file mode 100644 index 3ad17618fc0..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-bad-len.rs +++ /dev/null @@ -1,22 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -fn main() { - let val = fourcc!("foo"); //~ ERROR string literal with len != 4 in fourcc! - let val2 = fourcc!("fooba"); //~ ERROR string literal with len != 4 in fourcc! -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-invalid-endian.rs b/src/test/compile-fail-fulldeps/syntax-extension-fourcc-invalid-endian.rs deleted file mode 100644 index 4d425d9a205..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-invalid-endian.rs +++ /dev/null @@ -1,21 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -fn main() { - let val = fourcc!("foo ", bork); //~ ERROR invalid endian directive in fourcc! -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-ascii-str.rs b/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-ascii-str.rs deleted file mode 100644 index 1a6d747c1e8..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-ascii-str.rs +++ /dev/null @@ -1,21 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -fn main() { - let v = fourcc!("fooλ"); //~ ERROR fourcc! literal character out of range 0-255 -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-literal.rs b/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-literal.rs deleted file mode 100644 index 885d8dd1ec3..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-non-literal.rs +++ /dev/null @@ -1,21 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -fn main() { - let val = fourcc!(foo); //~ ERROR non-literal in fourcc! -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-unsupported-literal.rs b/src/test/compile-fail-fulldeps/syntax-extension-fourcc-unsupported-literal.rs deleted file mode 100644 index da1c0070715..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-fourcc-unsupported-literal.rs +++ /dev/null @@ -1,21 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -fn main() { - let val = fourcc!(45f32); //~ ERROR unsupported literal in fourcc! -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-lits.rs b/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-lits.rs deleted file mode 100644 index 191042f5f56..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-lits.rs +++ /dev/null @@ -1,34 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate hexfloat; - -fn main() { - hexfloat!("foo"); - //~^ ERROR invalid hex float literal in hexfloat!: Expected '0' - hexfloat!("0"); - //~^ERROR invalid hex float literal in hexfloat!: Expected 'x' - hexfloat!("0x"); - //~^ERROR invalid hex float literal in hexfloat!: Expected '.' - hexfloat!("0x."); - //~^ERROR invalid hex float literal in hexfloat!: Expected digits before or after decimal point - hexfloat!("0x0.0"); - //~^ERROR invalid hex float literal in hexfloat!: Expected 'p' - hexfloat!("0x0.0p"); - //~^ERROR invalid hex float literal in hexfloat!: Expected exponent digits - hexfloat!("0x0.0p0f"); - //~^ERROR invalid hex float literal in hexfloat!: Expected end of string -} diff --git a/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-types.rs b/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-types.rs deleted file mode 100644 index f0ace43ec9e..00000000000 --- a/src/test/compile-fail-fulldeps/syntax-extension-hexfloat-bad-types.rs +++ /dev/null @@ -1,26 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate hexfloat; - -fn main() { - hexfloat!(foo); - //~^ ERROR non-literal in hexfloat! - hexfloat!(0); - //~^ ERROR unsupported literal in hexfloat! - hexfloat!("0x0.p0", invalid); - //~^ ERROR invalid floating point type in hexfloat! -} diff --git a/src/test/compile-fail/borrowck-assign-comp-idx.rs b/src/test/compile-fail/borrowck-assign-comp-idx.rs index 143ebdaa773..5bc2edba301 100644 --- a/src/test/compile-fail/borrowck-assign-comp-idx.rs +++ b/src/test/compile-fail/borrowck-assign-comp-idx.rs @@ -17,7 +17,7 @@ fn a() { let mut p = vec!(1); // Create an immutable pointer into p's contents: - let q: &int = p.get(0); + let q: &int = &p[0]; *p.get_mut(0) = 5; //~ ERROR cannot borrow diff --git a/src/test/compile-fail/borrowck-loan-vec-content.rs b/src/test/compile-fail/borrowck-loan-vec-content.rs index 393b528869a..31b5c44df66 100644 --- a/src/test/compile-fail/borrowck-loan-vec-content.rs +++ b/src/test/compile-fail/borrowck-loan-vec-content.rs @@ -18,13 +18,13 @@ fn takes_imm_elt(_v: &int, f: ||) { fn has_mut_vec_and_does_not_try_to_change_it() { let mut v = vec!(1, 2, 3); - takes_imm_elt(v.get(0), || {}) + takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { let mut v = vec!(1, 2, 3); takes_imm_elt( - v.get(0), + &v[0], || { //~ ERROR cannot borrow `v` as mutable *v.get_mut(1) = 4; }) diff --git a/src/test/compile-fail/borrowck-overloaded-index-2.rs b/src/test/compile-fail/borrowck-overloaded-index-2.rs index 6d2eae8bc1e..d9d7a43d46c 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-2.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-2.rs @@ -14,7 +14,7 @@ struct MyVec { impl Index for MyVec { fn index(&self, &i: &uint) -> &T { - self.data.get(i) + &self.data[i] } } diff --git a/src/test/compile-fail/deprecated-url.rs b/src/test/compile-fail/deprecated-url.rs deleted file mode 100644 index 9f1c1fdd7c7..00000000000 --- a/src/test/compile-fail/deprecated-url.rs +++ /dev/null @@ -1,20 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-tidy-linelength - -#![deny(deprecated)] - -extern crate url; - -fn main() { - let _ = url::Url::parse("http://example.com"); - //~^ ERROR use of deprecated item: This is being removed. Use rust-url instead. http://servo.github.io/rust-url/ -} diff --git a/src/test/compile-fail/lub-if.rs b/src/test/compile-fail/lub-if.rs index 5440219e55e..6dcf1fdee83 100644 --- a/src/test/compile-fail/lub-if.rs +++ b/src/test/compile-fail/lub-if.rs @@ -16,14 +16,14 @@ pub fn opt_str0<'a>(maybestr: &'a Option) -> &'a str { if maybestr.is_none() { "(none)" } else { - let s: &'a str = maybestr.get_ref().as_slice(); + let s: &'a str = maybestr.as_ref().unwrap().as_slice(); s } } pub fn opt_str1<'a>(maybestr: &'a Option) -> &'a str { if maybestr.is_some() { - let s: &'a str = maybestr.get_ref().as_slice(); + let s: &'a str = maybestr.as_ref().unwrap().as_slice(); s } else { "(none)" @@ -34,14 +34,14 @@ pub fn opt_str2<'a>(maybestr: &'a Option) -> &'static str { if maybestr.is_none() { "(none)" } else { - let s: &'a str = maybestr.get_ref().as_slice(); + let s: &'a str = maybestr.as_ref().unwrap().as_slice(); s //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting } } pub fn opt_str3<'a>(maybestr: &'a Option) -> &'static str { if maybestr.is_some() { - let s: &'a str = maybestr.get_ref().as_slice(); + let s: &'a str = maybestr.as_ref().unwrap().as_slice(); s //~ ERROR cannot infer an appropriate lifetime for automatic coercion due to conflicting } else { "(none)" diff --git a/src/test/compile-fail/moves-based-on-type-access-to-field.rs b/src/test/compile-fail/moves-based-on-type-access-to-field.rs index 85723936997..c9efce0d684 100644 --- a/src/test/compile-fail/moves-based-on-type-access-to-field.rs +++ b/src/test/compile-fail/moves-based-on-type-access-to-field.rs @@ -18,7 +18,7 @@ fn touch(_a: &A) {} fn f20() { let x = vec!("hi".to_string()); consume(x.into_iter().next().unwrap()); - touch(x.get(0)); //~ ERROR use of moved value: `x` + touch(&x[0]); //~ ERROR use of moved value: `x` } fn main() {} diff --git a/src/test/compile-fail/moves-based-on-type-exprs.rs b/src/test/compile-fail/moves-based-on-type-exprs.rs index 330fd9f1ff0..1d6dc504ab4 100644 --- a/src/test/compile-fail/moves-based-on-type-exprs.rs +++ b/src/test/compile-fail/moves-based-on-type-exprs.rs @@ -30,7 +30,7 @@ fn f20() { fn f21() { let x = vec!(1i, 2, 3); - let _y = (*x.get(0), 3i); + let _y = (x[0], 3i); touch(&x); } @@ -96,8 +96,8 @@ fn f110() { fn f120() { let mut x = vec!("hi".to_string(), "ho".to_string()); x.as_mut_slice().swap(0, 1); - touch(x.get(0)); - touch(x.get(1)); + touch(&x[0]); + touch(&x[1]); } fn main() {} diff --git a/src/test/compile-fail/no-capture-arc.rs b/src/test/compile-fail/no-capture-arc.rs index ec218768a98..a07317176e4 100644 --- a/src/test/compile-fail/no-capture-arc.rs +++ b/src/test/compile-fail/no-capture-arc.rs @@ -18,10 +18,10 @@ fn main() { let arc_v = Arc::new(v); task::spawn(proc() { - assert_eq!(*arc_v.get(3), 4); + assert_eq!((*arc_v)[3], 4); }); - assert_eq!(*arc_v.get(2), 3); + assert_eq!((*arc_v)[2], 3); println!("{}", *arc_v); } diff --git a/src/test/compile-fail/no-reuse-move-arc.rs b/src/test/compile-fail/no-reuse-move-arc.rs index b8009031883..9f33f35838e 100644 --- a/src/test/compile-fail/no-reuse-move-arc.rs +++ b/src/test/compile-fail/no-reuse-move-arc.rs @@ -16,10 +16,10 @@ fn main() { let arc_v = Arc::new(v); task::spawn(proc() { - assert_eq!(*arc_v.get(3), 4); + assert_eq!((*arc_v)[3], 4); }); - assert_eq!(*arc_v.get(2), 3); //~ ERROR use of moved value: `arc_v` + assert_eq!((*arc_v)[2], 3); //~ ERROR use of moved value: `arc_v` println!("{}", *arc_v); //~ ERROR use of moved value: `arc_v` } diff --git a/src/test/compile-fail/ufcs-explicit-self-bad.rs b/src/test/compile-fail/ufcs-explicit-self-bad.rs index e5bad7e31b8..b639af61757 100644 --- a/src/test/compile-fail/ufcs-explicit-self-bad.rs +++ b/src/test/compile-fail/ufcs-explicit-self-bad.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::owned::Box; - struct Foo { f: int, } diff --git a/src/test/compile-fail/unresolved-extern-mod-suggestion.rs b/src/test/compile-fail/unresolved-extern-mod-suggestion.rs index 62066eb29d0..33d3deb8733 100644 --- a/src/test/compile-fail/unresolved-extern-mod-suggestion.rs +++ b/src/test/compile-fail/unresolved-extern-mod-suggestion.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -extern crate url; -use url; //~ ERROR unresolved import (maybe you meant `url::*`?) +extern crate core; +use core; //~ ERROR unresolved import (maybe you meant `core::*`?) fn main() {} diff --git a/src/test/compile-fail/writing-to-immutable-vec.rs b/src/test/compile-fail/writing-to-immutable-vec.rs index ab00a8a01e0..4e9f1545f3a 100644 --- a/src/test/compile-fail/writing-to-immutable-vec.rs +++ b/src/test/compile-fail/writing-to-immutable-vec.rs @@ -11,5 +11,5 @@ fn main() { let v: Vec = vec!(1, 2, 3); - *v.get(1) = 4; //~ ERROR cannot assign + v[1] = 4; //~ ERROR cannot borrow immutable local variable `v` as mutable } diff --git a/src/test/run-fail/bug-2470-bounds-check-overflow.rs b/src/test/run-fail/bug-2470-bounds-check-overflow.rs index 0e116bcede5..9123342f09a 100644 --- a/src/test/run-fail/bug-2470-bounds-check-overflow.rs +++ b/src/test/run-fail/bug-2470-bounds-check-overflow.rs @@ -31,5 +31,5 @@ fn main() { idx * mem::size_of::()); // This should fail. - println!("ov1 0x{:x}", *x.get(idx)); + println!("ov1 0x{:x}", x[idx]); } diff --git a/src/test/run-fail/glob-use-std.rs b/src/test/run-fail/glob-use-std.rs index bee60cd1205..bf04789bbc7 100644 --- a/src/test/run-fail/glob-use-std.rs +++ b/src/test/run-fail/glob-use-std.rs @@ -20,7 +20,5 @@ use std::*; fn main() { - String::from_byte(b'a'); // avoid an unused import message - fail!("fail works") } diff --git a/src/test/run-fail/issue-3029.rs b/src/test/run-fail/issue-3029.rs index 80e275019ce..539d2adc7d4 100644 --- a/src/test/run-fail/issue-3029.rs +++ b/src/test/run-fail/issue-3029.rs @@ -18,5 +18,5 @@ fn main() { let mut x = Vec::new(); let y = vec!(3i); fail!("so long"); - x.push_all_move(y); + x.extend(y.into_iter()); } diff --git a/src/test/run-fail/vec-overrun.rs b/src/test/run-fail/vec-overrun.rs index 40ffe15fe86..281523a807e 100644 --- a/src/test/run-fail/vec-overrun.rs +++ b/src/test/run-fail/vec-overrun.rs @@ -14,8 +14,8 @@ fn main() { let v: Vec = vec!(10); let x: uint = 0; - assert_eq!(*v.get(x), 10); + assert_eq!(v[x], 10); // Bounds-check failure. - assert_eq!(*v.get(x + 2), 20); + assert_eq!(v[x + 2], 20); } diff --git a/src/test/run-make/bootstrap-from-c-with-native/lib.rs b/src/test/run-make/bootstrap-from-c-with-native/lib.rs index d211167626d..99dd473344a 100644 --- a/src/test/run-make/bootstrap-from-c-with-native/lib.rs +++ b/src/test/run-make/bootstrap-from-c-with-native/lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="boot#0.1"] +#![crate_name="boot"] #![crate_type="dylib"] extern crate native; diff --git a/src/test/run-make/dep-info-custom/lib.rs b/src/test/run-make/dep-info-custom/lib.rs index 4255b1d934d..14baa8ca55a 100644 --- a/src/test/run-make/dep-info-custom/lib.rs +++ b/src/test/run-make/dep-info-custom/lib.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="foo#0.1"] +#![crate_name="foo"] pub mod foo; pub mod bar; diff --git a/src/test/run-make/libs-through-symlinks/foo.rs b/src/test/run-make/libs-through-symlinks/foo.rs index 6864076d18e..dd818cf8798 100644 --- a/src/test/run-make/libs-through-symlinks/foo.rs +++ b/src/test/run-make/libs-through-symlinks/foo.rs @@ -9,4 +9,4 @@ // except according to those terms. #![crate_type = "rlib"] -#![crate_id = "foo"] +#![crate_name = "foo"] diff --git a/src/test/run-make/lto-syntax-extension/main.rs b/src/test/run-make/lto-syntax-extension/main.rs index ec4fbca48f8..0f6bd10b15d 100644 --- a/src/test/run-make/lto-syntax-extension/main.rs +++ b/src/test/run-make/lto-syntax-extension/main.rs @@ -11,8 +11,9 @@ #![feature(phase)] extern crate lib; -#[phase(plugin)] extern crate fourcc; +extern crate regex; +#[phase(plugin)] extern crate regex_macros; fn main() { - fourcc!("1234"); + regex!("1234"); } diff --git a/src/test/run-make/many-crates-but-no-match/crateA1.rs b/src/test/run-make/many-crates-but-no-match/crateA1.rs index 0c88cf4745a..dbfe920c85b 100644 --- a/src/test/run-make/many-crates-but-no-match/crateA1.rs +++ b/src/test/run-make/many-crates-but-no-match/crateA1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateA"] +#![crate_name="crateA"] // Base crate pub fn func() {} diff --git a/src/test/run-make/many-crates-but-no-match/crateA2.rs b/src/test/run-make/many-crates-but-no-match/crateA2.rs index e3fb50e13d0..857c36aee60 100644 --- a/src/test/run-make/many-crates-but-no-match/crateA2.rs +++ b/src/test/run-make/many-crates-but-no-match/crateA2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateA"] +#![crate_name="crateA"] // Base crate pub fn func() { println!("hello"); } diff --git a/src/test/run-make/many-crates-but-no-match/crateA3.rs b/src/test/run-make/many-crates-but-no-match/crateA3.rs index ad9d458be24..8b8dac5e862 100644 --- a/src/test/run-make/many-crates-but-no-match/crateA3.rs +++ b/src/test/run-make/many-crates-but-no-match/crateA3.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="crateA"] +#![crate_name="crateA"] // Base crate pub fn foo() { println!("world!"); } diff --git a/src/test/run-make/rustdoc-hidden-line/foo.rs b/src/test/run-make/rustdoc-hidden-line/foo.rs index 26546cef0f0..c402da7987d 100644 --- a/src/test/run-make/rustdoc-hidden-line/foo.rs +++ b/src/test/run-make/rustdoc-hidden-line/foo.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id="foo#0.1"] +#![crate_name="foo"] /// The '# ' lines should be removed from the output, but the #[deriving] should be /// retained. diff --git a/src/test/run-make/rustdoc-json/foo.rs b/src/test/run-make/rustdoc-json/foo.rs index dda66f051bc..d57a7164cdb 100644 --- a/src/test/run-make/rustdoc-json/foo.rs +++ b/src/test/run-make/rustdoc-json/foo.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id = "foo#0.1"] +#![crate_name = "foo"] //! Very docs diff --git a/src/test/run-make/rustdoc-smoke/foo.rs b/src/test/run-make/rustdoc-smoke/foo.rs index b783dd39a06..499bcaff4d1 100644 --- a/src/test/run-make/rustdoc-smoke/foo.rs +++ b/src/test/run-make/rustdoc-smoke/foo.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -#![crate_id = "foo#0.1"] +#![crate_name = "foo"] //! Very docs diff --git a/src/test/run-make/unicode-input/multiple_files.rs b/src/test/run-make/unicode-input/multiple_files.rs index 7c6d97dd5a3..2aa4264225c 100644 --- a/src/test/run-make/unicode-input/multiple_files.rs +++ b/src/test/run-make/unicode-input/multiple_files.rs @@ -34,8 +34,8 @@ fn random_char() -> char { fn main() { let args = os::args(); - let rustc = args.get(1).as_slice(); - let tmpdir = Path::new(args.get(2).as_slice()); + let rustc = args[1].as_slice(); + let tmpdir = Path::new(args[2].as_slice()); let main_file = tmpdir.join("unicode_input_multiple_files_main.rs"); { diff --git a/src/test/run-make/unicode-input/span_length.rs b/src/test/run-make/unicode-input/span_length.rs index e213e266548..7b096d7d583 100644 --- a/src/test/run-make/unicode-input/span_length.rs +++ b/src/test/run-make/unicode-input/span_length.rs @@ -33,8 +33,8 @@ fn random_char() -> char { fn main() { let args = os::args(); - let rustc = args.get(1).as_slice(); - let tmpdir = Path::new(args.get(2).as_slice()); + let rustc = args[1].as_slice(); + let tmpdir = Path::new(args[2].as_slice()); let main_file = tmpdir.join("span_main.rs"); for _ in range(0u, 100) { diff --git a/src/test/run-pass-fulldeps/syntax-extension-fourcc.rs b/src/test/run-pass-fulldeps/syntax-extension-fourcc.rs deleted file mode 100644 index b16975fe6ee..00000000000 --- a/src/test/run-pass-fulldeps/syntax-extension-fourcc.rs +++ /dev/null @@ -1,43 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] - -#[phase(plugin)] -extern crate fourcc; - -static static_val: u32 = fourcc!("foo "); -static static_val_be: u32 = fourcc!("foo ", big); -static static_val_le: u32 = fourcc!("foo ", little); -static static_val_target: u32 = fourcc!("foo ", target); - -fn main() { - let val = fourcc!("foo ", big); - assert_eq!(val, 0x666f6f20u32); - assert_eq!(val, fourcc!("foo ")); - - let val = fourcc!("foo ", little); - assert_eq!(val, 0x206f6f66u32); - - let val = fourcc!("foo ", target); - let exp = if cfg!(target_endian = "big") { 0x666f6f20u32 } else { 0x206f6f66u32 }; - assert_eq!(val, exp); - - assert_eq!(static_val_be, 0x666f6f20u32); - assert_eq!(static_val, static_val_be); - assert_eq!(static_val_le, 0x206f6f66u32); - let exp = if cfg!(target_endian = "big") { 0x666f6f20u32 } else { 0x206f6f66u32 }; - assert_eq!(static_val_target, exp); - - assert_eq!(fourcc!("\xC0\xFF\xEE!"), 0xC0FFEE21); -} diff --git a/src/test/run-pass-fulldeps/syntax-extension-hexfloat.rs b/src/test/run-pass-fulldeps/syntax-extension-hexfloat.rs deleted file mode 100644 index 820606179bc..00000000000 --- a/src/test/run-pass-fulldeps/syntax-extension-hexfloat.rs +++ /dev/null @@ -1,29 +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 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -// ignore-stage1 -// ignore-pretty - -#![feature(phase)] -#[phase(plugin)] -extern crate hexfloat; - -pub fn main() { - let a = hexfloat!("0x1.999999999999ap-4"); - assert_eq!(a, 0.1f64); - let b = hexfloat!("-0x1.fffp-4", f32); - assert_eq!(b, -0.12498474_f32); - let c = hexfloat!("0x.12345p5", f64); - let d = hexfloat!("0x0.12345p5", f64); - assert_eq!(c,d); - let f = hexfloat!("0x10.p4", f32); - let g = hexfloat!("0x10.0p4", f32); - assert_eq!(f,g); -} diff --git a/src/test/run-pass/assignability-trait.rs b/src/test/run-pass/assignability-trait.rs index 1ffee6aad76..0d90636ec91 100644 --- a/src/test/run-pass/assignability-trait.rs +++ b/src/test/run-pass/assignability-trait.rs @@ -41,7 +41,7 @@ fn length>(x: T) -> uint { pub fn main() { let x: Vec = vec!(0,1,2,3); // Call a method - x.iterate(|y| { assert!(*x.get(*y as uint) == *y); true }); + x.iterate(|y| { assert!(x[*y as uint] == *y); true }); // Call a parameterized function assert_eq!(length(x.clone()), x.len()); // Call a parameterized function, with type arguments that require diff --git a/src/test/run-pass/bare-fn-implements-fn-mut.rs b/src/test/run-pass/bare-fn-implements-fn-mut.rs index 37c551734de..4962e9d0f22 100644 --- a/src/test/run-pass/bare-fn-implements-fn-mut.rs +++ b/src/test/run-pass/bare-fn-implements-fn-mut.rs @@ -25,8 +25,9 @@ fn call_g>(mut g: G, x: String, y: String) g(x, y) } -fn g(x: String, y: String) -> String { - x.append(y.as_slice()) +fn g(mut x: String, y: String) -> String { + x.push_str(y.as_slice()); + x } fn main() { diff --git a/src/test/run-pass/borrowck-mut-uniq.rs b/src/test/run-pass/borrowck-mut-uniq.rs index 867fdd531e9..e644c49366d 100644 --- a/src/test/run-pass/borrowck-mut-uniq.rs +++ b/src/test/run-pass/borrowck-mut-uniq.rs @@ -23,7 +23,7 @@ fn add_int(x: &mut Ints, v: int) { fn iter_ints(x: &Ints, f: |x: &int| -> bool) -> bool { let l = x.values.len(); - range(0u, l).all(|i| f(x.values.get(i))) + range(0u, l).all(|i| f(&x.values[i])) } pub fn main() { diff --git a/src/test/run-pass/call-closure-from-overloaded-op.rs b/src/test/run-pass/call-closure-from-overloaded-op.rs index bf242316757..432d022c69b 100644 --- a/src/test/run-pass/call-closure-from-overloaded-op.rs +++ b/src/test/run-pass/call-closure-from-overloaded-op.rs @@ -14,5 +14,5 @@ fn foo() -> int { 22 } pub fn main() { let mut x: Vec int> = Vec::new(); x.push(foo); - assert_eq!((*x.get(0))(), 22); + assert_eq!((x[0])(), 22); } diff --git a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs index ad7d818bd3b..646eed5de75 100644 --- a/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs +++ b/src/test/run-pass/coerce-reborrow-imm-vec-rcvr.rs @@ -10,11 +10,11 @@ fn bar(v: &mut [uint]) -> Vec { - Vec::from_slice(v) + v.to_vec() } fn bip(v: &[uint]) -> Vec { - Vec::from_slice(v) + v.to_vec() } pub fn main() { diff --git a/src/test/run-pass/drop-with-type-ascription-1.rs b/src/test/run-pass/drop-with-type-ascription-1.rs index c4ea169cb79..8c0c0afa94b 100644 --- a/src/test/run-pass/drop-with-type-ascription-1.rs +++ b/src/test/run-pass/drop-with-type-ascription-1.rs @@ -11,7 +11,7 @@ fn main() { let foo = "hello".to_string(); let foo: Vec<&str> = foo.as_slice().words().collect(); - let invalid_string = foo.get(0); + let invalid_string = &foo[0]; assert_eq!(*invalid_string, "hello"); } diff --git a/src/test/run-pass/drop-with-type-ascription-2.rs b/src/test/run-pass/drop-with-type-ascription-2.rs index 634b1004e53..f55f47bbc59 100644 --- a/src/test/run-pass/drop-with-type-ascription-2.rs +++ b/src/test/run-pass/drop-with-type-ascription-2.rs @@ -10,8 +10,8 @@ fn main() { let args = vec!("foobie", "asdf::asdf"); - let arr: Vec<&str> = args.get(1).as_slice().split_str("::").collect(); - assert_eq!(*arr.get(0), "asdf"); - assert_eq!(*arr.get(0), "asdf"); + let arr: Vec<&str> = args[1].as_slice().split_str("::").collect(); + assert_eq!(arr[0], "asdf"); + assert_eq!(arr[0], "asdf"); } diff --git a/src/test/run-pass/expr-fn.rs b/src/test/run-pass/expr-fn.rs index fc2912c184f..8172c16abf2 100644 --- a/src/test/run-pass/expr-fn.rs +++ b/src/test/run-pass/expr-fn.rs @@ -17,7 +17,7 @@ fn test_int() { fn test_vec() { fn f() -> Vec { vec!(10, 11) } let vect = f(); - assert_eq!(*vect.get(1), 11); + assert_eq!(vect[1], 11); } fn test_generic() { diff --git a/src/test/run-pass/expr-match-fail.rs b/src/test/run-pass/expr-match-fail.rs index 872701e33ee..1f246581687 100644 --- a/src/test/run-pass/expr-match-fail.rs +++ b/src/test/run-pass/expr-match-fail.rs @@ -16,7 +16,7 @@ fn test_simple() { fn test_box() { let r = match true { true => { vec!(10i) } false => { fail!() } }; - assert_eq!(*r.get(0), 10i); + assert_eq!(r[0], 10i); } pub fn main() { test_simple(); test_box(); } diff --git a/src/test/run-pass/foreach-nested.rs b/src/test/run-pass/foreach-nested.rs index 357d1201a4c..af6ca3c93d5 100644 --- a/src/test/run-pass/foreach-nested.rs +++ b/src/test/run-pass/foreach-nested.rs @@ -17,8 +17,8 @@ pub fn main() { two(|i| { two(|j| { *a.get_mut(p as uint) = 10 * i + j; p += 1; }) }); - assert_eq!(*a.get(0), 0); - assert_eq!(*a.get(1), 1); - assert_eq!(*a.get(2), 10); - assert_eq!(*a.get(3), 11); + assert_eq!(a[0], 0); + assert_eq!(a[1], 1); + assert_eq!(a[2], 10); + assert_eq!(a[3], 11); } diff --git a/src/test/run-pass/hashmap-memory.rs b/src/test/run-pass/hashmap-memory.rs index 8ff89ae2cde..87afd1601f6 100644 --- a/src/test/run-pass/hashmap-memory.rs +++ b/src/test/run-pass/hashmap-memory.rs @@ -52,7 +52,7 @@ mod map_reduce { } let (tx, rx) = channel(); println!("sending find_reducer"); - ctrl.send(find_reducer(Vec::from_slice(key.as_bytes()), tx)); + ctrl.send(find_reducer(key.as_bytes().to_vec(), tx)); println!("receiving"); let c = rx.recv(); println!("{}", c); diff --git a/src/test/run-pass/issue-13304.rs b/src/test/run-pass/issue-13304.rs index c868189197e..047ff74035b 100644 --- a/src/test/run-pass/issue-13304.rs +++ b/src/test/run-pass/issue-13304.rs @@ -29,7 +29,7 @@ fn parent() { let args = args.as_slice(); let mut p = io::process::Command::new(args[0].as_slice()) .arg("child").spawn().unwrap(); - p.stdin.get_mut_ref().write_str("test1\ntest2\ntest3").unwrap(); + p.stdin.as_mut().unwrap().write_str("test1\ntest2\ntest3").unwrap(); let out = p.wait_with_output().unwrap(); assert!(out.status.success()); let s = str::from_utf8(out.output.as_slice()).unwrap(); diff --git a/src/test/run-pass/issue-14021.rs b/src/test/run-pass/issue-14021.rs index f25a1fcdab6..a55cded87e5 100644 --- a/src/test/run-pass/issue-14021.rs +++ b/src/test/run-pass/issue-14021.rs @@ -19,7 +19,7 @@ struct UnitLikeStruct; pub fn main() { let obj = UnitLikeStruct; - let json_str: String = json::Encoder::str_encode(&obj); + let json_str: String = json::encode(&obj); let json_object = json::from_str(json_str.as_slice()); let mut decoder = json::Decoder::new(json_object.unwrap()); diff --git a/src/test/run-pass/issue-14456.rs b/src/test/run-pass/issue-14456.rs index bee4baf68a0..2339e3f6302 100644 --- a/src/test/run-pass/issue-14456.rs +++ b/src/test/run-pass/issue-14456.rs @@ -16,7 +16,7 @@ use std::os; fn main() { let args = os::args(); - if args.len() > 1 && args.get(1).as_slice() == "child" { + if args.len() > 1 && args[1].as_slice() == "child" { return child() } @@ -32,7 +32,7 @@ fn child() { fn test() { let args = os::args(); - let mut p = Command::new(args.get(0).as_slice()).arg("child") + let mut p = Command::new(args[0].as_slice()).arg("child") .stdin(process::Ignored) .stdout(process::Ignored) .stderr(process::Ignored) diff --git a/src/test/run-pass/issue-14940.rs b/src/test/run-pass/issue-14940.rs index e0a63331e97..acadc81df63 100644 --- a/src/test/run-pass/issue-14940.rs +++ b/src/test/run-pass/issue-14940.rs @@ -17,7 +17,7 @@ fn main() { let mut out = stdio::stdout(); out.write(['a' as u8, ..128 * 1024]).unwrap(); } else { - let out = Command::new(args.get(0).as_slice()).arg("child").output(); + let out = Command::new(args[0].as_slice()).arg("child").output(); let out = out.unwrap(); assert!(out.status.success()); } diff --git a/src/test/run-pass/issue-15149.rs b/src/test/run-pass/issue-15149.rs index cc80232691d..1fb17d4d5fa 100644 --- a/src/test/run-pass/issue-15149.rs +++ b/src/test/run-pass/issue-15149.rs @@ -15,8 +15,8 @@ use std::task::TaskBuilder; fn main() { // If we're the child, make sure we were invoked correctly let args = os::args(); - if args.len() > 1 && args.get(1).as_slice() == "child" { - return assert_eq!(args.get(0).as_slice(), "mytest"); + if args.len() > 1 && args[1].as_slice() == "child" { + return assert_eq!(args[0].as_slice(), "mytest"); } test(); diff --git a/src/test/run-pass/issue-15189.rs b/src/test/run-pass/issue-15189.rs index abf8b6dbbea..16212b5f529 100644 --- a/src/test/run-pass/issue-15189.rs +++ b/src/test/run-pass/issue-15189.rs @@ -12,7 +12,7 @@ #![feature(macro_rules)] -macro_rules! third(($e:expr)=>({let x = 2; *$e.get(x)})) +macro_rules! third(($e:expr)=>({let x = 2; $e[x]})) fn main() { let x = vec!(10u,11u,12u,13u); diff --git a/src/test/run-pass/issue-17216.rs b/src/test/run-pass/issue-17216.rs index 538b837d117..e48d7b0756c 100644 --- a/src/test/run-pass/issue-17216.rs +++ b/src/test/run-pass/issue-17216.rs @@ -25,7 +25,7 @@ fn main() { let mut dropped = false; { let leak = Leak { dropped: &mut dropped }; - for ((), leaked) in Some(((),leak)).move_iter() {} + for ((), leaked) in Some(((),leak)).into_iter() {} } assert!(dropped); diff --git a/src/test/run-pass/issue-2383.rs b/src/test/run-pass/issue-2383.rs index 41cf3eaf7e3..9a00868cc12 100644 --- a/src/test/run-pass/issue-2383.rs +++ b/src/test/run-pass/issue-2383.rs @@ -15,5 +15,5 @@ use std::collections::Deque; pub fn main() { let mut q = RingBuf::new(); - q.push_back(10i); + q.push(10i); } diff --git a/src/test/run-pass/issue-2804-2.rs b/src/test/run-pass/issue-2804-2.rs index 32fefac52eb..952ea1e9d3d 100644 --- a/src/test/run-pass/issue-2804-2.rs +++ b/src/test/run-pass/issue-2804-2.rs @@ -17,7 +17,7 @@ extern crate collections; use std::collections::HashMap; fn add_interfaces(managed_ip: String, device: HashMap) { - println!("{}, {}", managed_ip, device.get(&"interfaces".to_string())); + println!("{}, {}", managed_ip, device["interfaces".to_string()]); } pub fn main() {} diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index 7228f12c030..62104f2dc23 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -57,9 +57,9 @@ fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, fn add_interfaces(store: int, managed_ip: String, device: HashMap) -> Vec<(String, object)> { - match device.get(&"interfaces".to_string()) + match device["interfaces".to_string()] { - &json::List(ref interfaces) => + json::List(ref interfaces) => { interfaces.iter().map(|interface| { add_interface(store, managed_ip.clone(), (*interface).clone()) @@ -68,7 +68,7 @@ fn add_interfaces(store: int, managed_ip: String, device: HashMap { println!("Expected list for {} interfaces, found {}", managed_ip, - device.get(&"interfaces".to_string())); + device["interfaces".to_string()]); Vec::new() } } diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 01bfdddd285..1964001cebd 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -69,7 +69,7 @@ fn read_board_grid(mut input: rdr) row.push(square_from_char(*c as char)) } grid.push(row); - let width = grid.get(0).len(); + let width = grid[0].len(); for row in grid.iter() { assert!(row.len() == width) } grid } diff --git a/src/test/run-pass/issue-2989.rs b/src/test/run-pass/issue-2989.rs index c88f8b42d42..d625f6bcf92 100644 --- a/src/test/run-pass/issue-2989.rs +++ b/src/test/run-pass/issue-2989.rs @@ -24,7 +24,7 @@ fn to_bools(bitv: Storage) -> Vec { Vec::from_fn(8, |i| { let w = i / 64; let b = i % 64; - let x = 1u64 & (*bitv.storage.get(w) >> b); + let x = 1u64 & (bitv.storage[w] >> b); x == 1u64 }) } @@ -36,7 +36,7 @@ pub fn main() { let bools2 = to_bools(Storage{storage: vec!(0b01100100)}); for i in range(0u, 8) { - println!("{} => {} vs {}", i, *bools.get(i), *bools2.get(i)); + println!("{} => {} vs {}", i, bools[i], bools2[i]); } assert_eq!(bools, bools2); diff --git a/src/test/run-pass/issue-3609.rs b/src/test/run-pass/issue-3609.rs index 61dd2ea2a05..2e0159af984 100644 --- a/src/test/run-pass/issue-3609.rs +++ b/src/test/run-pass/issue-3609.rs @@ -23,7 +23,7 @@ fn foo(name: String, samples_chan: Sender) { let mut samples_chan = samples_chan; let callback: SamplesFn = proc(buffer) { for i in range(0u, buffer.len()) { - println!("{}: {}", i, *buffer.get(i)) + println!("{}: {}", i, buffer[i]) } }; samples_chan.send(GetSamples(name.clone(), callback)); diff --git a/src/test/run-pass/issue-5521.rs b/src/test/run-pass/issue-5521.rs index 8bf87e7f483..be75c723042 100644 --- a/src/test/run-pass/issue-5521.rs +++ b/src/test/run-pass/issue-5521.rs @@ -17,7 +17,7 @@ fn bar(a: foo::map) { if false { fail!(); } else { - let _b = a.get(&2); + let _b = &(*a)[2]; } } diff --git a/src/test/run-pass/issue-7660.rs b/src/test/run-pass/issue-7660.rs index 9a4b3bf0e54..8a953cea904 100644 --- a/src/test/run-pass/issue-7660.rs +++ b/src/test/run-pass/issue-7660.rs @@ -21,6 +21,6 @@ pub fn main() { let mut m: HashMap = HashMap::new(); m.insert(1, A(0, 0)); - let A(ref _a, ref _b) = *m.get(&1); - let (a, b) = match *m.get(&1) { A(ref _a, ref _b) => (_a, _b) }; + let A(ref _a, ref _b) = m[1]; + let (a, b) = match m[1] { A(ref _a, ref _b) => (_a, _b) }; } diff --git a/src/test/run-pass/issue-9259.rs b/src/test/run-pass/issue-9259.rs index 2818b824969..0fe520e59d6 100644 --- a/src/test/run-pass/issue-9259.rs +++ b/src/test/run-pass/issue-9259.rs @@ -19,5 +19,5 @@ pub fn main() { a: &["test".to_string()], b: Some(b), }; - assert_eq!(a.b.get_ref()[0].as_slice(), "foo"); + assert_eq!(a.b.as_ref().unwrap()[0].as_slice(), "foo"); } diff --git a/src/test/run-pass/match-vec-rvalue.rs b/src/test/run-pass/match-vec-rvalue.rs index 70c3b386a8a..0f058086add 100644 --- a/src/test/run-pass/match-vec-rvalue.rs +++ b/src/test/run-pass/match-vec-rvalue.rs @@ -15,9 +15,9 @@ pub fn main() { match vec!(1i, 2i, 3i) { x => { assert_eq!(x.len(), 3); - assert_eq!(*x.get(0), 1); - assert_eq!(*x.get(1), 2); - assert_eq!(*x.get(2), 3); + assert_eq!(x[0], 1); + assert_eq!(x[1], 2); + assert_eq!(x[2], 3); } } } diff --git a/src/test/run-pass/monad.rs b/src/test/run-pass/monad.rs index 783dc32426a..4f9e573ccff 100644 --- a/src/test/run-pass/monad.rs +++ b/src/test/run-pass/monad.rs @@ -18,7 +18,7 @@ impl vec_monad for Vec { fn bind(&self, f: |&A| -> Vec ) -> Vec { let mut r = Vec::new(); for elt in self.iter() { - r.push_all_move(f(elt)); + r.extend(f(elt).into_iter()); } r } diff --git a/src/test/run-pass/move-arg-2-unique.rs b/src/test/run-pass/move-arg-2-unique.rs index ac90f8f6ecf..29fd070fc19 100644 --- a/src/test/run-pass/move-arg-2-unique.rs +++ b/src/test/run-pass/move-arg-2-unique.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn test(foo: Box> ) { assert!((*foo.get(0) == 10)); } +fn test(foo: Box> ) { assert!(((*foo)[0] == 10)); } pub fn main() { let x = box vec!(10); diff --git a/src/test/run-pass/move-arg-2.rs b/src/test/run-pass/move-arg-2.rs index 840a3c2a6ee..0f3d0baecbe 100644 --- a/src/test/run-pass/move-arg-2.rs +++ b/src/test/run-pass/move-arg-2.rs @@ -9,7 +9,7 @@ // except according to those terms. -fn test(foo: Box>) { assert!((*foo.get(0) == 10)); } +fn test(foo: Box>) { assert!(((*foo)[0] == 10)); } pub fn main() { let x = box vec!(10); diff --git a/src/test/run-pass/newtype-polymorphic.rs b/src/test/run-pass/newtype-polymorphic.rs index 437f35d182b..a21bb489d16 100644 --- a/src/test/run-pass/newtype-polymorphic.rs +++ b/src/test/run-pass/newtype-polymorphic.rs @@ -26,8 +26,8 @@ pub fn main() { let mv = myvec(vec!(1i, 2, 3)); let mv_clone = mv.clone(); let mv_clone = myvec_deref(mv_clone); - assert_eq!(*mv_clone.get(1), 2); + assert_eq!(mv_clone[1], 2); assert_eq!(myvec_elt(mv.clone()), 1); let myvec(v) = mv; - assert_eq!(*v.get(2), 3); + assert_eq!(v[2], 3); } diff --git a/src/test/run-pass/nullable-pointer-iotareduction.rs b/src/test/run-pass/nullable-pointer-iotareduction.rs index 0c66b139e7c..9d7130ecb8c 100644 --- a/src/test/run-pass/nullable-pointer-iotareduction.rs +++ b/src/test/run-pass/nullable-pointer-iotareduction.rs @@ -44,7 +44,7 @@ macro_rules! check_option { assert!(option::None::<$T>.is_none()); let e = $e; let s_ = option::Some::<$T>(e); - let $v = s_.get_ref(); + let $v = s_.as_ref().unwrap(); $chk }} } diff --git a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs index 9ca6598b47c..ab3d39e2733 100644 --- a/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs +++ b/src/test/run-pass/objects-owned-object-borrowed-method-headerless.rs @@ -35,6 +35,6 @@ pub fn main() { ); for i in range(0u, foos.len()) { - assert_eq!(i, foos.get(i).foo()); + assert_eq!(i, foos[i].foo()); } } diff --git a/src/test/run-pass/overloaded-deref.rs b/src/test/run-pass/overloaded-deref.rs index 96cf3102a42..cdd56f64d27 100644 --- a/src/test/run-pass/overloaded-deref.rs +++ b/src/test/run-pass/overloaded-deref.rs @@ -46,7 +46,7 @@ pub fn main() { let v = Rc::new(RefCell::new(vec!(1i, 2, 3))); *(*(*v).borrow_mut()).get_mut(0) = 3; *(*(*v).borrow_mut()).get_mut(1) += 3; - assert_eq!((*(*(*v).borrow()).get(0), - *(*(*v).borrow()).get(1), - *(*(*v).borrow()).get(2)), (3, 5, 3)); + assert_eq!(((*(*v).borrow())[0], + (*(*v).borrow())[1], + (*(*v).borrow())[2]), (3, 5, 3)); } diff --git a/src/test/run-pass/process-spawn-with-unicode-params.rs b/src/test/run-pass/process-spawn-with-unicode-params.rs index f04bc62bf7f..9716d79f4c8 100644 --- a/src/test/run-pass/process-spawn-with-unicode-params.rs +++ b/src/test/run-pass/process-spawn-with-unicode-params.rs @@ -53,12 +53,14 @@ fn main() { // make a separate directory for the child drop(fs::mkdir(&cwd, io::USER_RWX).is_ok()); assert!(fs::copy(&my_path, &child_path).is_ok()); + let mut my_env = my_env; + my_env.push(env); // run child let p = Command::new(&child_path) .arg(arg) .cwd(&cwd) - .env_set_all(my_env.append_one(env).as_slice()) + .env_set_all(my_env.as_slice()) .spawn().unwrap().wait_with_output().unwrap(); // display the output @@ -74,7 +76,7 @@ fn main() { assert!(my_cwd.ends_with_path(&Path::new(child_dir))); // check arguments - assert_eq!(my_args.get(1).as_slice(), arg); + assert_eq!(my_args[1].as_slice(), arg); // check environment variable assert!(my_env.contains(&env)); diff --git a/src/test/run-pass/pure-sum.rs b/src/test/run-pass/pure-sum.rs index 60eb3f9debd..3b2897cf3a6 100644 --- a/src/test/run-pass/pure-sum.rs +++ b/src/test/run-pass/pure-sum.rs @@ -15,7 +15,7 @@ fn sums_to(v: Vec , sum: int) -> bool { let mut i = 0u; let mut sum0 = 0; while i < v.len() { - sum0 += *v.get(i); + sum0 += v[i]; i += 1u; } return sum0 == sum; @@ -25,7 +25,7 @@ fn sums_to_using_uniq(v: Vec , sum: int) -> bool { let mut i = 0u; let mut sum0 = box 0; while i < v.len() { - *sum0 += *v.get(i); + *sum0 += v[i]; i += 1u; } return *sum0 == sum; @@ -35,7 +35,7 @@ fn sums_to_using_rec(v: Vec , sum: int) -> bool { let mut i = 0u; let mut sum0 = F {f: 0}; while i < v.len() { - sum0.f += *v.get(i); + sum0.f += v[i]; i += 1u; } return sum0.f == sum; @@ -47,7 +47,7 @@ fn sums_to_using_uniq_rec(v: Vec , sum: int) -> bool { let mut i = 0u; let mut sum0 = F {f: box 0}; while i < v.len() { - *sum0.f += *v.get(i); + *sum0.f += v[i]; i += 1u; } return *sum0.f == sum; diff --git a/src/test/run-pass/regions-dependent-addr-of.rs b/src/test/run-pass/regions-dependent-addr-of.rs index 252c0b5578a..68a451b62ac 100644 --- a/src/test/run-pass/regions-dependent-addr-of.rs +++ b/src/test/run-pass/regions-dependent-addr-of.rs @@ -42,7 +42,7 @@ fn get_v2(a: &A, i: uint) -> &int { fn get_v3(a: &A, i: uint) -> &int { let foo = &a.value; - foo.v3.get(i) + &foo.v3[i] } fn get_v4(a: &A, _i: uint) -> &int { @@ -97,7 +97,7 @@ pub fn main() { assert_eq!(*p, a.value.v2[1]); let p = get_v3(&a, 1); - assert_eq!(*p, *a.value.v3.get(1)); + assert_eq!(*p, a.value.v3[1]); let p = get_v4(&a, 1); assert_eq!(*p, a.value.v4.f); diff --git a/src/test/run-pass/regions-infer-borrow-scope-view.rs b/src/test/run-pass/regions-infer-borrow-scope-view.rs index c4e0e3bb4fc..ce9edb5678a 100644 --- a/src/test/run-pass/regions-infer-borrow-scope-view.rs +++ b/src/test/run-pass/regions-infer-borrow-scope-view.rs @@ -15,5 +15,5 @@ pub fn main() { let v = vec!(1i, 2, 3); let x = view(v.as_slice()); let y = view(x.as_slice()); - assert!((*v.get(0) == x[0]) && (*v.get(0) == y[0])); + assert!((v[0] == x[0]) && (v[0] == y[0])); } diff --git a/src/test/run-pass/running-with-no-runtime.rs b/src/test/run-pass/running-with-no-runtime.rs index 3f559df4b7e..d0762d1f3d8 100644 --- a/src/test/run-pass/running-with-no-runtime.rs +++ b/src/test/run-pass/running-with-no-runtime.rs @@ -41,7 +41,7 @@ fn start(argc: int, argv: *const *const u8) -> int { fn main() { let args = os::args(); - let me = args.get(0).as_slice(); + let me = args[0].as_slice(); let x: &[u8] = &[1u8]; pass(Command::new(me).arg(x).output().unwrap()); diff --git a/src/test/run-pass/size-and-align.rs b/src/test/run-pass/size-and-align.rs index 1078359dc14..65928fd7bf3 100644 --- a/src/test/run-pass/size-and-align.rs +++ b/src/test/run-pass/size-and-align.rs @@ -11,7 +11,7 @@ enum clam { a(T, int), b, } fn uhoh(v: Vec> ) { - match *v.get(1) { + match v[1] { a::(ref _t, ref u) => { println!("incorrect"); println!("{}", u); diff --git a/src/test/run-pass/static-impl.rs b/src/test/run-pass/static-impl.rs index d0dacc2ff7a..ff6e0e4bbc9 100644 --- a/src/test/run-pass/static-impl.rs +++ b/src/test/run-pass/static-impl.rs @@ -63,9 +63,9 @@ pub fn main() { assert_eq!((vec!(1i)).length_().str(), "1".to_string()); let vect = vec!(3i, 4).map_(|a| *a + 4); - assert_eq!(*vect.get(0), 7); + assert_eq!(vect[0], 7); let vect = (vec!(3i, 4)).map_::(|a| *a as uint + 4u); - assert_eq!(*vect.get(0), 7u); + assert_eq!(vect[0], 7u); let mut x = 0u; 10u.multi(|_n| x += 2u ); assert_eq!(x, 20u); diff --git a/src/test/run-pass/swap-2.rs b/src/test/run-pass/swap-2.rs index 7789fe5abb4..4eb9274551f 100644 --- a/src/test/run-pass/swap-2.rs +++ b/src/test/run-pass/swap-2.rs @@ -13,10 +13,10 @@ use std::mem::swap; pub fn main() { let mut a: Vec = vec!(0, 1, 2, 3, 4, 5, 6); a.as_mut_slice().swap(2, 4); - assert_eq!(*a.get(2), 4); - assert_eq!(*a.get(4), 2); + assert_eq!(a[2], 4); + assert_eq!(a[4], 2); let mut n = 42; swap(&mut n, a.get_mut(0)); - assert_eq!(*a.get(0), 42); + assert_eq!(a[0], 42); assert_eq!(n, 0); } diff --git a/src/test/run-pass/task-comm-16.rs b/src/test/run-pass/task-comm-16.rs index d45e7a20c3b..a6cc8c463e8 100644 --- a/src/test/run-pass/task-comm-16.rs +++ b/src/test/run-pass/task-comm-16.rs @@ -29,9 +29,9 @@ fn test_vec() { let v0: Vec = vec!(0, 1, 2); tx.send(v0); let v1 = rx.recv(); - assert_eq!(*v1.get(0), 0); - assert_eq!(*v1.get(1), 1); - assert_eq!(*v1.get(2), 2); + assert_eq!(v1[0], 0); + assert_eq!(v1[1], 1); + assert_eq!(v1[2], 2); } fn test_str() { diff --git a/src/test/run-pass/trait-with-bounds-default.rs b/src/test/run-pass/trait-with-bounds-default.rs index ec9f666eb19..6b2c5093c83 100644 --- a/src/test/run-pass/trait-with-bounds-default.rs +++ b/src/test/run-pass/trait-with-bounds-default.rs @@ -32,7 +32,7 @@ impl Getter for int { } impl Getter for Option { - fn do_get(&self) -> T { self.get_ref().clone() } + fn do_get(&self) -> T { self.as_ref().unwrap().clone() } } diff --git a/src/test/run-pass/type-use-i1-versus-i8.rs b/src/test/run-pass/type-use-i1-versus-i8.rs index 97bf9e9e8e2..99c68ac8100 100644 --- a/src/test/run-pass/type-use-i1-versus-i8.rs +++ b/src/test/run-pass/type-use-i1-versus-i8.rs @@ -8,12 +8,12 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::mem; +use std::ptr; pub fn main() { unsafe { let mut x: bool = false; // this line breaks it - mem::overwrite(&mut x, false); + ptr::write(&mut x, false); } } diff --git a/src/test/run-pass/ufcs-explicit-self.rs b/src/test/run-pass/ufcs-explicit-self.rs index 9ffb56c516a..b96820eee14 100644 --- a/src/test/run-pass/ufcs-explicit-self.rs +++ b/src/test/run-pass/ufcs-explicit-self.rs @@ -8,8 +8,6 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use std::owned::Box; - struct Foo { f: int, } diff --git a/src/test/run-pass/unique-autoderef-index.rs b/src/test/run-pass/unique-autoderef-index.rs index ec328d65ac8..f9bd5114e7d 100644 --- a/src/test/run-pass/unique-autoderef-index.rs +++ b/src/test/run-pass/unique-autoderef-index.rs @@ -11,5 +11,5 @@ pub fn main() { let i = box vec!(100i); - assert_eq!(*i.get(0), 100i); + assert_eq!((*i)[0], 100i); } diff --git a/src/test/run-pass/unique-in-vec-copy.rs b/src/test/run-pass/unique-in-vec-copy.rs index fda3c53bdf4..33a28ddb2fc 100644 --- a/src/test/run-pass/unique-in-vec-copy.rs +++ b/src/test/run-pass/unique-in-vec-copy.rs @@ -13,12 +13,12 @@ pub fn main() { let mut a = vec!(box 10i); let b = a.clone(); - assert_eq!(**a.get(0), 10); - assert_eq!(**b.get(0), 10); + assert_eq!(*a[0], 10); + assert_eq!(*b[0], 10); // This should only modify the value in a, not b **a.get_mut(0) = 20; - assert_eq!(**a.get(0), 20); - assert_eq!(**b.get(0), 10); + assert_eq!(*a[0], 20); + assert_eq!(*b[0], 10); } diff --git a/src/test/run-pass/unique-in-vec.rs b/src/test/run-pass/unique-in-vec.rs index b7029ab38bc..0f8527664b9 100644 --- a/src/test/run-pass/unique-in-vec.rs +++ b/src/test/run-pass/unique-in-vec.rs @@ -10,5 +10,5 @@ pub fn main() { let vect = vec!(box 100i); - assert!(*vect.get(0) == box 100); + assert!(vect[0] == box 100); } diff --git a/src/test/run-pass/vec-concat.rs b/src/test/run-pass/vec-concat.rs index a0400a9dcc5..02a791e7975 100644 --- a/src/test/run-pass/vec-concat.rs +++ b/src/test/run-pass/vec-concat.rs @@ -13,9 +13,10 @@ use std::vec; pub fn main() { let a: Vec = vec!(1, 2, 3, 4, 5); let b: Vec = vec!(6, 7, 8, 9, 0); - let v: Vec = a.append(b.as_slice()); - println!("{}", *v.get(9)); - assert_eq!(*v.get(0), 1); - assert_eq!(*v.get(7), 8); - assert_eq!(*v.get(9), 0); + let mut v: Vec = a; + v.push_all(b.as_slice()); + println!("{}", v[9]); + assert_eq!(v[0], 1); + assert_eq!(v[7], 8); + assert_eq!(v[9], 0); } diff --git a/src/test/run-pass/vec-growth.rs b/src/test/run-pass/vec-growth.rs index 08f9b3c176b..d5e5f94d261 100644 --- a/src/test/run-pass/vec-growth.rs +++ b/src/test/run-pass/vec-growth.rs @@ -15,9 +15,9 @@ pub fn main() { v.push(3i); v.push(4i); v.push(5i); - assert_eq!(*v.get(0), 1); - assert_eq!(*v.get(1), 2); - assert_eq!(*v.get(2), 3); - assert_eq!(*v.get(3), 4); - assert_eq!(*v.get(4), 5); + 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); } diff --git a/src/test/run-pass/vec-late-init.rs b/src/test/run-pass/vec-late-init.rs index 118095b6c9a..dec0b3eaa78 100644 --- a/src/test/run-pass/vec-late-init.rs +++ b/src/test/run-pass/vec-late-init.rs @@ -12,5 +12,5 @@ pub fn main() { let mut later: Vec ; if true { later = vec!(1); } else { later = vec!(2); } - println!("{}", *later.get(0)); + println!("{}", later[0]); } diff --git a/src/test/run-pass/vec.rs b/src/test/run-pass/vec.rs index c5031a6e51f..5e19868de1d 100644 --- a/src/test/run-pass/vec.rs +++ b/src/test/run-pass/vec.rs @@ -11,12 +11,12 @@ pub fn main() { let v: Vec = vec!(10, 20); - assert_eq!(*v.get(0), 10); - assert_eq!(*v.get(1), 20); + assert_eq!(v[0], 10); + assert_eq!(v[1], 20); let mut x: uint = 0; - assert_eq!(*v.get(x), 10); - assert_eq!(*v.get(x + 1), 20); + assert_eq!(v[x], 10); + assert_eq!(v[x + 1], 20); x = x + 1; - assert_eq!(*v.get(x), 20); - assert_eq!(*v.get(x - 1), 10); + assert_eq!(v[x], 20); + assert_eq!(v[x - 1], 10); } diff --git a/src/test/run-pass/vector-sort-failure-safe.rs b/src/test/run-pass/vector-sort-failure-safe.rs index 46f760722a6..10c37651a86 100644 --- a/src/test/run-pass/vector-sort-failure-safe.rs +++ b/src/test/run-pass/vector-sort-failure-safe.rs @@ -9,7 +9,7 @@ // except according to those terms. use std::task; -use std::sync::atomics::{AtomicUint, INIT_ATOMIC_UINT, Relaxed}; +use std::sync::atomic::{AtomicUint, INIT_ATOMIC_UINT, Relaxed}; use std::rand::{task_rng, Rng, Rand}; const REPEATS: uint = 5;