Miscellaneous helpers for common patterns.

Struct NonCopyable

pub struct NonCopyable {
    i: (),
}

A non-copyable dummy type.

Function NonCopyable

fn NonCopyable() -> NonCopyable

Function id

fn id<T>(x: T) -> T

The identity function.

Function ignore

fn ignore<T>(_x: T)

Ignores a value.

Function replace

fn replace<T>(dest: &mut T, src: T) -> T

Replace the value at a mutable location with a new one, returning the old value, without deinitialising or copying either one.

Function swap

fn swap<T>(x: &mut T, y: &mut T)

Swap the values at two mutable locations of the same type, without deinitialising or copying either one.

Function unreachable

fn unreachable() -> !

A utility function for indicating unreachable code. It will fail if executed. This is occasionally useful to put after loops that never terminate normally, but instead directly return from a function.

Example

fn choose_weighted_item(v: &[Item]) -> Item {
    assert v.is_not_empty();
    let mut so_far = 0u;
    for v.each |item| {
        so_far += item.weight;
        if so_far > 100 {
            return item;
        }
    }
    // The above loop always returns, so we must hint to the
    // type checker that it isn't possible to get down here
    util::unreachable();
}

Function with

fn with<T: Copy, R>(ptr: &mut T, new_value: T, op: &fn() -> R) -> R

Sets *ptr to new_value, invokes op(), and then restores the original value of *ptr.