Move replace and swap to std::mem. Get rid of std::util

Also move Void to std::any, move drop to std::mem and reexport in
prelude.
This commit is contained in:
Edward Wang 2014-02-01 04:35:36 +08:00
parent 4f16e519f1
commit e9ff91e9be
59 changed files with 245 additions and 300 deletions

View File

@ -40,7 +40,6 @@ use std::rc::Rc;
use std::rt::global_heap;
use std::unstable::intrinsics::{TyDesc, get_tydesc};
use std::unstable::intrinsics;
use std::util;
use std::vec;
// The way arena uses arrays is really deeply awful. The arrays are
@ -404,7 +403,7 @@ impl TypedArenaChunk {
}
// Destroy the next chunk.
let next_opt = util::replace(&mut self.next, None);
let next_opt = mem::replace(&mut self.next, None);
match next_opt {
None => {}
Some(mut next) => {

View File

@ -23,8 +23,8 @@
// the reverse direction.
use std::cast;
use std::mem::{replace, swap};
use std::ptr;
use std::util;
use std::iter::Rev;
use std::iter;
@ -102,7 +102,7 @@ impl<T> Rawlink<T> {
/// Return the `Rawlink` and replace with `Rawlink::none()`
fn take(&mut self) -> Rawlink<T> {
util::replace(self, Rawlink::none())
replace(self, Rawlink::none())
}
}
@ -161,7 +161,7 @@ impl<T> DList<T> {
Some(ref mut head) => {
new_head.prev = Rawlink::none();
head.prev = Rawlink::some(new_head);
util::swap(head, &mut new_head);
swap(head, &mut new_head);
head.next = Some(new_head);
}
}
@ -319,7 +319,7 @@ impl<T> DList<T> {
/// O(1)
#[inline]
pub fn prepend(&mut self, mut other: DList<T>) {
util::swap(self, &mut other);
swap(self, &mut other);
self.append(other);
}

View File

@ -13,8 +13,7 @@
#[allow(missing_doc)];
use std::clone::Clone;
use std::mem::{move_val_init, init};
use std::util::{replace, swap};
use std::mem::{move_val_init, init, replace, swap};
use std::vec;
/// A priority queue implemented with a binary heap

View File

@ -16,7 +16,7 @@
#[allow(missing_doc)];
use std::iter::{Enumerate, FilterMap, Rev};
use std::util::replace;
use std::mem::replace;
use std::vec;
#[allow(missing_doc)]

View File

@ -12,9 +12,9 @@
//! trees. The only requirement for the types is that the key implements
//! `TotalOrd`.
use std::util::{swap, replace};
use std::iter::{Peekable};
use std::cmp::Ordering;
use std::mem::{replace, swap};
use std::ptr;
use serialize::{Encodable, Decodable, Encoder, Decoder};

View File

@ -2592,7 +2592,8 @@ mod bigint_tests {
#[cfg(test)]
mod bench {
use super::*;
use std::{iter, util};
use std::iter;
use std::mem::replace;
use std::num::{FromPrimitive, Zero, One};
use extra::test::BenchHarness;
@ -2609,7 +2610,7 @@ mod bench {
let mut f1: BigUint = One::one();
for _ in range(0, n) {
let f2 = f0 + f1;
f0 = util::replace(&mut f1, f2);
f0 = replace(&mut f1, f2);
}
f0
}

View File

@ -13,8 +13,8 @@
use std::cmp;
use std::hashmap;
use std::io;
use std::mem;
use std::num;
use std::util;
// NB: this can probably be rewritten in terms of num::Num
// to be less f64-specific.
@ -178,7 +178,7 @@ impl<'a> Stats for &'a [f64] {
for i in range(0, partials.len()) {
let mut y = partials[i];
if num::abs(x) < num::abs(y) {
util::swap(&mut x, &mut y);
mem::swap(&mut x, &mut y);
}
// Rounded `x+y` is stored in `hi` with round-off stored in
// `lo`. Together `hi+lo` are exactly equal to `x+y`.

View File

@ -16,10 +16,10 @@
//! loop if no other one is provided (and M:N scheduling is desired).
use std::cast;
use std::mem::replace;
use std::rt::rtio::{EventLoop, IoFactory, RemoteCallback, PausableIdleCallback,
Callback};
use std::unstable::sync::Exclusive;
use std::util;
/// This is the only exported function from this module.
pub fn event_loop() -> ~EventLoop {
@ -50,7 +50,7 @@ impl BasicLoop {
/// Process everything in the work queue (continually)
fn work(&mut self) {
while self.work.len() > 0 {
for work in util::replace(&mut self.work, ~[]).move_iter() {
for work in replace(&mut self.work, ~[]).move_iter() {
work();
}
}
@ -60,7 +60,7 @@ impl BasicLoop {
let messages = unsafe {
self.messages.with(|messages| {
if messages.len() > 0 {
Some(util::replace(messages, ~[]))
Some(replace(messages, ~[]))
} else {
None
}

View File

@ -174,6 +174,7 @@
// NB this does *not* include globs, please keep it that way.
#[feature(macro_rules)];
use std::mem::replace;
use std::os;
use std::rt::crate_map;
use std::rt::rtio;
@ -182,7 +183,6 @@ use std::rt;
use std::sync::atomics::{SeqCst, AtomicUint, INIT_ATOMIC_UINT};
use std::sync::deque;
use std::task::TaskOpts;
use std::util;
use std::vec;
use std::sync::arc::UnsafeArc;
@ -457,10 +457,10 @@ impl SchedPool {
}
// Now that everyone's gone, tell everything to shut down.
for mut handle in util::replace(&mut self.handles, ~[]).move_iter() {
for mut handle in replace(&mut self.handles, ~[]).move_iter() {
handle.send(Shutdown);
}
for thread in util::replace(&mut self.threads, ~[]).move_iter() {
for thread in replace(&mut self.threads, ~[]).move_iter() {
thread.join();
}
}

View File

@ -13,7 +13,7 @@
//! which are available for use externally when compiled as a library.
use std::hashmap::{HashSet, HashMap};
use std::util;
use std::mem::replace;
use metadata::csearch;
use middle::resolve;
@ -679,7 +679,7 @@ impl<'a> Visitor<()> for PrivacyVisitor<'a> {
return;
}
let orig_curitem = util::replace(&mut self.curitem, item.id);
let orig_curitem = replace(&mut self.curitem, item.id);
visit::walk_item(self, item, ());
self.curitem = orig_curitem;
}
@ -861,7 +861,7 @@ impl Visitor<()> for SanePrivacyVisitor {
self.check_sane_privacy(item);
}
let orig_in_fn = util::replace(&mut self.in_fn, match item.node {
let orig_in_fn = replace(&mut self.in_fn, match item.node {
ast::ItemMod(..) => false, // modules turn privacy back on
_ => self.in_fn, // otherwise we inherit
});
@ -872,7 +872,7 @@ impl Visitor<()> for SanePrivacyVisitor {
fn visit_fn(&mut self, fk: &visit::FnKind, fd: &ast::FnDecl,
b: &ast::Block, s: Span, n: ast::NodeId, _: ()) {
// This catches both functions and methods
let orig_in_fn = util::replace(&mut self.in_fn, true);
let orig_in_fn = replace(&mut self.in_fn, true);
visit::walk_fn(self, fk, fd, b, s, n, ());
self.in_fn = orig_in_fn;
}

View File

@ -31,7 +31,7 @@ use syntax::visit::Visitor;
use std::cell::{Cell, RefCell};
use std::uint;
use std::hashmap::{HashMap, HashSet};
use std::util;
use std::mem::replace;
// Definition mapping
pub type DefMap = @RefCell<HashMap<NodeId,Def>>;
@ -4067,7 +4067,7 @@ impl Resolver {
new_trait_refs.push(def_id_of_def(*def));
}
}
original_trait_refs = Some(util::replace(
original_trait_refs = Some(replace(
&mut this.current_trait_refs,
Some(new_trait_refs)));
}

View File

@ -115,8 +115,8 @@ use util::ppaux::{UserString, Repr};
use std::cell::{Cell, RefCell};
use std::hashmap::HashMap;
use std::mem::replace;
use std::result;
use std::util::replace;
use std::vec;
use syntax::abi::AbiSet;
use syntax::ast::{Provided, Required};

View File

@ -8,9 +8,9 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std;
use clean::*;
use std::iter::Extendable;
use std::mem::{replace, swap};
pub trait DocFolder {
fn fold_item(&mut self, item: Item) -> Option<Item> {
@ -19,7 +19,6 @@ pub trait DocFolder {
/// don't override!
fn fold_item_recur(&mut self, item: Item) -> Option<Item> {
use std::util::swap;
let Item { attrs, name, source, visibility, id, inner } = item;
let inner = inner;
let c = |x| self.fold_item(x);
@ -92,7 +91,7 @@ pub trait DocFolder {
}
fn fold_crate(&mut self, mut c: Crate) -> Crate {
c.module = match std::util::replace(&mut c.module, None) {
c.module = match replace(&mut c.module, None) {
Some(module) => self.fold_item(module), None => None
};
return c;

View File

@ -9,10 +9,10 @@
// except according to those terms.
use std::libc::c_int;
use std::mem::replace;
use std::rt::local::Local;
use std::rt::rtio::RtioTimer;
use std::rt::task::{BlockedTask, Task};
use std::util;
use homing::{HomeHandle, HomingIO};
use super::{UvHandle, ForbidUnwind, ForbidSwitch};
@ -76,7 +76,7 @@ impl RtioTimer for TimerWatcher {
let missile = self.fire_homing_missile();
self.id += 1;
self.stop();
let _missile = match util::replace(&mut self.action, None) {
let _missile = match replace(&mut self.action, None) {
None => missile, // no need to do a homing dance
Some(action) => {
drop(missile); // un-home ourself
@ -108,7 +108,7 @@ impl RtioTimer for TimerWatcher {
self.id += 1;
self.stop();
self.start(msecs, 0);
util::replace(&mut self.action, Some(SendOnce(chan)))
replace(&mut self.action, Some(SendOnce(chan)))
};
return port;
@ -124,7 +124,7 @@ impl RtioTimer for TimerWatcher {
self.id += 1;
self.stop();
self.start(msecs, msecs);
util::replace(&mut self.action, Some(SendMany(chan, self.id)))
replace(&mut self.action, Some(SendMany(chan, self.id)))
};
return port;

View File

@ -26,7 +26,9 @@ use result::{Result, Ok, Err};
use to_str::ToStr;
use unstable::intrinsics::TypeId;
use unstable::intrinsics;
use util::Void;
/// A type with no inhabitants
pub enum Void { }
///////////////////////////////////////////////////////////////////////////////
// Any trait

View File

@ -257,7 +257,6 @@ macro_rules! test (
use super::*;
use super::super::*;
use task;
use util;
fn f() $b

View File

@ -477,6 +477,7 @@ will look like `"\\{"`.
*/
use any;
use cast;
use char::Char;
use container::Container;
@ -489,7 +490,6 @@ use repr;
use result::{Ok, Err};
use str::StrSlice;
use str;
use util;
use vec::ImmutableVector;
use vec;
@ -524,8 +524,8 @@ pub struct Formatter<'a> {
/// compile time it is ensured that the function and the value have the correct
/// types, and then this struct is used to canonicalize arguments to one type.
pub struct Argument<'a> {
priv formatter: extern "Rust" fn(&util::Void, &mut Formatter) -> Result,
priv value: &'a util::Void,
priv formatter: extern "Rust" fn(&any::Void, &mut Formatter) -> Result,
priv value: &'a any::Void,
}
impl<'a> Arguments<'a> {
@ -794,11 +794,11 @@ impl<'a> Formatter<'a> {
rt::CountImplied => { None }
rt::CountIsParam(i) => {
let v = self.args[i].value;
unsafe { Some(*(v as *util::Void as *uint)) }
unsafe { Some(*(v as *any::Void as *uint)) }
}
rt::CountIsNextParam => {
let v = self.curarg.next().unwrap().value;
unsafe { Some(*(v as *util::Void as *uint)) }
unsafe { Some(*(v as *any::Void as *uint)) }
}
}
}

View File

@ -60,11 +60,11 @@ use hash::Hash;
use iter;
use iter::{Iterator, FromIterator, Extendable};
use iter::{FilterMap, Chain, Repeat, Zip};
use mem::replace;
use num;
use option::{None, Option, Some};
use rand::Rng;
use rand;
use util::replace;
use vec::{ImmutableVector, MutableVector, OwnedVector, Items, MutItems};
use vec_ng;
use vec_ng::Vec;

View File

@ -659,7 +659,6 @@ mod test {
use io::fs::{File, rmdir, mkdir, readdir, rmdir_recursive,
mkdir_recursive, copy, unlink, stat, symlink, link,
readlink, chmod, lstat, change_file_times};
use util;
use path::Path;
use io;
use ops::Drop;

View File

@ -32,6 +32,7 @@ use fmt;
use io::{Reader, Writer, IoResult, IoError, OtherIoError,
standard_error, EndOfFile, LineBufferedWriter};
use libc;
use mem::replace;
use option::{Option, Some, None};
use prelude::drop;
use result::{Ok, Err};
@ -39,7 +40,6 @@ use rt::local::Local;
use rt::rtio::{DontClose, IoFactory, LocalIo, RtioFileStream, RtioTTY};
use rt::task::Task;
use str::StrSlice;
use util;
use vec::ImmutableVector;
// And so begins the tale of acquiring a uv handle to a stdio stream on all
@ -132,7 +132,7 @@ fn reset_helper(w: ~Writer,
/// Note that this does not need to be called for all new tasks; the default
/// output handle is to the process's stdout stream.
pub fn set_stdout(stdout: ~Writer) -> Option<~Writer> {
reset_helper(stdout, |t, w| util::replace(&mut t.stdout, Some(w)))
reset_helper(stdout, |t, w| replace(&mut t.stdout, Some(w)))
}
/// Resets the task-local stderr handle to the specified writer
@ -144,7 +144,7 @@ pub fn set_stdout(stdout: ~Writer) -> Option<~Writer> {
/// Note that this does not need to be called for all new tasks; the default
/// output handle is to the process's stderr stream.
pub fn set_stderr(stderr: ~Writer) -> Option<~Writer> {
reset_helper(stderr, |t, w| util::replace(&mut t.stderr, Some(w)))
reset_helper(stderr, |t, w| replace(&mut t.stderr, Some(w)))
}
// Helper to access the local task's stdout handle
@ -183,7 +183,7 @@ fn with_task_stdout(f: |&mut Writer| -> IoResult<()> ) {
// temporarily take the task, swap the handles, put the task in TLS,
// and only then drop the previous handle.
let mut t = Local::borrow(None::<Task>);
let prev = util::replace(&mut t.get().stdout, my_stdout);
let prev = replace(&mut t.get().stdout, my_stdout);
drop(t);
drop(prev);
ret

View File

@ -71,7 +71,7 @@ use ops::{Add, Mul, Sub};
use cmp::{Eq, Ord};
use clone::Clone;
use uint;
use util;
use mem;
/// Conversion from an `Iterator`
pub trait FromIterator<A> {
@ -701,7 +701,7 @@ impl<'a, A, T: DoubleEndedIterator<&'a mut A>> MutableDoubleEndedIterator for T
fn reverse_(&mut self) {
loop {
match (self.next(), self.next_back()) {
(Some(x), Some(y)) => util::swap(x, y),
(Some(x), Some(y)) => mem::swap(x, y),
_ => break
}
}

View File

@ -178,7 +178,6 @@ pub mod cast;
pub mod fmt;
pub mod cleanup;
pub mod logging;
pub mod util;
pub mod mem;

View File

@ -45,7 +45,7 @@ use option::{None, Option, Some};
use vec::{ImmutableVector, MutableVector, OwnedVector};
use iter::{Iterator};
use rt::task::{Task, LocalStorage};
use util::replace;
use mem::replace;
/**
* Indexes a task-local data slot. This pointer is used for comparison to
@ -149,7 +149,7 @@ pub fn pop<T: 'static>(key: Key<T>) -> Option<T> {
fail!("TLS value cannot be removed because it is currently \
borrowed as {}", loan.describe());
}
// Move the data out of the `entry` slot via util::replace.
// Move the data out of the `entry` slot via prelude::replace.
// This is guaranteed to succeed because we already matched
// on `Some` above.
let data = match replace(entry, None) {

View File

@ -99,13 +99,13 @@ use fmt;
use io::LineBufferedWriter;
use io;
use io::Writer;
use mem::replace;
use ops::Drop;
use option::{Some, None, Option};
use prelude::drop;
use result::{Ok, Err};
use rt::local::Local;
use rt::task::Task;
use util;
/// Debug log level
pub static DEBUG: u32 = 4;
@ -173,7 +173,7 @@ pub fn log(level: u32, args: &fmt::Arguments) {
logger.get_mut_ref().log(level, args);
let mut task = Local::borrow(None::<Task>);
let prev = util::replace(&mut task.get().logger, logger);
let prev = replace(&mut task.get().logger, logger);
drop(task);
drop(prev);
}
@ -182,5 +182,5 @@ pub fn log(level: u32, args: &fmt::Arguments) {
/// logger.
pub fn set_logger(logger: ~Logger) -> Option<~Logger> {
let mut task = Local::borrow(None::<Task>);
util::replace(&mut task.get().logger, Some(logger))
replace(&mut task.get().logger, Some(logger))
}

View File

@ -15,6 +15,8 @@
#[allow(missing_doc)]; // FIXME
use cast;
use ptr;
use unstable::intrinsics;
use unstable::intrinsics::{bswap16, bswap32, bswap64};
@ -126,9 +128,45 @@ pub unsafe fn move_val_init<T>(dst: &mut T, src: T) {
#[cfg(target_endian = "big")] #[inline] pub fn from_be64(x: i64) -> i64 { x }
/**
* Swap the values at two mutable locations of the same type, without
* deinitialising or copying either one.
*/
#[inline]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninit();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `tmp`
// because it's no longer relevant.
cast::forget(t);
}
}
/**
* Replace the value at a mutable location with a new one, returning the old
* value, without deinitialising or copying either one.
*/
#[inline]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
#[inline]
pub fn drop<T>(_x: T) { }
#[cfg(test)]
mod tests {
use mem::*;
use option::{Some,None};
#[test]
fn size_of_basic() {
@ -207,4 +245,86 @@ mod tests {
assert_eq!(pref_align_of_val(&1u16), 2u);
assert_eq!(pref_align_of_val(&1u32), 4u);
}
#[test]
fn test_swap() {
let mut x = 31337;
let mut y = 42;
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);
}
#[test]
fn test_replace() {
let mut x = Some(~"test");
let y = replace(&mut x, None);
assert!(x.is_none());
assert!(y.is_some());
}
}
/// Completely miscellaneous language-construct benchmarks.
#[cfg(test)]
mod bench {
use extra::test::BenchHarness;
use option::{Some,None};
// Static/dynamic method dispatch
struct Struct {
field: int
}
trait Trait {
fn method(&self) -> int;
}
impl Trait for Struct {
fn method(&self) -> int {
self.field
}
}
#[bench]
fn trait_vtable_method_call(bh: &mut BenchHarness) {
let s = Struct { field: 10 };
let t = &s as &Trait;
bh.iter(|| {
t.method();
});
}
#[bench]
fn trait_static_method_call(bh: &mut BenchHarness) {
let s = Struct { field: 10 };
bh.iter(|| {
s.method();
});
}
// Overhead of various match forms
#[bench]
fn match_option_some(bh: &mut BenchHarness) {
let x = Some(10);
bh.iter(|| {
let _q = match x {
Some(y) => y,
None => 11
};
});
}
#[bench]
fn match_vec_pattern(bh: &mut BenchHarness) {
let x = [1,2,3,4,5,6];
bh.iter(|| {
let _q = match x {
[1,2,3,..] => 10,
_ => 11
};
});
}
}

View File

@ -45,9 +45,9 @@ use default::Default;
use fmt;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use kinds::Send;
use mem;
use str::OwnedStr;
use to_str::ToStr;
use util;
use vec;
/// The option type
@ -285,7 +285,7 @@ impl<T> Option<T> {
/// Take the value out of the option, leaving a `None` in its place.
#[inline]
pub fn take(&mut self) -> Option<T> {
util::replace(self, None)
mem::replace(self, None)
}
/// Filters an optional value using a given function.

View File

@ -40,6 +40,7 @@ pub use result::{Result, Ok, Err};
// Reexported functions
pub use from_str::from_str;
pub use iter::range;
pub use mem::drop;
// Reexported types and traits
@ -85,7 +86,3 @@ pub use task::spawn;
// Reexported statics
#[cfg(not(test))]
pub use gc::GC;
/// Disposes of a value.
#[inline]
pub fn drop<T>(_x: T) { }

View File

@ -18,7 +18,6 @@ use iter::{range, Iterator};
use mem;
use option::{Option, Some, None};
use unstable::intrinsics;
use util::swap;
#[cfg(not(test))] use cmp::{Eq, Ord};
@ -152,7 +151,7 @@ pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
*/
#[inline]
pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
swap(cast::transmute(dest), &mut src); // cannot overlap
mem::swap(cast::transmute(dest), &mut src); // cannot overlap
src
}

View File

@ -636,8 +636,8 @@ fn test_repr() {
use str;
use str::Str;
use io::stdio::println;
use util::swap;
use char::is_alphabetic;
use mem::swap;
fn exact_test<T>(t: &T, e:&str) {
let mut m = io::MemWriter::new();

View File

@ -72,7 +72,7 @@ mod imp {
#[cfg(not(test))] use str;
use unstable::finally::Finally;
use unstable::mutex::{Mutex, MUTEX_INIT};
use util;
use mem;
#[cfg(not(test))] use vec;
static mut global_args_ptr: uint = 0;
@ -93,7 +93,7 @@ mod imp {
pub fn take() -> Option<~[~str]> {
with_lock(|| unsafe {
let ptr = get_global_ptr();
let val = util::replace(&mut *ptr, None);
let val = mem::replace(&mut *ptr, None);
val.as_ref().map(|s: &~~[~str]| (**s).clone())
})
}

View File

@ -14,10 +14,10 @@
use cast;
use iter::Iterator;
use mem;
use option::{Some, None};
use ptr::RawPtr;
use unstable::sync::Exclusive;
use util;
use vec::OwnedVector;
type Queue = Exclusive<~[proc()]>;
@ -60,7 +60,7 @@ pub fn run() {
QUEUE = 0 as *mut Queue;
let mut vec = None;
state.with(|arr| {
vec = Some(util::replace(arr, ~[]));
vec = Some(mem::replace(arr, ~[]));
});
vec.take_unwrap()
};

View File

@ -60,6 +60,7 @@ use c_str::CString;
use cast;
use fmt;
use kinds::Send;
use mem;
use option::{Some, None, Option};
use prelude::drop;
use ptr::RawPtr;
@ -69,7 +70,6 @@ use rt::task::Task;
use str::Str;
use task::TaskResult;
use unstable::intrinsics;
use util;
use uw = self::libunwind;
@ -470,7 +470,7 @@ fn begin_unwind_inner(msg: ~Any, file: &'static str, line: uint) -> ! {
n, msg_s, file, line);
task = Local::take();
match util::replace(&mut task.stderr, Some(stderr)) {
match mem::replace(&mut task.stderr, Some(stderr)) {
Some(prev) => {
Local::put(task);
drop(prev);

View File

@ -15,7 +15,6 @@ use container::{Container, Map, Mutable, MutableMap};
use iter::{Extendable, FromIterator, Iterator};
use mem;
use uint;
use util::replace;
use mem::init;
use vec;
use ptr::RawPtr;
@ -429,7 +428,7 @@ fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
}
External(stored_key, ref mut stored_value) if stored_key == key => {
// swap in the new value and return the old.
return Some(replace(stored_value, value));
return Some(mem::replace(stored_value, value));
}
_ => {}
}
@ -437,7 +436,7 @@ fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
// conflict, an external node with differing keys: we have to
// split the node, so we need the old value by value; hence we
// have to move out of `child`.
match replace(child, Nothing) {
match mem::replace(child, Nothing) {
External(stored_key, stored_value) => {
let mut new = ~TrieNode::new();
insert(&mut new.count,
@ -456,7 +455,7 @@ fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
idx: uint) -> Option<T> {
let (ret, this) = match *child {
External(stored, _) if stored == key => {
match replace(child, Nothing) {
match mem::replace(child, Nothing) {
External(_, value) => (Some(value), true),
_ => fail!()
}

View File

@ -1,160 +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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Miscellaneous helpers for common patterns
use cast;
use mem;
use ptr;
/// The identity function.
#[inline]
pub fn id<T>(x: T) -> T { x }
/**
* Swap the values at two mutable locations of the same type, without
* deinitialising or copying either one.
*/
#[inline]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = mem::uninit();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping_memory(&mut t, &*x, 1);
ptr::copy_nonoverlapping_memory(x, &*y, 1);
ptr::copy_nonoverlapping_memory(y, &t, 1);
// y and t now point to the same thing, but we need to completely forget `tmp`
// because it's no longer relevant.
cast::forget(t);
}
}
/**
* Replace the value at a mutable location with a new one, returning the old
* value, without deinitialising or copying either one.
*/
#[inline]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// A type with no inhabitants
pub enum Void { }
impl Void {
/// A utility function for ignoring this uninhabited type
pub fn uninhabited(self) -> ! {
match self {
// Nothing to match on
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use prelude::*;
#[test]
fn identity_crisis() {
// Writing a test for the identity function. How did it come to this?
let x = ~[(5, false)];
//FIXME #3387 assert!(x.eq(id(x.clone())));
let y = x.clone();
assert!(x.eq(&id(y)));
}
#[test]
fn test_swap() {
let mut x = 31337;
let mut y = 42;
swap(&mut x, &mut y);
assert_eq!(x, 42);
assert_eq!(y, 31337);
}
#[test]
fn test_replace() {
let mut x = Some(~"test");
let y = replace(&mut x, None);
assert!(x.is_none());
assert!(y.is_some());
}
}
/// Completely miscellaneous language-construct benchmarks.
#[cfg(test)]
mod bench {
use extra::test::BenchHarness;
use option::{Some,None};
// Static/dynamic method dispatch
struct Struct {
field: int
}
trait Trait {
fn method(&self) -> int;
}
impl Trait for Struct {
fn method(&self) -> int {
self.field
}
}
#[bench]
fn trait_vtable_method_call(bh: &mut BenchHarness) {
let s = Struct { field: 10 };
let t = &s as &Trait;
bh.iter(|| {
t.method();
});
}
#[bench]
fn trait_static_method_call(bh: &mut BenchHarness) {
let s = Struct { field: 10 };
bh.iter(|| {
s.method();
});
}
// Overhead of various match forms
#[bench]
fn match_option_some(bh: &mut BenchHarness) {
let x = Some(10);
bh.iter(|| {
let _q = match x {
Some(y) => y,
None => 11
};
});
}
#[bench]
fn match_vec_pattern(bh: &mut BenchHarness) {
let x = [1,2,3,4,5,6];
bh.iter(|| {
let _q = match x {
[1,2,3,..] => 10,
_ => 11
};
});
}
}

View File

@ -121,7 +121,6 @@ use kinds::marker;
use uint;
use unstable::finally::Finally;
use unstable::raw::{Repr, Slice, Vec};
use util;
/**
* Creates and initializes an owned vector.
@ -1799,7 +1798,7 @@ impl<T:Eq> OwnedEqVector<T> for ~[T] {
if *p_r != *p_wm1 {
if r != w {
let p_w = ptr::mut_offset(p_wm1, 1);
util::swap(&mut *p_r, &mut *p_w);
mem::swap(&mut *p_r, &mut *p_w);
}
w += 1;
}
@ -1994,7 +1993,7 @@ fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
}
}
util::swap(&mut buf_dat, &mut buf_tmp);
mem::swap(&mut buf_dat, &mut buf_tmp);
width *= 2;
}
@ -2374,7 +2373,7 @@ impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
#[inline]
fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
util::swap(a, b);
mem::swap(a, b);
}
cmp::min(self.len(), end-start)
}
@ -2757,14 +2756,14 @@ impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
match self.v.iter().position(|x| (self.pred)(x)) {
None => {
self.finished = true;
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
let len = tmp.len();
let (head, tail) = tmp.mut_split_at(len);
self.v = tail;
Some(head)
}
Some(idx) => {
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.mut_split_at(idx);
self.v = tail.mut_slice_from(1);
Some(head)
@ -2792,11 +2791,11 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
match self.v.iter().rposition(|x| (self.pred)(x)) {
None => {
self.finished = true;
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
Some(tmp)
}
Some(idx) => {
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.mut_split_at(idx);
self.v = head;
Some(tail.mut_slice_from(1))
@ -2820,7 +2819,7 @@ impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
None
} else {
let sz = cmp::min(self.v.len(), self.chunk_size);
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
let (head, tail) = tmp.mut_split_at(sz);
self.v = tail;
Some(head)
@ -2847,7 +2846,7 @@ impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
} else {
let remainder = self.v.len() % self.chunk_size;
let sz = if remainder != 0 { remainder } else { self.chunk_size };
let tmp = util::replace(&mut self.v, &mut []);
let tmp = mem::replace(&mut self.v, &mut []);
let tmp_len = tmp.len();
let (head, tail) = tmp.mut_split_at(tmp_len - sz);
self.v = head;

View File

@ -26,7 +26,7 @@
#[allow(missing_doc)];
use std::util::replace;
use std::mem::replace;
/// A type encapsulating the result of a computation which may not be complete
pub struct Future<A> {

View File

@ -20,10 +20,10 @@
use std::cast;
use std::comm;
use std::kinds::marker;
use std::mem::replace;
use std::sync::arc::UnsafeArc;
use std::sync::atomics;
use std::unstable::finally::Finally;
use std::util;
use arc::MutexArc;
@ -290,7 +290,7 @@ impl<'a> Condvar<'a> {
// To avoid :broadcast_heavy, we make a new waitqueue,
// swap it out with the old one, and broadcast on the
// old one outside of the little-lock.
queue = Some(util::replace(&mut state.blocked[condvar_id],
queue = Some(replace(&mut state.blocked[condvar_id],
WaitQueue::new()));
} else {
out_of_bounds = Some(state.blocked.len());

View File

@ -18,8 +18,8 @@ use parse::token::{str_to_ident};
use std::cell::{Cell, RefCell};
use std::char;
use std::mem::replace;
use std::num::from_str_radix;
use std::util;
pub use ext::tt::transcribe::{TtReader, new_tt_reader};
@ -112,7 +112,7 @@ impl Reader for StringReader {
let ret_val = {
let mut peek_tok = self.peek_tok.borrow_mut();
TokenAndSpan {
tok: util::replace(peek_tok.get(), token::UNDERSCORE),
tok: replace(peek_tok.get(), token::UNDERSCORE),
sp: self.peek_span.get(),
}
};

View File

@ -76,7 +76,7 @@ impl ParserObsoleteMethods for Parser {
let (kind_str, desc) = match kind {
ObsoleteSwap => (
"swap",
"use std::util::{swap, replace} instead"
"use std::mem::{swap, replace} instead"
),
ObsoleteUnsafeBlock => (
"non-standalone unsafe block",

View File

@ -82,7 +82,7 @@ use opt_vec::OptVec;
use std::cell::Cell;
use std::hashmap::HashSet;
use std::kinds::marker;
use std::util;
use std::mem::replace;
use std::vec;
#[allow(non_camel_case_types)]
@ -735,7 +735,7 @@ impl Parser {
let next = if self.buffer_start == self.buffer_end {
self.reader.next_token()
} else {
// Avoid token copies with `util::replace`.
// Avoid token copies with `replace`.
let buffer_start = self.buffer_start as uint;
let next_index = (buffer_start + 1) & 3 as uint;
self.buffer_start = next_index as int;
@ -744,7 +744,7 @@ impl Parser {
tok: token::UNDERSCORE,
sp: self.span,
};
util::replace(&mut self.buffer[buffer_start], placeholder)
replace(&mut self.buffer[buffer_start], placeholder)
};
self.span = next.sp;
self.token = next.tok;
@ -753,7 +753,7 @@ impl Parser {
// Advance the parser by one token and return the bumped token.
pub fn bump_and_get(&mut self) -> token::Token {
let old_token = util::replace(&mut self.token, token::UNDERSCORE);
let old_token = replace(&mut self.token, token::UNDERSCORE);
self.bump();
old_token
}

View File

@ -7,8 +7,8 @@
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
use std::vec;
use std::util;
/// A vector type optimized for cases where the size is almost always 0 or 1
pub enum SmallVector<T> {
@ -54,9 +54,9 @@ impl<T> SmallVector<T> {
match *self {
Zero => *self = One(v),
One(..) => {
let one = util::replace(self, Zero);
let one = mem::replace(self, Zero);
match one {
One(v1) => util::replace(self, Many(~[v1, v])),
One(v1) => mem::replace(self, Many(~[v1, v])),
_ => unreachable!()
};
}
@ -101,7 +101,7 @@ impl<T> Iterator<T> for MoveItems<T> {
ZeroIterator => None,
OneIterator(..) => {
let mut replacement = ZeroIterator;
util::swap(self, &mut replacement);
mem::swap(self, &mut replacement);
match replacement {
OneIterator(v) => Some(v),
_ => unreachable!()

View File

@ -10,7 +10,8 @@
//! Parameterized string expansion
use std::{char, vec, util};
use std::{char, vec};
use std::mem::replace;
use std::num::strconv::{SignNone,SignNeg,SignAll,int_to_str_bytes_common};
#[deriving(Eq)]
@ -525,14 +526,14 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result<~[u8],~str> {
}
FormatHex => {
if flags.alternate {
let s_ = util::replace(&mut s, ~['0' as u8, 'x' as u8]);
let s_ = replace(&mut s, ~['0' as u8, 'x' as u8]);
s.push_all_move(s_);
}
}
FormatHEX => {
s = s.into_ascii().to_upper().into_bytes();
if flags.alternate {
let s_ = util::replace(&mut s, ~['0' as u8, 'X' as u8]);
let s_ = replace(&mut s, ~['0' as u8, 'X' as u8]);
s.push_all_move(s_);
}
}

View File

@ -15,11 +15,11 @@
extern mod extra;
use extra::time::precise_time_s;
use std::mem::swap;
use std::os;
use std::rand::Rng;
use std::rand;
use std::str;
use std::util;
use std::vec;
use std::io::File;
@ -125,7 +125,7 @@ fn vec_push_all() {
v.push_all(rv);
}
else {
util::swap(&mut v, &mut rv);
swap(&mut v, &mut rv);
v.push_all(rv);
}
}

View File

@ -18,12 +18,12 @@ extern mod extra;
use std::cmp::Ord;
use std::comm;
use std::hashmap::HashMap;
use std::mem::replace;
use std::option;
use std::os;
use std::io;
use std::str;
use std::task;
use std::util;
use std::vec;
fn f64_cmp(x: f64, y: f64) -> Ordering {
@ -161,7 +161,7 @@ fn main() {
let mut from_child = ~[];
let to_child = sizes.iter().zip(streams.mut_iter()).map(|(sz, stream_ref)| {
let sz = *sz;
let stream = util::replace(stream_ref, None);
let stream = replace(stream_ref, None);
let (from_child_, to_parent_) = stream.unwrap();
from_child.push(from_child_);

View File

@ -24,7 +24,7 @@ struct Iterate<'a, T> {
impl<'a, T> Iterator<T> for Iterate<'a, T> {
fn next(&mut self) -> Option<T> {
let mut res = (self.f)(&self.next);
std::util::swap(&mut res, &mut self.next);
std::mem::swap(&mut res, &mut self.next);
Some(res)
}
}

View File

@ -13,8 +13,6 @@
//
// Example from src/middle/borrowck/doc.rs
use std::util::swap;
fn foo(t0: & &mut int) {
let t1 = t0;
let p: &int = &**t0;

View File

@ -13,8 +13,6 @@
//
// Example from src/middle/borrowck/doc.rs
use std::util::swap;
fn foo<'a>(mut t0: &'a mut int,
mut t1: &'a mut int) {
let p: &mut int = &mut *t0; // Claims `*t0`

View File

@ -13,8 +13,6 @@
//
// Example from src/middle/borrowck/doc.rs
use std::util::swap;
fn foo(t0: &mut int) {
let p: &int = &*t0; // Freezes `*t0`
let t1 = t0; //~ ERROR cannot move out of `t0`

View File

@ -13,8 +13,6 @@
//
// Example from src/middle/borrowck/doc.rs
use std::util::swap;
fn foo<'a>(mut t0: &'a mut int,
mut t1: &'a mut int) {
let p: &int = &*t0; // Freezes `*t0`

View File

@ -13,7 +13,7 @@
//
// Example from src/middle/borrowck/doc.rs
use std::util::swap;
use std::mem::swap;
fn foo<'a>(mut t0: &'a mut int,
mut t1: &'a mut int) {

View File

@ -14,8 +14,8 @@
use cal = bar::c::cc;
use std::util::*; // shouldn't get errors for not using
// everything imported
use std::mem::*; // shouldn't get errors for not using
// everything imported
// Should get errors for both 'Some' and 'None'
use std::option::{Some, None}; //~ ERROR unused import
@ -61,8 +61,9 @@ mod bar {
fn main() {
cal(foo::Point{x:3, y:9});
let a = 3;
id(a);
let mut a = 3;
let mut b = 4;
swap(&mut a, &mut b);
test::C.b();
let _a = from_elem(0, 0);
}

View File

@ -8,16 +8,16 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::util;
use std::mem::swap;
struct Ints {sum: ~int, values: ~[int]}
fn add_int(x: &mut Ints, v: int) {
*x.sum += v;
let mut values = ~[];
util::swap(&mut values, &mut x.values);
swap(&mut values, &mut x.values);
values.push(v);
util::swap(&mut values, &mut x.values);
swap(&mut values, &mut x.values);
}
fn iter_ints(x: &Ints, f: |x: &int| -> bool) -> bool {

View File

@ -11,11 +11,11 @@
#[feature(globs)];
pub fn main() {
use std::util::replace;
use std::mem::replace;
let mut x = 5;
replace(&mut x, 6);
{
use std::util::*;
use std::mem::*;
let mut y = 6;
swap(&mut x, &mut y);
}

View File

@ -17,8 +17,8 @@ pub mod pipes {
use super::Task;
use std::cast::{forget, transmute};
use std::cast;
use std::mem::{replace, swap};
use std::task;
use std::util;
pub struct Stuff<T> {
state: state,
@ -111,7 +111,7 @@ pub mod pipes {
match old_state {
empty | blocked => { task::deschedule(); }
full => {
let payload = util::replace(&mut p.payload, None);
let payload = replace(&mut p.payload, None);
return Some(payload.unwrap())
}
terminated => {
@ -167,7 +167,7 @@ pub mod pipes {
if self.p != None {
let self_p: &mut Option<*packet<T>> =
cast::transmute(&self.p);
let p = util::replace(self_p, None);
let p = replace(self_p, None);
sender_terminate(p.unwrap())
}
}
@ -176,7 +176,7 @@ pub mod pipes {
impl<T:Send> send_packet<T> {
pub fn unwrap(&mut self) -> *packet<T> {
util::replace(&mut self.p, None).unwrap()
replace(&mut self.p, None).unwrap()
}
}
@ -197,7 +197,7 @@ pub mod pipes {
if self.p != None {
let self_p: &mut Option<*packet<T>> =
cast::transmute(&self.p);
let p = util::replace(self_p, None);
let p = replace(self_p, None);
receiver_terminate(p.unwrap())
}
}
@ -206,7 +206,7 @@ pub mod pipes {
impl<T:Send> recv_packet<T> {
pub fn unwrap(&mut self) -> *packet<T> {
util::replace(&mut self.p, None).unwrap()
replace(&mut self.p, None).unwrap()
}
}

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::util;
use std::mem::swap;
pub fn main() {
let mut x = 4;
@ -26,6 +26,6 @@ pub fn main() {
}
}
let mut y = 4;
util::swap(&mut y, &mut x);
swap(&mut y, &mut x);
}
}

View File

@ -8,10 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::util;
use std::mem::swap;
pub fn main() {
let mut x = 3; let mut y = 7;
util::swap(&mut x, &mut y);
swap(&mut x, &mut y);
assert!((x == 7)); assert!((y == 3));
}

View File

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::util;
use std::mem::swap;
pub fn main() {
let mut a: ~[int] = ~[0, 1, 2, 3, 4, 5, 6];
@ -16,7 +16,7 @@ pub fn main() {
assert_eq!(a[2], 4);
assert_eq!(a[4], 2);
let mut n = 42;
util::swap(&mut n, &mut a[0]);
swap(&mut n, &mut a[0]);
assert_eq!(a[0], 42);
assert_eq!(n, 0);
}

View File

@ -8,12 +8,12 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::util;
use std::mem::swap;
pub fn main() {
let mut i = ~100;
let mut j = ~200;
util::swap(&mut i, &mut j);
swap(&mut i, &mut j);
assert_eq!(i, ~200);
assert_eq!(j, ~100);
}

View File

@ -11,7 +11,7 @@
#[feature(managed_boxes)];
use std::cell::Cell;
use std::util;
use std::mem::swap;
// Just a grab bag of stuff that you wouldn't want to actually write.
@ -59,7 +59,7 @@ fn notsure() {
let mut _y = (_x = 0) == (_x = 0);
let mut _z = (_x = 0) < (_x = 0);
let _a = (_x += 0) == (_x = 0);
let _b = util::swap(&mut _y, &mut _z) == util::swap(&mut _y, &mut _z);
let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}
fn canttouchthis() -> uint {