提交 51b901e1 编写于 作者: B bors

auto merge of #16241 : P1start/rust/doc-fixes, r=alexcrichton

For crates `alloc`–`collections`. This is mostly just updating a few function/method descriptions to use the indicative style. 

cc #4361; I’ve sort of assumed that the third-person indicative style has been decided on, but I could update this to use the imperative style if that’s preferred, or even update this to remove all function-style-related changes. (I think that standardising on one thing, even if it’s not the ‘best’ option, is still better than having no standard at all.) The indicative style seems to be more common in the Rust standard library at the moment, especially in the newer modules (e.g. `collections::vec`), more popular in the discussion about it, and also more popular amongst other languages (see https://github.com/rust-lang/rust/issues/4361#issuecomment-33470215).
......@@ -77,7 +77,7 @@ struct ArcInner<T> {
}
impl<T: Sync + Send> Arc<T> {
/// Create an atomically reference counted wrapper.
/// Creates an atomically reference counted wrapper.
#[inline]
#[stable]
pub fn new(data: T) -> Arc<T> {
......@@ -101,7 +101,7 @@ fn inner(&self) -> &ArcInner<T> {
unsafe { &*self._ptr }
}
/// Downgrades a strong pointer to a weak pointer
/// Downgrades a strong pointer to a weak pointer.
///
/// Weak pointers will not keep the data alive. Once all strong references
/// to the underlying data have been dropped, the data itself will be
......@@ -224,7 +224,7 @@ impl<T: Sync + Send> Weak<T> {
///
/// This method will fail to upgrade this reference if the strong reference
/// count has already reached 0, but if there are still other active strong
/// references this function will return a new strong reference to the data
/// references this function will return a new strong reference to the data.
pub fn upgrade(&self) -> Option<Arc<T>> {
// We use a CAS loop to increment the strong count instead of a
// fetch_add because once the count hits 0 is must never be above 0.
......
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// 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.
//
......@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A unique pointer type
//! A unique pointer type.
use core::any::{Any, AnyRefExt};
use core::clone::Clone;
......@@ -26,12 +26,14 @@
///
/// The following two examples are equivalent:
///
/// use std::boxed::HEAP;
/// ```rust
/// use std::boxed::HEAP;
///
/// # struct Bar;
/// # impl Bar { fn new(_a: int) { } }
/// let foo = box(HEAP) Bar::new(2);
/// let foo = box Bar::new(2);
/// # struct Bar;
/// # impl Bar { fn new(_a: int) { } }
/// let foo = box(HEAP) Bar::new(2);
/// let foo = box Bar::new(2);
/// ```
#[lang = "exchange_heap"]
#[experimental = "may be renamed; uncertain about custom allocator design"]
pub static HEAP: () = ();
......@@ -47,11 +49,11 @@ fn default() -> Box<T> { box Default::default() }
#[unstable]
impl<T: Clone> Clone for Box<T> {
/// Return a copy of the owned box.
/// Returns a copy of the owned box.
#[inline]
fn clone(&self) -> Box<T> { box {(**self).clone()} }
/// Perform copy-assignment from `source` by reusing the existing allocation.
/// Performs copy-assignment from `source` by reusing the existing allocation.
#[inline]
fn clone_from(&mut self, source: &Box<T>) {
(**self).clone_from(&(**source));
......@@ -86,7 +88,7 @@ fn cmp(&self, other: &Box<T>) -> Ordering {
}
impl<T: Eq> Eq for Box<T> {}
/// Extension methods for an owning `Any` trait object
/// Extension methods for an owning `Any` trait object.
#[unstable = "post-DST and coherence changes, this will not be a trait but \
rather a direct `impl` on `Box<Any>`"]
pub trait BoxAny {
......
......@@ -15,7 +15,7 @@
#[cfg(not(test))] use core::raw;
#[cfg(not(test))] use util;
/// Return a pointer to `size` bytes of memory.
/// Returns a pointer to `size` bytes of memory.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
......@@ -25,7 +25,7 @@ pub unsafe fn allocate(size: uint, align: uint) -> *mut u8 {
imp::allocate(size, align)
}
/// Extend or shrink the allocation referenced by `ptr` to `size` bytes of
/// Extends or shrinks the allocation referenced by `ptr` to `size` bytes of
/// memory.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
......@@ -41,10 +41,10 @@ pub unsafe fn reallocate(ptr: *mut u8, size: uint, align: uint,
imp::reallocate(ptr, size, align, old_size)
}
/// Extend or shrink the allocation referenced by `ptr` to `size` bytes of
/// Extends or shrinks the allocation referenced by `ptr` to `size` bytes of
/// memory in-place.
///
/// Return true if successful, otherwise false if the allocation was not
/// Returns true if successful, otherwise false if the allocation was not
/// altered.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
......@@ -60,7 +60,7 @@ pub unsafe fn reallocate_inplace(ptr: *mut u8, size: uint, align: uint,
imp::reallocate_inplace(ptr, size, align, old_size)
}
/// Deallocate the memory referenced by `ptr`.
/// Deallocates the memory referenced by `ptr`.
///
/// The `ptr` parameter must not be null.
///
......@@ -72,14 +72,14 @@ pub unsafe fn deallocate(ptr: *mut u8, size: uint, align: uint) {
imp::deallocate(ptr, size, align)
}
/// Return the usable size of an allocation created with the specified the
/// Returns the usable size of an allocation created with the specified the
/// `size` and `align`.
#[inline]
pub fn usable_size(size: uint, align: uint) -> uint {
imp::usable_size(size, align)
}
/// Print implementation-defined allocator statistics.
/// Prints implementation-defined allocator statistics.
///
/// These statistics may be inconsistent if other threads use the allocator
/// during the call.
......@@ -88,7 +88,7 @@ pub fn stats_print() {
imp::stats_print();
}
// The compiler never calls `exchange_free` on ~ZeroSizeType, so zero-size
// The compiler never calls `exchange_free` on Box<ZeroSizeType>, so zero-size
// allocations can point to this `static`. It would be incorrect to use a null
// pointer, due to enums assuming types like unique pointers are never null.
pub static mut EMPTY: uint = 12345;
......
......@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Rust's core allocation library
//! # The Rust core allocation library
//!
//! This is the lowest level library through which allocation in Rust can be
//! performed where the allocation is assumed to succeed. This library will
......@@ -23,13 +23,13 @@
//!
//! ## Boxed values
//!
//! The [`Box`](boxed/index.html) type is the core owned pointer type in rust.
//! The [`Box`](boxed/index.html) type is the core owned pointer type in Rust.
//! There can only be one owner of a `Box`, and the owner can decide to mutate
//! the contents, which live on the heap.
//!
//! This type can be sent among tasks efficiently as the size of a `Box` value
//! is just a pointer. Tree-like data structures are often built on owned
//! pointers because each node often has only one owner, the parent.
//! is the same as that of a pointer. Tree-like data structures are often built
//! with boxes because each node often has only one owner, the parent.
//!
//! ## Reference counted pointers
//!
......@@ -37,8 +37,8 @@
//! type intended for sharing memory within a task. An `Rc` pointer wraps a
//! type, `T`, and only allows access to `&T`, a shared reference.
//!
//! This type is useful when inherited mutability is too constraining for an
//! application (such as using `Box`), and is often paired with the `Cell` or
//! This type is useful when inherited mutability (such as using `Box`) is too
//! constraining for an application, and is often paired with the `Cell` or
//! `RefCell` types in order to allow mutation.
//!
//! ## Atomically reference counted pointers
......
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// 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.
//
......@@ -14,7 +14,7 @@
use libc::{c_void, size_t, free, malloc, realloc};
use core::ptr::{RawPtr, mut_null};
/// A wrapper around libc::malloc, aborting on out-of-memory
/// A wrapper around libc::malloc, aborting on out-of-memory.
#[inline]
pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
// `malloc(0)` may allocate, but it may also return a null pointer
......@@ -30,7 +30,7 @@ pub unsafe fn malloc_raw(size: uint) -> *mut u8 {
}
}
/// A wrapper around libc::realloc, aborting on out-of-memory
/// A wrapper around libc::realloc, aborting on out-of-memory.
#[inline]
pub unsafe fn realloc_raw(ptr: *mut u8, size: uint) -> *mut u8 {
// `realloc(ptr, 0)` may allocate, but it may also return a null pointer
......
......@@ -8,145 +8,142 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*! Task-local reference-counted boxes (`Rc` type)
The `Rc` type provides shared ownership of an immutable value. Destruction is
deterministic, and will occur as soon as the last owner is gone. It is marked
as non-sendable because it avoids the overhead of atomic reference counting.
The `downgrade` method can be used to create a non-owning `Weak` pointer to the
box. A `Weak` pointer can be upgraded to an `Rc` pointer, but will return
`None` if the value has already been freed.
For example, a tree with parent pointers can be represented by putting the
nodes behind strong `Rc` pointers, and then storing the parent pointers as
`Weak` pointers.
## Examples
Consider a scenario where a set of Gadgets are owned by a given Owner. We want
to have our Gadgets point to their Owner. We can't do this with unique
ownership, because more than one gadget may belong to the same Owner. Rc
allows us to share an Owner between multiple Gadgets, and have the Owner kept
alive as long as any Gadget points at it.
```rust
use std::rc::Rc;
struct Owner {
name: String
// ...other fields
}
struct Gadget {
id: int,
owner: Rc<Owner>
// ...other fields
}
fn main() {
// Create a reference counted Owner.
let gadget_owner : Rc<Owner> = Rc::new(
Owner { name: String::from_str("Gadget Man") }
);
// Create Gadgets belonging to gadget_owner. To increment the reference
// count we clone the Rc object.
let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
drop(gadget_owner);
// Despite dropping gadget_owner, we're still able to print out the name of
// the Owner of the Gadgets. This is because we've only dropped the
// reference count object, not the Owner it wraps. As long as there are
// other Rc objects pointing at the same Owner, it will stay alive. Notice
// that the Rc wrapper around Gadget.owner gets automatically dereferenced
// for us.
println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
// At the end of the method, gadget1 and gadget2 get destroyed, and with
// them the last counted references to our Owner. Gadget Man now gets
// destroyed as well.
}
```
If our requirements change, and we also need to be able to traverse from
Owner->Gadget, we will run into problems: an Rc pointer from Owner->Gadget
introduces a cycle between the objects. This means that their reference counts
can never reach 0, and the objects will stay alive: a memory leak. In order to
get around this, we can use `Weak` pointers. These are reference counted
pointers that don't keep an object alive if there are no normal `Rc` (or
*strong*) pointers left.
Rust actually makes it somewhat difficult to produce this loop in the first
place: in order to end up with two objects that point at each other, one of
them needs to be mutable. This is problematic because Rc enforces memory
safety by only giving out shared references to the object it wraps, and these
don't allow direct mutation. We need to wrap the part of the object we wish to
mutate in a `RefCell`, which provides *interior mutability*: a method to
achieve mutability through a shared reference. `RefCell` enforces Rust's
borrowing rules at runtime. Read the `Cell` documentation for more details on
interior mutability.
```rust
use std::rc::Rc;
use std::rc::Weak;
use std::cell::RefCell;
struct Owner {
name: String,
gadgets: RefCell<Vec<Weak<Gadget>>>
// ...other fields
}
struct Gadget {
id: int,
owner: Rc<Owner>
// ...other fields
}
fn main() {
// Create a reference counted Owner. Note the fact that we've put the
// Owner's vector of Gadgets inside a RefCell so that we can mutate it
// through a shared reference.
let gadget_owner : Rc<Owner> = Rc::new(
Owner {
name: "Gadget Man".to_string(),
gadgets: RefCell::new(Vec::new())
}
);
// Create Gadgets belonging to gadget_owner as before.
let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
// Add the Gadgets to their Owner. To do this we mutably borrow from
// the RefCell holding the Owner's Gadgets.
gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
// Iterate over our Gadgets, printing their details out
for gadget_opt in gadget_owner.gadgets.borrow().iter() {
// gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
// that their object is still alive, we need to call upgrade() on them
// to turn them into a strong reference. This returns an Option, which
// contains a reference to our object if it still exists.
let gadget = gadget_opt.upgrade().unwrap();
println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
}
// At the end of the method, gadget_owner, gadget1 and gadget2 get
// destroyed. There are now no strong (Rc) references to the gadgets.
// Once they get destroyed, the Gadgets get destroyed. This zeroes the
// reference count on Gadget Man, so he gets destroyed as well.
}
```
*/
//! Task-local reference-counted boxes (the `Rc` type).
//!
//! The `Rc` type provides shared ownership of an immutable value. Destruction is
//! deterministic, and will occur as soon as the last owner is gone. It is marked
//! as non-sendable because it avoids the overhead of atomic reference counting.
//!
//! The `downgrade` method can be used to create a non-owning `Weak` pointer to the
//! box. A `Weak` pointer can be upgraded to an `Rc` pointer, but will return
//! `None` if the value has already been freed.
//!
//! For example, a tree with parent pointers can be represented by putting the
//! nodes behind strong `Rc` pointers, and then storing the parent pointers as
//! `Weak` pointers.
//!
//! # Examples
//!
//! Consider a scenario where a set of `Gadget`s are owned by a given `Owner`.
//! We want to have our `Gadget`s point to their `Owner`. We can't do this with
//! unique ownership, because more than one gadget may belong to the same
//! `Owner`. `Rc` allows us to share an `Owner` between multiple `Gadget`s, and
//! have the `Owner` kept alive as long as any `Gadget` points at it.
//!
//! ```rust
//! use std::rc::Rc;
//!
//! struct Owner {
//! name: String
//! // ...other fields
//! }
//!
//! struct Gadget {
//! id: int,
//! owner: Rc<Owner>
//! // ...other fields
//! }
//!
//! fn main() {
//! // Create a reference counted Owner.
//! let gadget_owner : Rc<Owner> = Rc::new(
//! Owner { name: String::from_str("Gadget Man") }
//! );
//!
//! // Create Gadgets belonging to gadget_owner. To increment the reference
//! // count we clone the Rc object.
//! let gadget1 = Gadget { id: 1, owner: gadget_owner.clone() };
//! let gadget2 = Gadget { id: 2, owner: gadget_owner.clone() };
//!
//! drop(gadget_owner);
//!
//! // Despite dropping gadget_owner, we're still able to print out the name of
//! // the Owner of the Gadgets. This is because we've only dropped the
//! // reference count object, not the Owner it wraps. As long as there are
//! // other Rc objects pointing at the same Owner, it will stay alive. Notice
//! // that the Rc wrapper around Gadget.owner gets automatically dereferenced
//! // for us.
//! println!("Gadget {} owned by {}", gadget1.id, gadget1.owner.name);
//! println!("Gadget {} owned by {}", gadget2.id, gadget2.owner.name);
//!
//! // At the end of the method, gadget1 and gadget2 get destroyed, and with
//! // them the last counted references to our Owner. Gadget Man now gets
//! // destroyed as well.
//! }
//! ```
//!
//! If our requirements change, and we also need to be able to traverse from
//! Owner → Gadget, we will run into problems: an `Rc` pointer from Owner → Gadget
//! introduces a cycle between the objects. This means that their reference counts
//! can never reach 0, and the objects will stay alive: a memory leak. In order to
//! get around this, we can use `Weak` pointers. These are reference counted
//! pointers that don't keep an object alive if there are no normal `Rc` (or
//! *strong*) pointers left.
//!
//! Rust actually makes it somewhat difficult to produce this loop in the first
//! place: in order to end up with two objects that point at each other, one of
//! them needs to be mutable. This is problematic because `Rc` enforces memory
//! safety by only giving out shared references to the object it wraps, and these
//! don't allow direct mutation. We need to wrap the part of the object we wish to
//! mutate in a `RefCell`, which provides *interior mutability*: a method to
//! achieve mutability through a shared reference. `RefCell` enforces Rust's
//! borrowing rules at runtime. Read the `Cell` documentation for more details on
//! interior mutability.
//!
//! ```rust
//! use std::rc::Rc;
//! use std::rc::Weak;
//! use std::cell::RefCell;
//!
//! struct Owner {
//! name: String,
//! gadgets: RefCell<Vec<Weak<Gadget>>>
//! // ...other fields
//! }
//!
//! struct Gadget {
//! id: int,
//! owner: Rc<Owner>
//! // ...other fields
//! }
//!
//! fn main() {
//! // Create a reference counted Owner. Note the fact that we've put the
//! // Owner's vector of Gadgets inside a RefCell so that we can mutate it
//! // through a shared reference.
//! let gadget_owner : Rc<Owner> = Rc::new(
//! Owner {
//! name: "Gadget Man".to_string(),
//! gadgets: RefCell::new(Vec::new())
//! }
//! );
//!
//! // Create Gadgets belonging to gadget_owner as before.
//! let gadget1 = Rc::new(Gadget{id: 1, owner: gadget_owner.clone()});
//! let gadget2 = Rc::new(Gadget{id: 2, owner: gadget_owner.clone()});
//!
//! // Add the Gadgets to their Owner. To do this we mutably borrow from
//! // the RefCell holding the Owner's Gadgets.
//! gadget_owner.gadgets.borrow_mut().push(gadget1.clone().downgrade());
//! gadget_owner.gadgets.borrow_mut().push(gadget2.clone().downgrade());
//!
//! // Iterate over our Gadgets, printing their details out
//! for gadget_opt in gadget_owner.gadgets.borrow().iter() {
//!
//! // gadget_opt is a Weak<Gadget>. Since weak pointers can't guarantee
//! // that their object is still alive, we need to call upgrade() on them
//! // to turn them into a strong reference. This returns an Option, which
//! // contains a reference to our object if it still exists.
//! let gadget = gadget_opt.upgrade().unwrap();
//! println!("Gadget {} owned by {}", gadget.id, gadget.owner.name);
//! }
//!
//! // At the end of the method, gadget_owner, gadget1 and gadget2 get
//! // destroyed. There are now no strong (Rc) references to the gadgets.
//! // Once they get destroyed, the Gadgets get destroyed. This zeroes the
//! // reference count on Gadget Man, so he gets destroyed as well.
//! }
//! ```
#![stable]
......@@ -171,7 +168,7 @@ struct RcBox<T> {
weak: Cell<uint>
}
/// Immutable reference counted pointer type
/// An immutable reference-counted pointer type.
#[unsafe_no_drop_flag]
#[stable]
pub struct Rc<T> {
......@@ -184,7 +181,7 @@ pub struct Rc<T> {
#[stable]
impl<T> Rc<T> {
/// Construct a new reference-counted box
/// Constructs a new reference-counted pointer.
pub fn new(value: T) -> Rc<T> {
unsafe {
Rc {
......@@ -206,8 +203,8 @@ pub fn new(value: T) -> Rc<T> {
}
impl<T> Rc<T> {
/// Downgrade the reference-counted pointer to a weak reference
#[experimental = "Weak pointers may not belong in this module."]
/// Downgrades the reference-counted pointer to a weak reference.
#[experimental = "Weak pointers may not belong in this module"]
pub fn downgrade(&self) -> Weak<T> {
self.inc_weak();
Weak {
......@@ -234,7 +231,7 @@ pub fn is_unique<T>(rc: &Rc<T>) -> bool {
/// If the `Rc` does not have unique ownership, `Err` is returned with the
/// same `Rc`.
///
/// # Example:
/// # Example
///
/// ```
/// use std::rc::{mod, Rc};
......@@ -267,7 +264,7 @@ pub fn try_unwrap<T>(rc: Rc<T>) -> Result<T, Rc<T>> {
///
/// Returns `None` if the `Rc` does not have unique ownership.
///
/// # Example:
/// # Example
///
/// ```
/// use std::rc::{mod, Rc};
......@@ -312,7 +309,7 @@ pub fn make_unique(&mut self) -> &mut T {
#[experimental = "Deref is experimental."]
impl<T> Deref<T> for Rc<T> {
/// Borrow the value contained in the reference-counted box
/// Borrows the value contained in the reference-counted pointer.
#[inline(always)]
fn deref(&self) -> &T {
&self.inner().value
......@@ -404,7 +401,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
}
/// Weak reference to a reference-counted box
/// A weak reference to a reference-counted pointer.
#[unsafe_no_drop_flag]
#[experimental = "Weak pointers may not belong in this module."]
pub struct Weak<T> {
......@@ -417,7 +414,10 @@ pub struct Weak<T> {
#[experimental = "Weak pointers may not belong in this module."]
impl<T> Weak<T> {
/// Upgrade a weak reference to a strong reference
/// Upgrades a weak reference to a strong reference.
///
/// Returns `None` if there were no strong references and the data was
/// destroyed.
pub fn upgrade(&self) -> Option<Rc<T>> {
if self.strong() == 0 {
None
......
......@@ -7,7 +7,7 @@
// <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.
//
//! The arena, a fast but limited type of allocator.
//!
//! Arenas are a type of allocator that destroy the objects within, all at
......@@ -15,9 +15,9 @@
//! of individual objects while the arena itself is still alive. The benefit
//! of an arena is very fast allocation; just a pointer bump.
//!
//! This crate has two arenas implemented: TypedArena, which is a simpler
//! arena but can only hold objects of a single type, and Arena, which is a
//! more complex, slower Arena which can hold objects of any type.
//! This crate has two arenas implemented: `TypedArena`, which is a simpler
//! arena but can only hold objects of a single type, and `Arena`, which is a
//! more complex, slower arena which can hold objects of any type.
#![crate_name = "arena"]
#![experimental]
......@@ -62,24 +62,24 @@ unsafe fn as_ptr(&self) -> *const u8 {
/// A slower reflection-based arena that can allocate objects of any type.
///
/// This arena uses Vec<u8> as a backing store to allocate objects from. For
/// This arena uses `Vec<u8>` as a backing store to allocate objects from. For
/// each allocated object, the arena stores a pointer to the type descriptor
/// followed by the object. (Potentially with alignment padding after each
/// element.) When the arena is destroyed, it iterates through all of its
/// followed by the object (potentially with alignment padding after each
/// element). When the arena is destroyed, it iterates through all of its
/// chunks, and uses the tydesc information to trace through the objects,
/// calling the destructors on them. One subtle point that needs to be
/// calling the destructors on them. One subtle point that needs to be
/// addressed is how to handle failures while running the user provided
/// initializer function. It is important to not run the destructor on
/// uninitialized objects, but how to detect them is somewhat subtle. Since
/// alloc() can be invoked recursively, it is not sufficient to simply exclude
/// `alloc()` can be invoked recursively, it is not sufficient to simply exclude
/// the most recent object. To solve this without requiring extra space, we
/// use the low order bit of the tydesc pointer to encode whether the object
/// it describes has been fully initialized.
///
/// As an optimization, objects with destructors are stored in
/// different chunks than objects without destructors. This reduces
/// overhead when initializing plain-old-data and means we don't need
/// to waste time running the destructors of POD.
/// As an optimization, objects with destructors are stored in different chunks
/// than objects without destructors. This reduces overhead when initializing
/// plain-old-data (`Copy` types) and means we don't need to waste time running
/// their destructors.
pub struct Arena {
// The head is separated out from the list as a unbenchmarked
// microoptimization, to avoid needing to case on the list to access the
......@@ -90,12 +90,12 @@ pub struct Arena {
}
impl Arena {
/// Allocate a new Arena with 32 bytes preallocated.
/// Allocates a new Arena with 32 bytes preallocated.
pub fn new() -> Arena {
Arena::new_with_size(32u)
}
/// Allocate a new Arena with `initial_size` bytes preallocated.
/// Allocates a new Arena with `initial_size` bytes preallocated.
pub fn new_with_size(initial_size: uint) -> Arena {
Arena {
head: RefCell::new(chunk(initial_size, false)),
......@@ -282,8 +282,8 @@ fn alloc_noncopy<T>(&self, op: || -> T) -> &T {
}
}
/// Allocate a new item in the arena, using `op` to initialize the value
/// and returning a reference to it.
/// Allocates a new item in the arena, using `op` to initialize the value,
/// and returns a reference to it.
#[inline]
pub fn alloc<T>(&self, op: || -> T) -> &T {
unsafe {
......@@ -438,13 +438,13 @@ fn end(&self) -> *const u8 {
}
impl<T> TypedArena<T> {
/// Creates a new TypedArena with preallocated space for 8 objects.
/// Creates a new `TypedArena` with preallocated space for eight objects.
#[inline]
pub fn new() -> TypedArena<T> {
TypedArena::with_capacity(8)
}
/// Creates a new TypedArena with preallocated space for the given number of
/// Creates a new `TypedArena` with preallocated space for the given number of
/// objects.
#[inline]
pub fn with_capacity(capacity: uint) -> TypedArena<T> {
......@@ -456,7 +456,7 @@ pub fn with_capacity(capacity: uint) -> TypedArena<T> {
}
}
/// Allocates an object in the TypedArena, returning a reference to it.
/// Allocates an object in the `TypedArena`, returning a reference to it.
#[inline]
pub fn alloc(&self, object: T) -> &T {
if self.ptr == self.end {
......
......@@ -109,7 +109,7 @@ struct BigBitv {
#[deriving(Clone)]
enum BitvVariant { Big(BigBitv), Small(SmallBitv) }
/// The bitvector type
/// The bitvector type.
///
/// # Example
///
......@@ -222,7 +222,7 @@ fn mask_words<'a>(&'a self, mut start: uint) -> MaskWords<'a> {
}
}
/// Create an empty Bitv.
/// Creates an empty `Bitv`.
///
/// # Example
///
......@@ -234,7 +234,7 @@ pub fn new() -> Bitv {
Bitv { storage: Vec::new(), nbits: 0 }
}
/// Create a Bitv that holds `nbits` elements, setting each element
/// Creates a `Bitv` that holds `nbits` elements, setting each element
/// to `init`.
///
/// # Example
......@@ -256,11 +256,11 @@ pub fn with_capacity(nbits: uint, init: bool) -> Bitv {
}
}
/// Retrieve the value at index `i`.
/// Retrieves the value at index `i`.
///
/// # Failure
///
/// Assert if `i` out of bounds.
/// Fails if `i` is out of bounds.
///
/// # Example
///
......@@ -283,11 +283,11 @@ pub fn get(&self, i: uint) -> bool {
x != 0
}
/// Set the value of a bit at a index `i`.
/// Sets the value of a bit at a index `i`.
///
/// # Failure
///
/// Assert if `i` out of bounds.
/// Fails if `i` is out of bounds.
///
/// # Example
///
......@@ -308,7 +308,7 @@ pub fn set(&mut self, i: uint, x: bool) {
else { self.storage[w] & !flag };
}
/// Set all bits to 1.
/// Sets all bits to 1.
///
/// # Example
///
......@@ -327,7 +327,7 @@ pub fn set_all(&mut self) {
for w in self.storage.mut_iter() { *w = !0u; }
}
/// Flip all bits.
/// Flips all bits.
///
/// # Example
///
......@@ -346,14 +346,15 @@ pub fn negate(&mut self) {
for w in self.storage.mut_iter() { *w = !*w; }
}
/// Calculate the union of two bitvectors, acts like bitwise or.
/// Calculates the union of two bitvectors. This acts like the bitwise `or`
/// function.
///
/// Set `self` to the union of `self` and `other`. Both bitvectors must be
/// the same length. Return `true` if `self` changed.
/// Sets `self` to the union of `self` and `other`. Both bitvectors must be
/// the same length. Returns `true` if `self` changed.
///
/// # Failure
///
/// Assert if the bitvectors are of different length.
/// Fails if the bitvectors are of different lengths.
///
/// # Example
///
......@@ -375,14 +376,15 @@ pub fn union(&mut self, other: &Bitv) -> bool {
self.process(other, |w1, w2| w1 | w2)
}
/// Calculate the intersection of two bitvectors, acts like bitwise and.
/// Calculates the intersection of two bitvectors. This acts like the
/// bitwise `and` function.
///
/// Set `self` to the intersection of `self` and `other`. Both bitvectors
/// must be the same length. Return `true` if `self` changed.
/// Sets `self` to the intersection of `self` and `other`. Both bitvectors
/// must be the same length. Returns `true` if `self` changed.
///
/// # Failure
///
/// Assert if the bitvectors are of different length.
/// Fails if the bitvectors are of different lengths.
///
/// # Example
///
......@@ -404,15 +406,15 @@ pub fn intersect(&mut self, other: &Bitv) -> bool {
self.process(other, |w1, w2| w1 & w2)
}
/// Calculate the difference between two bitvectors.
/// Calculates the difference between two bitvectors.
///
/// Set each element of `self` to the value of that element minus the
/// Sets each element of `self` to the value of that element minus the
/// element of `other` at the same index. Both bitvectors must be the same
/// length. Return `true` if `self` changed.
/// length. Returns `true` if `self` changed.
///
/// # Failure
///
/// Assert if the bitvectors are of different length.
/// Fails if the bitvectors are of different length.
///
/// # Example
///
......@@ -464,7 +466,7 @@ pub fn all(&self) -> bool {
(last_word == ((1 << self.nbits % uint::BITS) - 1) || last_word == !0u)
}
/// Return an iterator over the elements of the vector in order.
/// Returns an iterator over the elements of the vector in order.
///
/// # Example
///
......@@ -479,7 +481,7 @@ pub fn iter<'a>(&'a self) -> Bits<'a> {
Bits {bitv: self, next_idx: 0, end_idx: self.nbits}
}
/// Return `true` if all bits are 0.
/// Returns `true` if all bits are 0.
///
/// # Example
///
......@@ -496,7 +498,7 @@ pub fn none(&self) -> bool {
self.mask_words(0).all(|(_, w)| w == 0)
}
/// Return `true` if any bit is 1.
/// Returns `true` if any bit is 1.
///
/// # Example
///
......@@ -514,9 +516,9 @@ pub fn any(&self) -> bool {
!self.none()
}
/// Organise the bits into bytes, such that the first bit in the
/// Organises the bits into bytes, such that the first bit in the
/// `Bitv` becomes the high-order bit of the first byte. If the
/// size of the `Bitv` is not a multiple of 8 then trailing bits
/// size of the `Bitv` is not a multiple of eight then trailing bits
/// will be filled-in with `false`.
///
/// # Example
......@@ -559,7 +561,7 @@ fn bit (bitv: &Bitv, byte: uint, bit: uint) -> u8 {
)
}
/// Transform `self` into a `Vec<bool>` by turning each bit into a `bool`.
/// Transforms `self` into a `Vec<bool>` by turning each bit into a `bool`.
///
/// # Example
///
......@@ -574,11 +576,12 @@ pub fn to_bools(&self) -> Vec<bool> {
Vec::from_fn(self.nbits, |i| self.get(i))
}
/// Compare a bitvector to a vector of `bool`.
/// Both the bitvector and vector must have the same length.
/// Compares a `Bitv` to a slice of `bool`s.
/// Both the `Bitv` and slice must have the same length.
///
/// # Failure
///
/// Assert if the bitvectors are of different length.
/// Fails if the the `Bitv` and slice are of different length.
///
/// # Example
///
......@@ -600,7 +603,7 @@ pub fn eq_vec(&self, v: &[bool]) -> bool {
true
}
/// Shorten a Bitv, dropping excess elements.
/// Shortens a `Bitv`, dropping excess elements.
///
/// If `len` is greater than the vector's current length, this has no
/// effect.
......@@ -626,7 +629,7 @@ pub fn truncate(&mut self, len: uint) {
}
}
/// Grow the vector to be able to store `size` bits without resizing.
/// Grows the vector to be able to store `size` bits without resizing.
///
/// # Example
///
......@@ -646,7 +649,7 @@ pub fn reserve(&mut self, size: uint) {
}
}
/// Return the capacity in bits for this bit vector. Inserting any
/// Returns the capacity in bits for this bit vector. Inserting any
/// element less than this amount will not trigger a resizing.
///
/// # Example
......@@ -663,7 +666,7 @@ pub fn capacity(&self) -> uint {
self.storage.len() * uint::BITS
}
/// Grow the `Bitv` in-place. Add `n` copies of `value` to the `Bitv`.
/// Grows the `Bitv` in-place, adding `n` copies of `value` to the `Bitv`.
///
/// # Example
///
......@@ -704,7 +707,7 @@ pub fn grow(&mut self, n: uint, value: bool) {
self.nbits = new_nbits;
}
/// Shorten by one and return the removed element.
/// Shortens by one element and returns the removed element.
///
/// # Failure
///
......@@ -731,7 +734,7 @@ pub fn pop(&mut self) -> bool {
ret
}
/// Push a `bool` onto the end.
/// Pushes a `bool` onto the end.
///
/// # Example
///
......@@ -753,7 +756,7 @@ pub fn push(&mut self, elem: bool) {
}
}
/// Transform a byte-vector into a `Bitv`. Each byte becomes 8 bits,
/// Transforms a byte-vector into a `Bitv`. Each byte becomes eight bits,
/// with the most significant bits of each byte coming first. Each
/// bit becomes `true` if equal to 1 or `false` if equal to 0.
///
......@@ -776,7 +779,7 @@ pub fn from_bytes(bytes: &[u8]) -> Bitv {
})
}
/// Create a `Bitv` of the specified length where the value at each
/// Creates a `Bitv` of the specified length where the value at each
/// index is `f(index)`.
///
/// # Example
......@@ -1035,7 +1038,7 @@ fn eq(&self, other: &BitvSet) -> bool {
impl cmp::Eq for BitvSet {}
impl BitvSet {
/// Create a new bit vector set with initially no contents.
/// Creates a new bit vector set with initially no contents.
///
/// # Example
///
......@@ -1048,7 +1051,7 @@ pub fn new() -> BitvSet {
BitvSet(Bitv::new())
}
/// Create a new bit vector set with initially no contents, able to
/// Creates a new bit vector set with initially no contents, able to
/// hold `nbits` elements without resizing.
///
/// # Example
......@@ -1063,7 +1066,7 @@ pub fn with_capacity(nbits: uint) -> BitvSet {
BitvSet(Bitv::with_capacity(nbits, false))
}
/// Create a new bit vector set from the given bit vector.
/// Creates a new bit vector set from the given bit vector.
///
/// # Example
///
......@@ -1116,7 +1119,7 @@ pub fn reserve(&mut self, size: uint) {
bitv.reserve(size)
}
/// Consume this set to return the underlying bit vector.
/// Consumes this set to return the underlying bit vector.
///
/// # Example
///
......@@ -1136,7 +1139,7 @@ pub fn unwrap(self) -> Bitv {
bitv
}
/// Return a reference to the underlying bit vector.
/// Returns a reference to the underlying bit vector.
///
/// # Example
///
......@@ -1155,7 +1158,7 @@ pub fn get_ref<'a>(&'a self) -> &'a Bitv {
bitv
}
/// Return a mutable reference to the underlying bit vector.
/// Returns a mutable reference to the underlying bit vector.
///
/// # Example
///
......@@ -1201,7 +1204,7 @@ fn other_op(&mut self, other: &BitvSet, f: |uint, uint| -> uint) {
}
}
/// Truncate the underlying vector to the least length required.
/// Truncates the underlying vector to the least length required.
///
/// # Example
///
......@@ -1232,7 +1235,7 @@ pub fn shrink_to_fit(&mut self) {
bitv.nbits = trunc_len * uint::BITS;
}
/// Iterator over each uint stored in the BitvSet.
/// Iterator over each uint stored in the `BitvSet`.
///
/// # Example
///
......@@ -1373,7 +1376,7 @@ pub fn symmetric_difference<'a>(&'a self, other: &'a BitvSet) -> TwoBitPositions
}
}
/// Union in-place with the specified other bit vector.
/// Unions in-place with the specified other bit vector.
///
/// # Example
///
......@@ -1396,7 +1399,7 @@ pub fn union_with(&mut self, other: &BitvSet) {
self.other_op(other, |w1, w2| w1 | w2);
}
/// Intersect in-place with the specified other bit vector.
/// Intersects in-place with the specified other bit vector.
///
/// # Example
///
......@@ -1419,7 +1422,8 @@ pub fn intersect_with(&mut self, other: &BitvSet) {
self.other_op(other, |w1, w2| w1 & w2);
}
/// Difference in-place with the specified other bit vector.
/// Makes this bit vector the difference with the specified other bit vector
/// in-place.
///
/// # Example
///
......@@ -1449,7 +1453,8 @@ pub fn difference_with(&mut self, other: &BitvSet) {
self.other_op(other, |w1, w2| w1 & !w2);
}
/// Symmetric difference in-place with the specified other bit vector.
/// Makes this bit vector the symmetric difference with the specified other
/// bit vector in-place.
///
/// # Example
///
......
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// 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.
//
......@@ -8,8 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//
// btree.rs
//
// NB. this is not deprecated for removal, just deprecating the
// current implementation. If the major pain-points are addressed
......@@ -18,12 +16,12 @@
prefer a HashMap, TreeMap or TrieMap"]
#![allow(deprecated)]
//! Starting implementation of a btree for rust.
//! Structure inspired by github user davidhalperin's gist.
//! Starting implementation of a B-tree for Rust.
//! Structure inspired by Github user davidhalperin's gist.
///A B-tree contains a root node (which contains a vector of elements),
///a length (the height of the tree), and lower and upper bounds on the
///number of elements that a given node can contain.
// A B-tree contains a root node (which contains a vector of elements),
// a length (the height of the tree), and lower and upper bounds on the
// number of elements that a given node can contain.
use core::prelude::*;
......@@ -43,9 +41,8 @@ pub struct BTree<K, V> {
}
impl<K: Ord, V> BTree<K, V> {
///Returns new BTree with root node (leaf) and user-supplied lower bound
///The lower bound applies to every node except the root node.
/// Returns new `BTree` with root node (leaf) and user-supplied lower bound
/// The lower bound applies to every node except the root node.
pub fn new(k: K, v: V, lb: uint) -> BTree<K, V> {
BTree {
root: Node::new_leaf(vec!(LeafElt::new(k, v))),
......@@ -55,8 +52,8 @@ pub fn new(k: K, v: V, lb: uint) -> BTree<K, V> {
}
}
///Helper function for clone: returns new BTree with supplied root node,
///length, and lower bound. For use when the length is known already.
/// Helper function for `clone`: returns new BTree with supplied root node,
/// length, and lower bound. For use when the length is known already.
fn new_with_node_len(n: Node<K, V>,
length: uint,
lb: uint) -> BTree<K, V> {
......@@ -69,17 +66,17 @@ fn new_with_node_len(n: Node<K, V>,
}
}
//We would probably want to remove the dependence on the Clone trait in the future.
//It is here as a crutch to ensure values can be passed around through the tree's nodes
//especially during insertions and deletions.
// We would probably want to remove the dependence on the Clone trait in the future.
// It is here as a crutch to ensure values can be passed around through the tree's nodes
// especially during insertions and deletions.
impl<K: Clone + Ord, V: Clone> BTree<K, V> {
///Returns the value of a given key, which may not exist in the tree.
///Calls the root node's get method.
/// Returns the value of a given key, which may not exist in the tree.
/// Calls the root node's get method.
pub fn get(self, k: K) -> Option<V> {
return self.root.get(k);
}
///An insert method that uses the clone() feature for support.
/// An insert method that uses the `clone` method for support.
pub fn insert(mut self, k: K, v: V) -> BTree<K, V> {
let (a, b) = self.root.clone().insert(k, v, self.upper_bound.clone());
if b {
......@@ -98,8 +95,6 @@ pub fn insert(mut self, k: K, v: V) -> BTree<K, V> {
}
impl<K: Clone + Ord, V: Clone> Clone for BTree<K, V> {
///Implements the Clone trait for the BTree.
///Uses a helper function/constructor to produce a new BTree.
fn clone(&self) -> BTree<K, V> {
BTree::new_with_node_len(self.root.clone(), self.len, self.lower_bound)
}
......@@ -120,46 +115,46 @@ fn partial_cmp(&self, other: &BTree<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for BTree<K, V> {
///Returns an ordering based on the root nodes of each BTree.
/// Returns an ordering based on the root nodes of each `BTree`.
fn cmp(&self, other: &BTree<K, V>) -> Ordering {
self.root.cmp(&other.root)
}
}
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for BTree<K, V> {
///Returns a string representation of the BTree
/// Returns a string representation of the `BTree`.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.root.fmt(f)
}
}
//Node types
//A node is either a LeafNode or a BranchNode, which contain either a Leaf or a Branch.
//Branches contain BranchElts, which contain a left child (another node) and a key-value
//pair. Branches also contain the rightmost child of the elements in the array.
//Leaves contain LeafElts, which do not have children.
// Node types
//
// A node is either a LeafNode or a BranchNode, which contain either a Leaf or a Branch.
// Branches contain BranchElts, which contain a left child (another node) and a key-value
// pair. Branches also contain the rightmost child of the elements in the array.
// Leaves contain LeafElts, which do not have children.
enum Node<K, V> {
LeafNode(Leaf<K, V>),
BranchNode(Branch<K, V>)
}
//Node functions/methods
impl<K: Ord, V> Node<K, V> {
///Creates a new leaf node given a vector of elements.
/// Creates a new leaf node given a vector of elements.
fn new_leaf(vec: Vec<LeafElt<K, V>>) -> Node<K,V> {
LeafNode(Leaf::new(vec))
}
///Creates a new branch node given a vector of an elements and a pointer to a rightmost child.
/// Creates a new branch node given a vector of an elements and a pointer to a rightmost child.
fn new_branch(vec: Vec<BranchElt<K, V>>, right: Box<Node<K, V>>)
-> Node<K, V> {
BranchNode(Branch::new(vec, right))
}
///Determines whether the given Node contains a Branch or a Leaf.
///Used in testing.
/// Determines whether the given Node contains a Branch or a Leaf.
/// Used in testing.
fn is_leaf(&self) -> bool {
match self {
&LeafNode(..) => true,
......@@ -167,8 +162,8 @@ fn is_leaf(&self) -> bool {
}
}
///A binary search function for Nodes.
///Calls either the Branch's or the Leaf's bsearch function.
/// A binary search function for Nodes.
/// Calls either the Branch's or the Leaf's bsearch function.
fn bsearch_node(&self, k: K) -> Option<uint> {
match self {
&LeafNode(ref leaf) => leaf.bsearch_leaf(k),
......@@ -178,8 +173,8 @@ fn bsearch_node(&self, k: K) -> Option<uint> {
}
impl<K: Clone + Ord, V: Clone> Node<K, V> {
///Returns the corresponding value to the provided key.
///get() is called in different ways on a branch or a leaf.
/// Returns the corresponding value to the provided key.
/// `get()` is called in different ways on a branch or a leaf.
fn get(&self, k: K) -> Option<V> {
match *self {
LeafNode(ref leaf) => return leaf.get(k),
......@@ -187,7 +182,7 @@ fn get(&self, k: K) -> Option<V> {
}
}
///Matches on the Node, then performs and returns the appropriate insert method.
/// Matches on the `Node`, then performs and returns the appropriate insert method.
fn insert(self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
match self {
LeafNode(leaf) => leaf.insert(k, v, ub),
......@@ -197,7 +192,7 @@ fn insert(self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
}
impl<K: Clone + Ord, V: Clone> Clone for Node<K, V> {
///Returns a new node based on whether or not it is a branch or a leaf.
/// Returns a new `Node` based on whether or not it is a branch or a leaf.
fn clone(&self) -> Node<K, V> {
match *self {
LeafNode(ref leaf) => {
......@@ -242,7 +237,7 @@ fn partial_cmp(&self, other: &Node<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for Node<K, V> {
///Implementation of Ord for Nodes.
/// Implementation of `Ord` for `Node`s.
fn cmp(&self, other: &Node<K, V>) -> Ordering {
match *self {
LeafNode(ref leaf) => {
......@@ -262,10 +257,10 @@ fn cmp(&self, other: &Node<K, V>) -> Ordering {
}
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for Node<K, V> {
///Returns a string representation of a Node.
///Will iterate over the Node and show "Key: x, value: y, child: () // "
///for all elements in the Node. "Child" only exists if the Node contains
///a branch.
/// Returns a string representation of a `Node`.
/// Will iterate over the Node and show `Key: x, value: y, child: ()`
/// for all elements in the `Node`. `child` only exists if the `Node` contains
/// a branch.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LeafNode(ref leaf) => leaf.fmt(f),
......@@ -275,13 +270,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
//A leaf is a vector with elements that contain no children. A leaf also
//does not contain a rightmost child.
// A leaf is a vector with elements that contain no children. A leaf also
// does not contain a rightmost child.
struct Leaf<K, V> {
elts: Vec<LeafElt<K, V>>
}
//Vector of values with children, plus a rightmost child (greater than all)
// Vector of values with children, plus a rightmost child (greater than all)
struct Branch<K, V> {
elts: Vec<BranchElt<K,V>>,
rightmost_child: Box<Node<K, V>>,
......@@ -289,15 +284,15 @@ struct Branch<K, V> {
impl<K: Ord, V> Leaf<K, V> {
///Creates a new Leaf from a vector of LeafElts.
/// Creates a new `Leaf` from a vector of `LeafElts`.
fn new(vec: Vec<LeafElt<K, V>>) -> Leaf<K, V> {
Leaf {
elts: vec
}
}
///Searches a leaf for a spot for a new element using a binary search.
///Returns None if the element is already in the vector.
/// Searches a leaf for a spot for a new element using a binary search.
/// Returns `None` if the element is already in the vector.
fn bsearch_leaf(&self, k: K) -> Option<uint> {
let mut high: uint = self.elts.len();
let mut low: uint = 0;
......@@ -349,7 +344,7 @@ fn bsearch_leaf(&self, k: K) -> Option<uint> {
impl<K: Clone + Ord, V: Clone> Leaf<K, V> {
///Returns the corresponding value to the supplied key.
/// Returns the corresponding value to the supplied key.
fn get(&self, k: K) -> Option<V> {
for s in self.elts.iter() {
let order = s.key.cmp(&k);
......@@ -361,7 +356,7 @@ fn get(&self, k: K) -> Option<V> {
return None;
}
///Uses clone() to facilitate inserting new elements into a tree.
/// Uses `clone()` to facilitate inserting new elements into a tree.
fn insert(mut self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
let to_insert = LeafElt::new(k, v);
let index: Option<uint> = self.bsearch_leaf(to_insert.clone().key);
......@@ -400,7 +395,7 @@ fn insert(mut self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
}
impl<K: Clone + Ord, V: Clone> Clone for Leaf<K, V> {
///Returns a new Leaf with the same elts.
/// Returns a new `Leaf` with the same elts.
fn clone(&self) -> Leaf<K, V> {
Leaf::new(self.elts.clone())
}
......@@ -421,7 +416,7 @@ fn partial_cmp(&self, other: &Leaf<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for Leaf<K, V> {
///Returns an ordering based on the first element of each Leaf.
/// Returns an ordering based on the first element of each `Leaf`.
fn cmp(&self, other: &Leaf<K, V>) -> Ordering {
if self.elts.len() > other.elts.len() {
return Greater;
......@@ -435,7 +430,7 @@ fn cmp(&self, other: &Leaf<K, V>) -> Ordering {
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for Leaf<K, V> {
///Returns a string representation of a Leaf.
/// Returns a string representation of a `Leaf`.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, s) in self.elts.iter().enumerate() {
if i != 0 { try!(write!(f, " // ")) }
......@@ -447,7 +442,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
impl<K: Ord, V> Branch<K, V> {
///Creates a new Branch from a vector of BranchElts and a rightmost child (a node).
/// Creates a new `Branch` from a vector of `BranchElts` and a rightmost child (a node).
fn new(vec: Vec<BranchElt<K, V>>, right: Box<Node<K, V>>)
-> Branch<K, V> {
Branch {
......@@ -506,8 +501,8 @@ fn bsearch_branch(&self, k: K) -> Option<uint> {
}
impl<K: Clone + Ord, V: Clone> Branch<K, V> {
///Returns the corresponding value to the supplied key.
///If the key is not there, find the child that might hold it.
/// Returns the corresponding value to the supplied key.
/// If the key is not there, find the child that might hold it.
fn get(&self, k: K) -> Option<V> {
for s in self.elts.iter() {
let order = s.key.cmp(&k);
......@@ -520,7 +515,7 @@ fn get(&self, k: K) -> Option<V> {
self.rightmost_child.get(k)
}
///An insert method that uses .clone() for support.
/// An insert method that uses `.clone()` for support.
fn insert(mut self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
let mut new_branch = Node::new_branch(self.clone().elts, self.clone().rightmost_child);
let mut outcome = false;
......@@ -630,7 +625,7 @@ fn insert(mut self, k: K, v: V, ub: uint) -> (Node<K, V>, bool) {
}
impl<K: Clone + Ord, V: Clone> Clone for Branch<K, V> {
///Returns a new branch using the clone methods of the Branch's internal variables.
/// Returns a new branch using the clone methods of the `Branch`'s internal variables.
fn clone(&self) -> Branch<K, V> {
Branch::new(self.elts.clone(), self.rightmost_child.clone())
}
......@@ -651,7 +646,8 @@ fn partial_cmp(&self, other: &Branch<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for Branch<K, V> {
///Compares the first elements of two branches to determine an ordering
/// Compares the first elements of two `Branch`es to determine an
/// `Ordering`.
fn cmp(&self, other: &Branch<K, V>) -> Ordering {
if self.elts.len() > other.elts.len() {
return Greater;
......@@ -664,7 +660,7 @@ fn cmp(&self, other: &Branch<K, V>) -> Ordering {
}
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for Branch<K, V> {
///Returns a string representation of a Branch.
/// Returns a string representation of a `Branch`.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, s) in self.elts.iter().enumerate() {
if i != 0 { try!(write!(f, " // ")) }
......@@ -688,7 +684,7 @@ struct BranchElt<K, V> {
}
impl<K: Ord, V> LeafElt<K, V> {
///Creates a new LeafElt from a supplied key-value pair.
/// Creates a new `LeafElt` from a supplied key-value pair.
fn new(k: K, v: V) -> LeafElt<K, V> {
LeafElt {
key: k,
......@@ -698,7 +694,7 @@ fn new(k: K, v: V) -> LeafElt<K, V> {
}
impl<K: Clone + Ord, V: Clone> Clone for LeafElt<K, V> {
///Returns a new LeafElt by cloning the key and value.
/// Returns a new `LeafElt` by cloning the key and value.
fn clone(&self) -> LeafElt<K, V> {
LeafElt::new(self.key.clone(), self.value.clone())
}
......@@ -719,21 +715,21 @@ fn partial_cmp(&self, other: &LeafElt<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for LeafElt<K, V> {
///Returns an ordering based on the keys of the LeafElts.
/// Returns an ordering based on the keys of the `LeafElt`s.
fn cmp(&self, other: &LeafElt<K, V>) -> Ordering {
self.key.cmp(&other.key)
}
}
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for LeafElt<K, V> {
///Returns a string representation of a LeafElt.
/// Returns a string representation of a `LeafElt`.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key: {}, value: {};", self.key, self.value)
}
}
impl<K: Ord, V> BranchElt<K, V> {
///Creates a new BranchElt from a supplied key, value, and left child.
/// Creates a new `BranchElt` from a supplied key, value, and left child.
fn new(k: K, v: V, n: Box<Node<K, V>>) -> BranchElt<K, V> {
BranchElt {
left: n,
......@@ -745,7 +741,7 @@ fn new(k: K, v: V, n: Box<Node<K, V>>) -> BranchElt<K, V> {
impl<K: Clone + Ord, V: Clone> Clone for BranchElt<K, V> {
///Returns a new BranchElt by cloning the key, value, and left child.
/// Returns a new `BranchElt` by cloning the key, value, and left child.
fn clone(&self) -> BranchElt<K, V> {
BranchElt::new(self.key.clone(),
self.value.clone(),
......@@ -768,15 +764,15 @@ fn partial_cmp(&self, other: &BranchElt<K, V>) -> Option<Ordering> {
}
impl<K: Ord, V: Eq> Ord for BranchElt<K, V> {
///Fulfills Ord for BranchElts
/// Fulfills `Ord` for `BranchElts`.
fn cmp(&self, other: &BranchElt<K, V>) -> Ordering {
self.key.cmp(&other.key)
}
}
impl<K: fmt::Show + Ord, V: fmt::Show> fmt::Show for BranchElt<K, V> {
/// Returns string containing key, value, and child (which should recur to a
/// leaf) Consider changing in future to be more readable.
/// Formats as a string containing the key, value, and child (which should recur to a
/// leaf). Consider changing in future to be more readable.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Key: {}, value: {}, (child: {})",
self.key, self.value, *self.left)
......
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// 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.
//
......@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Container traits for collections
//! Container traits for collections.
#[cfg(test)]
pub mod bench {
......@@ -18,9 +18,9 @@ pub mod bench {
use test::Bencher;
use MutableMap;
pub fn insert_rand_n<M:MutableMap<uint,uint>>(n: uint,
map: &mut M,
b: &mut Bencher) {
pub fn insert_rand_n<M: MutableMap<uint, uint>>(n: uint,
map: &mut M,
b: &mut Bencher) {
// setup
let mut rng = rand::weak_rng();
......@@ -37,9 +37,9 @@ pub fn insert_rand_n<M:MutableMap<uint,uint>>(n: uint,
})
}
pub fn insert_seq_n<M:MutableMap<uint,uint>>(n: uint,
map: &mut M,
b: &mut Bencher) {
pub fn insert_seq_n<M: MutableMap<uint, uint>>(n: uint,
map: &mut M,
b: &mut Bencher) {
// setup
map.clear();
for i in range(0u, n) {
......
......@@ -10,10 +10,10 @@
//! A doubly-linked list with owned nodes.
//!
//! The DList allows pushing and popping elements at either end.
//! The `DList` allows pushing and popping elements at either end.
//!
//! DList implements the trait Deque. It should be imported with `use
//! collections::Deque`.
//! `DList` implements the trait `Deque`. It should be imported with
//! `use collections::Deque`.
// DList is constructed like a singly-linked list over the field `next`.
// including the last link being None; each Node owns its `next` field.
......@@ -49,7 +49,7 @@ struct Node<T> {
value: T,
}
/// Double-ended DList iterator
/// An iterator over references to the items of a `DList`.
pub struct Items<'a, T> {
head: &'a Link<T>,
tail: Rawlink<Node<T>>,
......@@ -61,7 +61,7 @@ impl<'a, T> Clone for Items<'a, T> {
fn clone(&self) -> Items<'a, T> { *self }
}
/// Double-ended mutable DList iterator
/// An iterator over mutable references to the items of a `DList`.
pub struct MutItems<'a, T> {
list: &'a mut DList<T>,
head: Rawlink<Node<T>>,
......@@ -69,7 +69,7 @@ pub struct MutItems<'a, T> {
nelem: uint,
}
/// DList consuming iterator
/// A consuming iterator over the items of a `DList`.
#[deriving(Clone)]
pub struct MoveItems<T> {
list: DList<T>
......@@ -130,12 +130,17 @@ fn link_with_prev<T>(mut next: Box<Node<T>>, prev: Rawlink<Node<T>>)
}
impl<T> Collection for DList<T> {
/// O(1)
/// Returns `true` if the `DList` is empty.
///
/// This operation should compute in O(1) time.
#[inline]
fn is_empty(&self) -> bool {
self.list_head.is_none()
}
/// O(1)
/// Returns the length of the `DList`.
///
/// This operation should compute in O(1) time.
#[inline]
fn len(&self) -> uint {
self.length
......@@ -143,9 +148,9 @@ fn len(&self) -> uint {
}
impl<T> Mutable for DList<T> {
/// Remove all elements from the DList
/// Removes all elements from the `DList`.
///
/// O(N)
/// This operation should compute in O(n) time.
#[inline]
fn clear(&mut self) {
*self = DList::new()
......@@ -213,40 +218,45 @@ fn pop_back_node(&mut self) -> Option<Box<Node<T>>> {
}
impl<T> Deque<T> for DList<T> {
/// Provide a reference to the front element, or None if the list is empty
/// Provides a reference to the front element, or `None` if the list is
/// empty.
#[inline]
fn front<'a>(&'a self) -> Option<&'a T> {
self.list_head.as_ref().map(|head| &head.value)
}
/// Provide a mutable reference to the front element, or None if the list is empty
/// Provides a mutable reference to the front element, or `None` if the list
/// is empty.
#[inline]
fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
self.list_head.as_mut().map(|head| &mut head.value)
}
/// Provide a reference to the back element, or None if the list is empty
/// Provides a reference to the back element, or `None` if the list is
/// empty.
#[inline]
fn back<'a>(&'a self) -> Option<&'a T> {
self.list_tail.resolve_immut().as_ref().map(|tail| &tail.value)
}
/// Provide a mutable reference to the back element, or None if the list is empty
/// Provides a mutable reference to the back element, or `None` if the list
/// is empty.
#[inline]
fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
self.list_tail.resolve().map(|tail| &mut tail.value)
}
/// Add an element first in the list
/// Adds an element first in the list.
///
/// O(1)
/// This operation should compute in O(1) time.
fn push_front(&mut self, elt: T) {
self.push_front_node(box Node::new(elt))
}
/// Remove the first element and return it, or None if the list is empty
/// Removes the first element and returns it, or `None` if the list is
/// empty.
///
/// O(1)
/// This operation should compute in O(1) time.
fn pop_front(&mut self) -> Option<T> {
self.pop_front_node().map(|box Node{value, ..}| value)
}
......@@ -267,15 +277,15 @@ fn default() -> DList<T> { DList::new() }
}
impl<T> DList<T> {
/// Create an empty DList
/// Creates an empty `DList`.
#[inline]
pub fn new() -> DList<T> {
DList{list_head: None, list_tail: Rawlink::none(), length: 0}
}
/// Move the last element to the front of the list.
/// Moves the last element to the front of the list.
///
/// If the list is empty, do nothing.
/// If the list is empty, does nothing.
///
/// # Example
///
......@@ -300,9 +310,9 @@ pub fn rotate_forward(&mut self) {
});
}
/// Move the first element to the back of the list.
/// Moves the first element to the back of the list.
///
/// If the list is empty, do nothing.
/// If the list is empty, does nothing.
///
/// # Example
///
......@@ -327,9 +337,9 @@ pub fn rotate_backward(&mut self) {
});
}
/// Add all elements from `other` to the end of the list
/// Adds all elements from `other` to the end of the list.
///
/// O(1)
/// This operation should compute in O(1) time.
///
/// # Example
///
......@@ -368,9 +378,9 @@ pub fn append(&mut self, mut other: DList<T>) {
}
}
/// Add all elements from `other` to the beginning of the list
/// Adds all elements from `other` to the beginning of the list.
///
/// O(1)
/// This operation should compute in O(1) time.
///
/// # Example
///
......@@ -396,10 +406,10 @@ pub fn prepend(&mut self, mut other: DList<T>) {
self.append(other);
}
/// Insert `elt` before the first `x` in the list where `f(x, elt)` is true,
/// or at the end.
/// Inserts `elt` before the first `x` in the list where `f(x, elt)` is
/// true, or at the end.
///
/// O(N)
/// This operation should compute in O(N) time.
///
/// # Example
///
......@@ -433,11 +443,12 @@ pub fn insert_when(&mut self, elt: T, f: |&T, &T| -> bool) {
}
}
/// Merge DList `other` into this DList, using the function `f`.
/// Iterate the both DList with `a` from self and `b` from `other`, and
/// put `a` in the result if `f(a, b)` is true, else `b`.
/// Merges `other` into this `DList`, using the function `f`.
///
/// Iterates both `DList`s with `a` from self and `b` from `other`, and
/// put `a` in the result if `f(a, b)` is true, and otherwise `b`.
///
/// O(max(N, M))
/// This operation should compute in O(max(N, M)) time.
pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
{
let mut it = self.mut_iter();
......@@ -458,13 +469,13 @@ pub fn merge(&mut self, mut other: DList<T>, f: |&T, &T| -> bool) {
}
/// Provide a forward iterator
/// Provides a forward iterator.
#[inline]
pub fn iter<'a>(&'a self) -> Items<'a, T> {
Items{nelem: self.len(), head: &self.list_head, tail: self.list_tail}
}
/// Provide a forward iterator with mutable references
/// Provides a forward iterator with mutable references.
#[inline]
pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
let head_raw = match self.list_head {
......@@ -480,7 +491,7 @@ pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
}
/// Consume the list into an iterator yielding elements by value
/// Consumes the list into an iterator yielding elements by value.
#[inline]
pub fn move_iter(self) -> MoveItems<T> {
MoveItems{list: self}
......@@ -488,9 +499,9 @@ pub fn move_iter(self) -> MoveItems<T> {
}
impl<T: Ord> DList<T> {
/// Insert `elt` sorted in ascending order
/// Inserts `elt` sorted in ascending order.
///
/// O(N)
/// This operation should compute in O(N) time.
#[inline]
pub fn insert_ordered(&mut self, elt: T) {
self.insert_when(elt, |a, b| a >= b)
......@@ -593,14 +604,15 @@ fn next_back(&mut self) -> Option<&'a mut A> {
impl<'a, A> ExactSize<&'a mut A> for MutItems<'a, A> {}
/// Allow mutating the DList while iterating
/// Allows mutating a `DList` while iterating.
pub trait ListInsertion<A> {
/// Insert `elt` just after to the element most recently returned by `.next()`
/// Inserts `elt` just after to the element most recently returned by
/// `.next()`
///
/// The inserted element does not appear in the iteration.
fn insert_next(&mut self, elt: A);
/// Provide a reference to the next element, without changing the iterator
/// Provides a reference to the next element, without changing the iterator
fn peek_next<'a>(&'a mut self) -> Option<&'a mut A>;
}
......
......@@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A structure for holding a set of enum variants
//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.
......@@ -16,7 +16,7 @@
use core::prelude::*;
#[deriving(Clone, PartialEq, Eq, Hash, Show)]
/// A specialized Set implementation to use enum types.
/// A specialized `Set` implementation to use enum types.
pub struct EnumSet<E> {
// We must maintain the invariant that no bits are set
// for which no variant exists
......@@ -25,9 +25,9 @@ pub struct EnumSet<E> {
/// An interface for casting C-like enum to uint and back.
pub trait CLike {
/// Converts C-like enum to uint.
/// Converts a C-like enum to a `uint`.
fn to_uint(&self) -> uint;
/// Converts uint to C-like enum.
/// Converts a `uint` to a C-like enum.
fn from_uint(uint) -> Self;
}
......@@ -36,47 +36,47 @@ fn bit<E:CLike>(e: E) -> uint {
}
impl<E:CLike> EnumSet<E> {
/// Returns an empty EnumSet.
/// Returns an empty `EnumSet`.
pub fn empty() -> EnumSet<E> {
EnumSet {bits: 0}
}
/// Returns true if an EnumSet is empty.
/// Returns true if the `EnumSet` is empty.
pub fn is_empty(&self) -> bool {
self.bits == 0
}
/// Returns true if an EnumSet contains any enum of a given EnumSet
/// Returns `true` if the `EnumSet` contains any enum of the given `EnumSet`.
pub fn intersects(&self, e: EnumSet<E>) -> bool {
(self.bits & e.bits) != 0
}
/// Returns an intersection of both EnumSets.
/// Returns the intersection of both `EnumSets`.
pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits & e.bits}
}
/// Returns true if a given EnumSet is included in an EnumSet.
/// Returns `true` if a given `EnumSet` is included in an `EnumSet`.
pub fn contains(&self, e: EnumSet<E>) -> bool {
(self.bits & e.bits) == e.bits
}
/// Returns a union of both EnumSets.
/// Returns the union of both `EnumSets`.
pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
EnumSet {bits: self.bits | e.bits}
}
/// Add an enum to an EnumSet
/// Adds an enum to an `EnumSet`.
pub fn add(&mut self, e: E) {
self.bits |= bit(e);
}
/// Returns true if an EnumSet contains a given enum
/// Returns `true` if an `EnumSet` contains a given enum.
pub fn contains_elem(&self, e: E) -> bool {
(self.bits & bit(e)) != 0
}
/// Returns an iterator over an EnumSet
/// Returns an iterator over an `EnumSet`.
pub fn iter(&self) -> Items<E> {
Items::new(self.bits)
}
......
......@@ -77,18 +77,18 @@
pub mod sip;
/// A trait that represents a hashable type. The `S` type parameter is an
/// abstract hash state that is used by the `Hash` to compute the hash.
/// It defaults to `std::hash::sip::SipState`.
/// A hashable type. The `S` type parameter is an abstract hash state that is
/// used by the `Hash` to compute the hash. It defaults to
/// `std::hash::sip::SipState`.
pub trait Hash<S = sip::SipState> {
/// Compute a hash of the value.
/// Computes the hash of a value.
fn hash(&self, state: &mut S);
}
/// A trait that computes a hash for a value. The main users of this trait are
/// containers like `HashMap`, which need a generic way hash multiple types.
pub trait Hasher<S> {
/// Compute a hash of the value.
/// Compute the hash of a value.
fn hash<T: Hash<S>>(&self, value: &T) -> u64;
}
......
......@@ -10,21 +10,19 @@
//
// ignore-lexer-test FIXME #15883
/*!
* Implementation of SipHash 2-4
*
* See: http://131002.net/siphash/
*
* Consider this as a main "general-purpose" hash for all hashtables: it
* runs at good speed (competitive with spooky and city) and permits
* strong _keyed_ hashing. Key your hashtables from a strong RNG,
* such as `rand::Rng`.
*
* Although the SipHash algorithm is considered to be cryptographically
* strong, this implementation has not been reviewed for such purposes.
* As such, all cryptographic uses of this implementation are strongly
* discouraged.
*/
//! An implementation of SipHash 2-4.
//!
//! See: http://131002.net/siphash/
//!
//! Consider this as a main "general-purpose" hash for all hashtables: it
//! runs at good speed (competitive with spooky and city) and permits
//! strong _keyed_ hashing. Key your hashtables from a strong RNG,
//! such as `rand::Rng`.
//!
//! Although the SipHash algorithm is considered to be cryptographically
//! strong, this implementation has not been reviewed for such purposes.
//! As such, all cryptographic uses of this implementation are strongly
//! discouraged.
use core::prelude::*;
......@@ -89,13 +87,13 @@ pub struct SipState {
)
impl SipState {
/// Create a `SipState` that is keyed off the provided keys.
/// Creates a `SipState` that is keyed off the provided keys.
#[inline]
pub fn new() -> SipState {
SipState::new_with_keys(0, 0)
}
/// Create a `SipState` that is keyed off the provided keys.
/// Creates a `SipState` that is keyed off the provided keys.
#[inline]
pub fn new_with_keys(key0: u64, key1: u64) -> SipState {
let mut state = SipState {
......@@ -113,7 +111,7 @@ pub fn new_with_keys(key0: u64, key1: u64) -> SipState {
state
}
/// Reset the state back to it's initial state.
/// Resets the state to its initial state.
#[inline]
pub fn reset(&mut self) {
self.length = 0;
......@@ -124,7 +122,7 @@ pub fn reset(&mut self) {
self.ntail = 0;
}
/// Return the computed hash.
/// Returns the computed hash.
#[inline]
pub fn result(&self) -> u64 {
let mut v0 = self.v0;
......@@ -219,13 +217,13 @@ pub struct SipHasher {
}
impl SipHasher {
/// Create a `Sip`.
/// Creates a `Sip`.
#[inline]
pub fn new() -> SipHasher {
SipHasher::new_with_keys(0, 0)
}
/// Create a `Sip` that is keyed off the provided keys.
/// Creates a `Sip` that is keyed off the provided keys.
#[inline]
pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher {
SipHasher {
......@@ -251,7 +249,7 @@ fn default() -> SipHasher {
}
}
/// Hash a value using the SipHash algorithm.
/// Hashes a value using the SipHash algorithm.
#[inline]
pub fn hash<T: Hash<SipState>>(value: &T) -> u64 {
let mut state = SipState::new();
......@@ -259,7 +257,7 @@ pub fn hash<T: Hash<SipState>>(value: &T) -> u64 {
state.result()
}
/// Hash a value with the SipHash algorithm with the provided keys.
/// Hashes a value with the SipHash algorithm with the provided keys.
#[inline]
pub fn hash_with_keys<T: Hash<SipState>>(k0: u64, k1: u64, value: &T) -> u64 {
let mut state = SipState::new_with_keys(k0, k1);
......
......@@ -8,9 +8,7 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Collection types.
*/
//! Collection types.
#![crate_name = "collections"]
#![experimental]
......@@ -73,9 +71,9 @@
mod deque;
/// A trait to represent mutable containers
/// A mutable container type.
pub trait Mutable: Collection {
/// Clear the container, removing all values.
/// Clears the container, removing all values.
///
/// # Example
///
......@@ -87,10 +85,10 @@ pub trait Mutable: Collection {
fn clear(&mut self);
}
/// A map is a key-value store where values may be looked up by their keys. This
/// trait provides basic operations to operate on these stores.
/// A key-value store where values may be looked up by their keys. This trait
/// provides basic operations to operate on these stores.
pub trait Map<K, V>: Collection {
/// Return a reference to the value corresponding to the key.
/// Returns a reference to the value corresponding to the key.
///
/// # Example
///
......@@ -104,7 +102,7 @@ pub trait Map<K, V>: Collection {
/// ```
fn find<'a>(&'a self, key: &K) -> Option<&'a V>;
/// Return true if the map contains a value for the specified key.
/// Returns true if the map contains a value for the specified key.
///
/// # Example
///
......@@ -122,10 +120,10 @@ fn contains_key(&self, key: &K) -> bool {
}
}
/// This trait provides basic operations to modify the contents of a map.
/// A key-value store (map) where the values can be modified.
pub trait MutableMap<K, V>: Map<K, V> + Mutable {
/// Insert a key-value pair into the map. An existing value for a
/// key is replaced by the new value. Return true if the key did
/// Inserts a key-value pair into the map. An existing value for a
/// key is replaced by the new value. Returns `true` if the key did
/// not already exist in the map.
///
/// # Example
......@@ -143,8 +141,8 @@ fn insert(&mut self, key: K, value: V) -> bool {
self.swap(key, value).is_none()
}
/// Remove a key-value pair from the map. Return true if the key
/// was present in the map, otherwise false.
/// Removes a key-value pair from the map. Returns `true` if the key
/// was present in the map.
///
/// # Example
///
......@@ -161,8 +159,9 @@ fn remove(&mut self, key: &K) -> bool {
self.pop(key).is_some()
}
/// Insert a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise None is returned.
/// Inserts a key-value pair into the map. If the key already had a value
/// present in the map, that value is returned. Otherwise, `None` is
/// returned.
///
/// # Example
///
......@@ -194,7 +193,7 @@ fn remove(&mut self, key: &K) -> bool {
/// ```
fn pop(&mut self, k: &K) -> Option<V>;
/// Return a mutable reference to the value corresponding to the key.
/// Returns a mutable reference to the value corresponding to the key.
///
/// # Example
///
......@@ -212,11 +211,11 @@ fn remove(&mut self, key: &K) -> bool {
fn find_mut<'a>(&'a mut self, key: &K) -> Option<&'a mut V>;
}
/// A set is a group of objects which are each distinct from one another. This
/// A group of objects which are each distinct from one another. This
/// trait represents actions which can be performed on sets to iterate over
/// them.
pub trait Set<T>: Collection {
/// Return true if the set contains a value.
/// Returns `true` if the set contains a value.
///
/// # Example
///
......@@ -229,7 +228,7 @@ pub trait Set<T>: Collection {
/// ```
fn contains(&self, value: &T) -> bool;
/// Return true if the set has no elements in common with `other`.
/// Returns `true` if the set has no elements in common with `other`.
/// This is equivalent to checking for an empty intersection.
///
/// # Example
......@@ -248,7 +247,7 @@ pub trait Set<T>: Collection {
/// ```
fn is_disjoint(&self, other: &Self) -> bool;
/// Return true if the set is a subset of another.
/// Returns `true` if the set is a subset of another.
///
/// # Example
///
......@@ -266,7 +265,7 @@ pub trait Set<T>: Collection {
/// ```
fn is_subset(&self, other: &Self) -> bool;
/// Return true if the set is a superset of another.
/// Returns `true` if the set is a superset of another.
///
/// # Example
///
......@@ -292,10 +291,10 @@ fn is_superset(&self, other: &Self) -> bool {
// FIXME #8154: Add difference, sym. difference, intersection and union iterators
}
/// This trait represents actions which can be performed on sets to mutate
/// them.
/// A mutable collection of values which are distinct from one another that
/// can be mutaed.
pub trait MutableSet<T>: Set<T> + Mutable {
/// Add a value to the set. Return true if the value was not already
/// Adds a value to the set. Returns `true` if the value was not already
/// present in the set.
///
/// # Example
......@@ -311,7 +310,7 @@ pub trait MutableSet<T>: Set<T> + Mutable {
/// ```
fn insert(&mut self, value: T) -> bool;
/// Remove a value from the set. Return true if the value was
/// Removes a value from the set. Returns `true` if the value was
/// present in the set.
///
/// # Example
......@@ -329,7 +328,7 @@ pub trait MutableSet<T>: Set<T> + Mutable {
}
pub trait MutableSeq<T>: Mutable {
/// Append an element to the back of a collection.
/// Appends an element to the back of a collection.
///
/// # Example
///
......@@ -339,8 +338,9 @@ pub trait MutableSeq<T>: Mutable {
/// assert_eq!(vec, vec!(1, 2, 3));
/// ```
fn push(&mut self, t: T);
/// Remove the last element from a collection and return it, or `None` if it is
/// empty.
/// Removes the last element from a collection and returns it, or `None` if
/// it is empty.
///
/// # Example
///
......@@ -412,7 +412,7 @@ pub trait MutableSeq<T>: Mutable {
/// }
/// ```
pub trait Deque<T> : MutableSeq<T> {
/// Provide a reference to the front element, or `None` if the sequence is
/// Provides a reference to the front element, or `None` if the sequence is
/// empty.
///
/// # Example
......@@ -429,7 +429,7 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn front<'a>(&'a self) -> Option<&'a T>;
/// Provide a mutable reference to the front element, or `None` if the
/// Provides a mutable reference to the front element, or `None` if the
/// sequence is empty.
///
/// # Example
......@@ -450,7 +450,7 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn front_mut<'a>(&'a mut self) -> Option<&'a mut T>;
/// Provide a reference to the back element, or `None` if the sequence is
/// Provides a reference to the back element, or `None` if the sequence is
/// empty.
///
/// # Example
......@@ -467,8 +467,8 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn back<'a>(&'a self) -> Option<&'a T>;
/// Provide a mutable reference to the back element, or `None` if the sequence
/// is empty.
/// Provides a mutable reference to the back element, or `None` if the
/// sequence is empty.
///
/// # Example
///
......@@ -488,7 +488,7 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn back_mut<'a>(&'a mut self) -> Option<&'a mut T>;
/// Insert an element first in the sequence.
/// Inserts an element first in the sequence.
///
/// # Example
///
......@@ -502,7 +502,7 @@ pub trait Deque<T> : MutableSeq<T> {
/// ```
fn push_front(&mut self, elt: T);
/// Insert an element last in the sequence.
/// Inserts an element last in the sequence.
///
/// # Example
///
......@@ -517,7 +517,8 @@ pub trait Deque<T> : MutableSeq<T> {
#[deprecated = "use the `push` method"]
fn push_back(&mut self, elt: T) { self.push(elt) }
/// Remove the last element and return it, or `None` if the sequence is empty.
/// Removes the last element and returns it, or `None` if the sequence is
/// empty.
///
/// # Example
///
......@@ -535,7 +536,8 @@ fn push_back(&mut self, elt: T) { self.push(elt) }
#[deprecated = "use the `pop` method"]
fn pop_back(&mut self) -> Option<T> { self.pop() }
/// Remove the first element and return it, or `None` if the sequence is empty.
/// Removes the first element and returns it, or `None` if the sequence is
/// empty.
///
/// # Example
///
......
......@@ -10,7 +10,7 @@
#![macro_escape]
/// Create a `std::vec::Vec` containing the arguments.
/// Creates a `std::vec::Vec` containing the arguments.
macro_rules! vec(
($($e:expr),*) => ({
// leading _ to allow empty construction without a warning.
......
......@@ -167,12 +167,12 @@ pub struct PriorityQueue<T> {
}
impl<T: Ord> Collection for PriorityQueue<T> {
/// Returns the length of the queue
/// Returns the length of the queue.
fn len(&self) -> uint { self.data.len() }
}
impl<T: Ord> Mutable for PriorityQueue<T> {
/// Drop all items from the queue
/// Drops all items from the queue.
fn clear(&mut self) { self.data.truncate(0) }
}
......@@ -182,7 +182,7 @@ fn default() -> PriorityQueue<T> { PriorityQueue::new() }
}
impl<T: Ord> PriorityQueue<T> {
/// Create an empty PriorityQueue as a max-heap.
/// Creates an empty `PriorityQueue` as a max-heap.
///
/// # Example
///
......@@ -192,9 +192,9 @@ impl<T: Ord> PriorityQueue<T> {
/// ```
pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }
/// Create an empty PriorityQueue with a specific capacity.
/// Creates an empty `PriorityQueue` with a specific capacity.
/// This preallocates enough memory for `capacity` elements,
/// so that the PriorityQueue does not have to be reallocated
/// so that the `PriorityQueue` does not have to be reallocated
/// until it contains at least that many values.
///
/// # Example
......@@ -207,7 +207,7 @@ pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
PriorityQueue { data: Vec::with_capacity(capacity) }
}
/// Create a PriorityQueue from a vector. This is sometimes called
/// Creates a `PriorityQueue` from a vector. This is sometimes called
/// `heapifying` the vector.
///
/// # Example
......@@ -244,7 +244,7 @@ pub fn iter<'a>(&'a self) -> Items<'a, T> {
Items { iter: self.data.iter() }
}
/// Returns the greatest item in a queue or `None` if it is empty.
/// Returns the greatest item in a queue, or `None` if it is empty.
///
/// # Example
///
......@@ -279,7 +279,7 @@ pub fn maybe_top<'a>(&'a self) -> Option<&'a T> { self.top() }
/// ```
pub fn capacity(&self) -> uint { self.data.capacity() }
/// Reserve capacity for exactly `n` elements in the PriorityQueue.
/// Reserves capacity for exactly `n` elements in the `PriorityQueue`.
/// Do nothing if the capacity is already sufficient.
///
/// # Example
......@@ -293,7 +293,7 @@ pub fn capacity(&self) -> uint { self.data.capacity() }
/// ```
pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }
/// Reserve capacity for at least `n` elements in the PriorityQueue.
/// Reserves capacity for at least `n` elements in the `PriorityQueue`.
/// Do nothing if the capacity is already sufficient.
///
/// # Example
......@@ -309,8 +309,8 @@ pub fn reserve(&mut self, n: uint) {
self.data.reserve(n)
}
/// Remove the greatest item from a queue and return it, or `None` if it is
/// empty.
/// Removes the greatest item from a queue and returns it, or `None` if it
/// is empty.
///
/// # Example
///
......@@ -339,7 +339,7 @@ pub fn pop(&mut self) -> Option<T> {
#[deprecated="renamed to `pop`"]
pub fn maybe_pop(&mut self) -> Option<T> { self.pop() }
/// Push an item onto the queue.
/// Pushes an item onto the queue.
///
/// # Example
///
......@@ -360,7 +360,8 @@ pub fn push(&mut self, item: T) {
self.siftup(0, new_len);
}
/// Optimized version of a push followed by a pop.
/// Pushes an item onto a queue then pops the greatest item off the queue in
/// an optimized fashion.
///
/// # Example
///
......@@ -384,8 +385,9 @@ pub fn push_pop(&mut self, mut item: T) -> T {
item
}
/// Optimized version of a pop followed by a push. The push is done
/// regardless of whether the queue is empty.
/// Pops the greatest item off a queue then pushes an item onto the queue in
/// an optimized fashion. The push is done regardless of whether the queue
/// was empty.
///
/// # Example
///
......@@ -418,7 +420,7 @@ fn to_vec(self) -> Vec<T> { self.into_vec() }
#[deprecated="renamed to `into_sorted_vec`"]
fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
/// Consume the PriorityQueue and return the underlying vector
/// Consumes the `PriorityQueue` and returns the underlying vector
/// in arbitrary order.
///
/// # Example
......@@ -436,7 +438,7 @@ fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }
/// ```
pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }
/// Consume the PriorityQueue and return a vector in sorted
/// Consumes the `PriorityQueue` and returns a vector in sorted
/// (ascending) order.
///
/// # Example
......@@ -513,7 +515,7 @@ fn siftdown(&mut self, pos: uint) {
}
}
/// PriorityQueue iterator.
/// `PriorityQueue` iterator.
pub struct Items <'a, T> {
iter: slice::Items<'a, T>,
}
......
......@@ -8,10 +8,10 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A double-ended queue implemented as a circular buffer
//! A double-ended queue implemented as a circular buffer.
//!
//! RingBuf implements the trait Deque. It should be imported with `use
//! collections::Deque`.
//! `RingBuf` implements the trait `Deque`. It should be imported with
//! `use collections::Deque`.
use core::prelude::*;
......@@ -27,7 +27,7 @@
static INITIAL_CAPACITY: uint = 8u; // 2^3
static MINIMUM_CAPACITY: uint = 2u;
/// RingBuf is a circular buffer that implements Deque.
/// `RingBuf` is a circular buffer that implements `Deque`.
#[deriving(Clone)]
pub struct RingBuf<T> {
nelts: uint,
......@@ -36,12 +36,12 @@ pub struct RingBuf<T> {
}
impl<T> Collection for RingBuf<T> {
/// Return the number of elements in the RingBuf
/// Returns the number of elements in the `RingBuf`.
fn len(&self) -> uint { self.nelts }
}
impl<T> Mutable for RingBuf<T> {
/// Clear the RingBuf, removing all values.
/// Clears the `RingBuf`, removing all values.
fn clear(&mut self) {
for x in self.elts.mut_iter() { *x = None }
self.nelts = 0;
......@@ -50,28 +50,29 @@ fn clear(&mut self) {
}
impl<T> Deque<T> for RingBuf<T> {
/// Return a reference to the first element in the RingBuf
/// Returns a reference to the first element in the `RingBuf`.
fn front<'a>(&'a self) -> Option<&'a T> {
if self.nelts > 0 { Some(&self[0]) } else { None }
}
/// Return a mutable reference to the first element in the RingBuf
/// Returns a mutable reference to the first element in the `RingBuf`.
fn front_mut<'a>(&'a mut self) -> Option<&'a mut T> {
if self.nelts > 0 { Some(self.get_mut(0)) } else { None }
}
/// Return a reference to the last element in the RingBuf
/// Returns a reference to the last element in the `RingBuf`.
fn back<'a>(&'a self) -> Option<&'a T> {
if self.nelts > 0 { Some(&self[self.nelts - 1]) } else { None }
}
/// Return a mutable reference to the last element in the RingBuf
/// Returns a mutable reference to the last element in the `RingBuf`.
fn back_mut<'a>(&'a mut self) -> Option<&'a mut T> {
let nelts = self.nelts;
if nelts > 0 { Some(self.get_mut(nelts - 1)) } else { None }
}
/// Remove and return the first element in the RingBuf, or None if it is empty
/// Removes and returns the first element in the `RingBuf`, or `None` if it
/// is empty.
fn pop_front(&mut self) -> Option<T> {
let result = self.elts.get_mut(self.lo).take();
if result.is_some() {
......@@ -81,7 +82,7 @@ fn pop_front(&mut self) -> Option<T> {
result
}
/// Prepend an element to the RingBuf
/// Prepends an element to the `RingBuf`.
fn push_front(&mut self, t: T) {
if self.nelts == self.elts.len() {
grow(self.nelts, &mut self.lo, &mut self.elts);
......@@ -120,20 +121,20 @@ fn default() -> RingBuf<T> { RingBuf::new() }
}
impl<T> RingBuf<T> {
/// Create an empty RingBuf
/// Creates an empty `RingBuf`.
pub fn new() -> RingBuf<T> {
RingBuf::with_capacity(INITIAL_CAPACITY)
}
/// Create an empty RingBuf with space for at least `n` elements.
/// Creates an empty `RingBuf` with space for at least `n` elements.
pub fn with_capacity(n: uint) -> RingBuf<T> {
RingBuf{nelts: 0, lo: 0,
elts: Vec::from_fn(cmp::max(MINIMUM_CAPACITY, n), |_| None)}
}
/// Retrieve an element in the RingBuf by index
/// Retrieva an element in the `RingBuf` by index.
///
/// Fails if there is no element with the given index
/// Fails if there is no element with the given index.
///
/// # Example
///
......@@ -157,9 +158,9 @@ pub fn get<'a>(&'a self, i: uint) -> &'a T {
}
}
/// Retrieve an element in the RingBuf by index
/// Retrieves an element in the `RingBuf` by index.
///
/// Fails if there is no element with the given index
/// Fails if there is no element with the given index.
///
/// # Example
///
......@@ -181,11 +182,11 @@ pub fn get_mut<'a>(&'a mut self, i: uint) -> &'a mut T {
}
}
/// Swap elements at indices `i` and `j`
/// Swaps elements at indices `i` and `j`.
///
/// `i` and `j` may be equal.
///
/// Fails if there is no element with the given index
/// Fails if there is no element with either index.
///
/// # Example
///
......@@ -208,37 +209,30 @@ pub fn swap(&mut self, i: uint, j: uint) {
self.elts.as_mut_slice().swap(ri, rj);
}
/// Return index in underlying vec for a given logical element index
/// Returns the index in the underlying `Vec` for a given logical element
/// index.
fn raw_index(&self, idx: uint) -> uint {
raw_index(self.lo, self.elts.len(), idx)
}
/// Reserve capacity for exactly `n` elements in the given RingBuf,
/// Reserves capacity for exactly `n` elements in the given `RingBuf`,
/// doing nothing if `self`'s capacity is already equal to or greater
/// than the requested capacity
///
/// # Arguments
///
/// * n - The number of elements to reserve space for
/// than the requested capacity.
pub fn reserve_exact(&mut self, n: uint) {
self.elts.reserve_exact(n);
}
/// Reserve capacity for at least `n` elements in the given RingBuf,
/// Reserves capacity for at least `n` elements in the given `RingBuf`,
/// over-allocating in case the caller needs to reserve additional
/// space.
///
/// Do nothing if `self`'s capacity is already equal to or greater
/// than the requested capacity.
///
/// # Arguments
///
/// * n - The number of elements to reserve space for
pub fn reserve(&mut self, n: uint) {
self.elts.reserve(n);
}
/// Front-to-back iterator.
/// Returns a front-to-back iterator.
///
/// # Example
///
......@@ -255,7 +249,7 @@ pub fn iter<'a>(&'a self) -> Items<'a, T> {
Items{index: 0, rindex: self.nelts, lo: self.lo, elts: self.elts.as_slice()}
}
/// Front-to-back iterator which returns mutable values.
/// Returns a front-to-back iterator which returns mutable references.
///
/// # Example
///
......@@ -297,7 +291,7 @@ pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a, T> {
}
}
/// RingBuf iterator
/// `RingBuf` iterator.
pub struct Items<'a, T> {
lo: uint,
index: uint,
......@@ -352,7 +346,7 @@ fn idx(&mut self, j: uint) -> Option<&'a T> {
}
}
/// RingBuf mutable iterator
/// `RingBuf` mutable iterator.
pub struct MutItems<'a, T> {
remaining1: &'a mut [Option<T>],
remaining2: &'a mut [Option<T>],
......@@ -437,7 +431,7 @@ fn grow<T>(nelts: uint, loptr: &mut uint, elts: &mut Vec<Option<T>>) {
}
}
/// Return index in underlying vec for a given logical element index
/// Returns the index in the underlying `Vec` for a given logical element index.
fn raw_index(lo: uint, len: uint, index: uint) -> uint {
if lo >= len - index {
lo + index - len
......
......@@ -8,81 +8,77 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Utilities for slice manipulation
The `slice` module contains useful code to help work with slice values.
Slices are a view into a block of memory represented as a pointer and a length.
```rust
// slicing a Vec
let vec = vec!(1i, 2, 3);
let int_slice = vec.as_slice();
// coercing an array to a slice
let str_slice: &[&str] = ["one", "two", "three"];
```
Slices are either mutable or shared. The shared slice type is `&[T]`,
while the mutable slice type is `&mut[T]`. For example, you can mutate the
block of memory that a mutable slice points to:
```rust
let x: &mut[int] = [1i, 2, 3];
x[1] = 7;
assert_eq!(x[0], 1);
assert_eq!(x[1], 7);
assert_eq!(x[2], 3);
```
Here are some of the things this module contains:
## Structs
There are several structs that are useful for slices, such as `Items`, which
represents iteration over a slice.
## Traits
A number of traits add methods that allow you to accomplish tasks with slices.
These traits include `ImmutableSlice`, which is defined for `&[T]` types,
and `MutableSlice`, defined for `&mut [T]` types.
An example is the method `.slice(a, b)` that returns an immutable "view" into
a `Vec` or another slice from the index interval `[a, b)`:
```rust
let numbers = [0i, 1i, 2i];
let last_numbers = numbers.slice(1, 3);
// last_numbers is now &[1i, 2i]
```
## Implementations of other traits
There are several implementations of common traits for slices. Some examples
include:
* `Clone`
* `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
* `Hash` - for slices whose element type is `Hash`
## Iteration
The method `iter()` returns an iteration value for a slice. The iterator
yields references to the slice's elements, so if the element
type of the slice is `int`, the element type of the iterator is `&int`.
```rust
let numbers = [0i, 1i, 2i];
for &x in numbers.iter() {
println!("{} is a number!", x);
}
```
* `.mut_iter()` returns an iterator that allows modifying each value.
* Further iterators exist that split, chunk or permute the slice.
*/
//! Utilities for slice manipulation
//!
//! The `slice` module contains useful code to help work with slice values.
//! Slices are a view into a block of memory represented as a pointer and a length.
//!
//! ```rust
//! // slicing a Vec
//! let vec = vec!(1i, 2, 3);
//! let int_slice = vec.as_slice();
//! // coercing an array to a slice
//! let str_slice: &[&str] = ["one", "two", "three"];
//! ```
//!
//! Slices are either mutable or shared. The shared slice type is `&[T]`,
//! while the mutable slice type is `&mut[T]`. For example, you can mutate the
//! block of memory that a mutable slice points to:
//!
//! ```rust
//! let x: &mut[int] = [1i, 2, 3];
//! x[1] = 7;
//! assert_eq!(x[0], 1);
//! assert_eq!(x[1], 7);
//! assert_eq!(x[2], 3);
//! ```
//!
//! Here are some of the things this module contains:
//!
//! ## Structs
//!
//! There are several structs that are useful for slices, such as `Items`, which
//! represents iteration over a slice.
//!
//! ## Traits
//!
//! A number of traits add methods that allow you to accomplish tasks with slices.
//! These traits include `ImmutableSlice`, which is defined for `&[T]` types,
//! and `MutableSlice`, defined for `&mut [T]` types.
//!
//! An example is the method `.slice(a, b)` that returns an immutable "view" into
//! a `Vec` or another slice from the index interval `[a, b)`:
//!
//! ```rust
//! let numbers = [0i, 1i, 2i];
//! let last_numbers = numbers.slice(1, 3);
//! // last_numbers is now &[1i, 2i]
//! ```
//!
//! ## Implementations of other traits
//!
//! There are several implementations of common traits for slices. Some examples
//! include:
//!
//! * `Clone`
//! * `Eq`, `Ord` - for immutable slices whose element type are `Eq` or `Ord`.
//! * `Hash` - for slices whose element type is `Hash`
//!
//! ## Iteration
//!
//! The method `iter()` returns an iteration value for a slice. The iterator
//! yields references to the slice's elements, so if the element
//! type of the slice is `int`, the element type of the iterator is `&int`.
//!
//! ```rust
//! let numbers = [0i, 1i, 2i];
//! for &x in numbers.iter() {
//! println!("{} is a number!", x);
//! }
//! ```
//!
//! * `.mut_iter()` returns an iterator that allows modifying each value.
//! * Further iterators exist that split, chunk or permute the slice.
#![doc(primitive = "slice")]
......@@ -109,7 +105,7 @@
pub trait VectorVector<T> {
// FIXME #5898: calling these .concat and .connect conflicts with
// StrVector::con{cat,nect}, since they have generic contents.
/// Flattens a vector of vectors of T into a single vector of T.
/// Flattens a vector of vectors of `T` into a single `Vec<T>`.
fn concat_vec(&self) -> Vec<T>;
/// Concatenate a vector of vectors, placing a given separator between each.
......@@ -138,7 +134,7 @@ fn connect_vec(&self, sep: &T) -> Vec<T> {
}
}
/// An Iterator that yields the element swaps needed to produce
/// An iterator that yields the element swaps needed to produce
/// a sequence of all possible permutations for an indexed sequence of
/// elements. Each permutation is only a single swap apart.
///
......@@ -150,13 +146,14 @@ fn connect_vec(&self, sep: &T) -> Vec<T> {
/// sequence to its initial order.
pub struct ElementSwaps {
sdir: Vec<SizeDirection>,
/// If true, emit the last swap that returns the sequence to initial state
/// If `true`, emit the last swap that returns the sequence to initial
/// state.
emit_reset: bool,
swaps_made : uint,
}
impl ElementSwaps {
/// Create an `ElementSwaps` iterator for a sequence of `length` elements
/// Creates an `ElementSwaps` iterator for a sequence of `length` elements.
pub fn new(length: uint) -> ElementSwaps {
// Initialize `sdir` with a direction that position should move in
// (all negative at the beginning) and the `size` of the
......@@ -171,7 +168,7 @@ pub fn new(length: uint) -> ElementSwaps {
enum Direction { Pos, Neg }
/// An Index and Direction together
/// An `Index` and `Direction` together.
struct SizeDirection {
size: uint,
dir: Direction,
......@@ -229,7 +226,7 @@ fn size_hint(&self) -> (uint, Option<uint>) {
}
}
/// An Iterator that uses `ElementSwaps` to iterate through
/// An iterator that uses `ElementSwaps` to iterate through
/// all possible permutations of a vector.
///
/// The first iteration yields a clone of the vector as it is,
......@@ -264,16 +261,16 @@ fn size_hint(&self) -> (uint, Option<uint>) {
/// Extension methods for vector slices with cloneable elements
pub trait CloneableVector<T> {
/// Copy `self` into a new vector
/// Copies `self` into a new `Vec`.
fn to_vec(&self) -> Vec<T>;
/// Deprecated. Use `to_vec`
/// Deprecated. Use `to_vec`.
#[deprecated = "Replaced by `to_vec`"]
fn to_owned(&self) -> Vec<T> {
self.to_vec()
}
/// Convert `self` into an owned vector, not making a copy if possible.
/// Converts `self` into an owned vector, not making a copy if possible.
fn into_vec(self) -> Vec<T>;
/// Deprecated. Use `into_vec`
......@@ -283,7 +280,6 @@ fn into_owned(self) -> Vec<T> {
}
}
/// Extension methods for vector slices
impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
/// Returns a copy of `v`.
#[inline]
......@@ -295,11 +291,11 @@ fn into_vec(self) -> Vec<T> { self.to_vec() }
/// Extension methods for vectors containing `Clone` elements.
pub trait ImmutableCloneableVector<T> {
/// Partitions the vector into two vectors `(A,B)`, where all
/// elements of `A` satisfy `f` and all elements of `B` do not.
/// Partitions the vector into two vectors `(a, b)`, where all
/// elements of `a` satisfy `f` and all elements of `b` do not.
fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
/// Create an iterator that yields every possible permutation of the
/// Creates an iterator that yields every possible permutation of the
/// vector in succession.
///
/// # Example
......@@ -559,7 +555,7 @@ unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
/// Extension methods for vectors such that their elements are
/// mutable.
pub trait MutableSliceAllocating<'a, T> {
/// Sort the vector, in place, using `compare` to compare
/// Sorts the slice, in place, using `compare` to compare
/// elements.
///
/// This sort is `O(n log n)` worst-case and stable, but allocates
......@@ -578,29 +574,27 @@ pub trait MutableSliceAllocating<'a, T> {
/// ```
fn sort_by(self, compare: |&T, &T| -> Ordering);
/**
* Consumes `src` and moves as many elements as it can into `self`
* from the range [start,end).
*
* Returns the number of elements copied (the shorter of self.len()
* and end - start).
*
* # Arguments
*
* * src - A mutable vector of `T`
* * start - The index into `src` to start copying from
* * end - The index into `src` to stop copying from
*
* # Example
*
* ```rust
* let mut a = [1i, 2, 3, 4, 5];
* let b = vec![6i, 7, 8];
* let num_moved = a.move_from(b, 0, 3);
* assert_eq!(num_moved, 3);
* assert!(a == [6i, 7, 8, 4, 5]);
* ```
*/
/// Consumes `src` and moves as many elements as it can into `self`
/// from the range [start,end).
///
/// Returns the number of elements copied (the shorter of `self.len()`
/// and `end - start`).
///
/// # Arguments
///
/// * src - A mutable vector of `T`
/// * start - The index into `src` to start copying from
/// * end - The index into `src` to stop copying from
///
/// # Example
///
/// ```rust
/// let mut a = [1i, 2, 3, 4, 5];
/// let b = vec![6i, 7, 8];
/// let num_moved = a.move_from(b, 0, 3);
/// assert_eq!(num_moved, 3);
/// assert!(a == [6i, 7, 8, 4, 5]);
/// ```
fn move_from(self, src: Vec<T>, start: uint, end: uint) -> uint;
}
......@@ -622,7 +616,7 @@ fn move_from(self, mut src: Vec<T>, start: uint, end: uint) -> uint {
/// Methods for mutable vectors with orderable elements, such as
/// in-place sorting.
pub trait MutableOrdSlice<T> {
/// Sort the vector, in place.
/// Sorts the slice, in place.
///
/// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
///
......@@ -638,7 +632,8 @@ pub trait MutableOrdSlice<T> {
/// Mutates the slice to the next lexicographic permutation.
///
/// Returns `true` if successful, `false` if the slice is at the last-ordered permutation.
/// Returns `true` if successful and `false` if the slice is at the
/// last-ordered permutation.
///
/// # Example
///
......@@ -653,7 +648,8 @@ pub trait MutableOrdSlice<T> {
/// Mutates the slice to the previous lexicographic permutation.
///
/// Returns `true` if successful, `false` if the slice is at the first-ordered permutation.
/// Returns `true` if successful and `false` if the slice is at the
/// first-ordered permutation.
///
/// # Example
///
......
......@@ -66,24 +66,24 @@ pub struct SmallIntMap<T> {
}
impl<V> Collection for SmallIntMap<V> {
/// Return the number of elements in the map.
/// Returns the number of elements in the map.
fn len(&self) -> uint {
self.v.iter().filter(|elt| elt.is_some()).count()
}
/// Return `true` if there are no elements in the map.
/// Returns`true` if there are no elements in the map.
fn is_empty(&self) -> bool {
self.v.iter().all(|elt| elt.is_none())
}
}
impl<V> Mutable for SmallIntMap<V> {
/// Clear the map, removing all key-value pairs.
/// Clears the map, removing all key-value pairs.
fn clear(&mut self) { self.v.clear() }
}
impl<V> Map<uint, V> for SmallIntMap<V> {
/// Return a reference to the value corresponding to the key.
/// Returns a reference to the value corresponding to the key.
fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
if *key < self.v.len() {
match self.v[*key] {
......@@ -97,7 +97,7 @@ fn find<'a>(&'a self, key: &uint) -> Option<&'a V> {
}
impl<V> MutableMap<uint, V> for SmallIntMap<V> {
/// Return a mutable reference to the value corresponding to the key.
/// Returns a mutable reference to the value corresponding to the key.
fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
if *key < self.v.len() {
match *self.v.get_mut(*key) {
......@@ -109,8 +109,8 @@ fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut V> {
}
}
/// Insert a key-value pair into the map. An existing value for a
/// key is replaced by the new value. Return `true` if the key did
/// Inserts a key-value pair into the map. An existing value for a
/// key is replaced by the new value. Returns `true` if the key did
/// not already exist in the map.
fn insert(&mut self, key: uint, value: V) -> bool {
let exists = self.contains_key(&key);
......@@ -122,13 +122,13 @@ fn insert(&mut self, key: uint, value: V) -> bool {
!exists
}
/// Remove a key-value pair from the map. Return `true` if the key
/// was present in the map, otherwise `false`.
/// Removes a key-value pair from the map. Returns `true` if the key
/// was present in the map.
fn remove(&mut self, key: &uint) -> bool {
self.pop(key).is_some()
}
/// Insert a key-value pair from the map. If the key already had a value
/// Inserts a key-value pair into the map. If the key already had a value
/// present in the map, that value is returned. Otherwise `None` is returned.
fn swap(&mut self, key: uint, value: V) -> Option<V> {
match self.find_mut(&key) {
......@@ -176,7 +176,7 @@ fn hash(&self, state: &mut S) {
}
impl<V> SmallIntMap<V> {
/// Create an empty SmallIntMap.
/// Creates an empty `SmallIntMap`.
///
/// # Example
///
......@@ -186,8 +186,8 @@ impl<V> SmallIntMap<V> {
/// ```
pub fn new() -> SmallIntMap<V> { SmallIntMap{v: vec!()} }
/// Create an empty SmallIntMap with space for at least `capacity` elements
/// before resizing.
/// Creates an empty `SmallIntMap` with space for at least `capacity`
/// elements before resizing.
///
/// # Example
///
......@@ -222,20 +222,20 @@ pub fn get<'a>(&'a self, key: &uint) -> &'a V {
self.find(key).expect("key not present")
}
/// An iterator visiting all keys in ascending order by the keys.
/// Iterator element type is `uint`.
/// 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> {
self.iter().map(|(k, _v)| k)
}
/// An iterator visiting all values in ascending order by the keys.
/// Iterator element type is `&'r V`.
/// Returns an iterator visiting all values in ascending order by the keys.
/// The iterator's element type is `&'r V`.
pub fn values<'r>(&'r self) -> Values<'r, V> {
self.iter().map(|(_k, v)| v)
}
/// An iterator visiting all key-value pairs in ascending order by the keys.
/// Iterator element type is `(uint, &'r V)`.
/// Returns an iterator visiting all key-value pairs in ascending order by the keys.
/// The iterator's element type is `(uint, &'r V)`.
///
/// # Example
///
......@@ -260,9 +260,9 @@ pub fn iter<'r>(&'r self) -> Entries<'r, V> {
}
}
/// An iterator visiting all key-value pairs in ascending order by the keys,
/// with mutable references to the values
/// Iterator element type is `(uint, &'r mut V)`.
/// 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)`.
///
/// # Example
///
......@@ -290,7 +290,9 @@ pub fn mut_iter<'r>(&'r mut self) -> MutEntries<'r, V> {
}
}
/// Empties the map, moving all values into the specified closure.
/// 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)`.
///
/// # Example
///
......@@ -319,10 +321,10 @@ pub fn move_iter(&mut self)
}
impl<V:Clone> SmallIntMap<V> {
/// Update a value in the map. If the key already exists in the map,
/// modify the value with `ff` taking `oldval, newval`.
/// Otherwise set the value to `newval`.
/// Return `true` if the key did not already exist in the map.
/// Updates a value in the map. If the key already exists in the map,
/// modifies the value with `ff` taking `oldval, newval`.
/// Otherwise, sets the value to `newval`.
/// Returasn `true` if the key did not already exist in the map.
///
/// # Example
///
......@@ -343,10 +345,10 @@ pub fn update(&mut self, key: uint, newval: V, ff: |V, V| -> V) -> bool {
self.update_with_key(key, newval, |_k, v, v1| ff(v,v1))
}
/// Update a value in the map. If the key already exists in the map,
/// modify the value with `ff` taking `key, oldval, newval`.
/// Otherwise set the value to `newval`.
/// Return `true` if the key did not already exist in the map.
/// Updates a value in the map. If the key already exists in the map,
/// modifies the value with `ff` taking `key, oldval, newval`.
/// Otherwise, sets the value to `newval`.
/// Returns `true` if the key did not already exist in the map.
///
/// # Example
///
......
......@@ -10,51 +10,47 @@
//
// ignore-lexer-test FIXME #15679
/*!
Unicode string manipulation (`str` type)
# Basic Usage
Rust's string type is one of the core primitive types of the language. While
represented by the name `str`, the name `str` is not actually a valid type in
Rust. Each string must also be decorated with a pointer. `String` is used
for an owned string, so there is only one commonly-used `str` type in Rust:
`&str`.
`&str` is the borrowed string type. This type of string can only be created
from other strings, unless it is a static string (see below). As the word
"borrowed" implies, this type of string is owned elsewhere, and this string
cannot be moved out of.
As an example, here's some code that uses a string.
```rust
fn main() {
let borrowed_string = "This string is borrowed with the 'static lifetime";
}
```
From the example above, you can see that Rust's string literals have the
`'static` lifetime. This is akin to C's concept of a static string.
String literals are allocated statically in the rodata of the
executable/library. The string then has the type `&'static str` meaning that
the string is valid for the `'static` lifetime, otherwise known as the
lifetime of the entire program. As can be inferred from the type, these static
strings are not mutable.
# Representation
Rust's string type, `str`, is a sequence of unicode scalar values encoded as a
stream of UTF-8 bytes. All strings are guaranteed to be validly encoded UTF-8
sequences. Additionally, strings are not null-terminated and can contain null
bytes.
The actual representation of strings have direct mappings to vectors: `&str`
is the same as `&[u8]`.
*/
//! Unicode string manipulation (`str` type)
//!
//! # Basic Usage
//!
//! Rust's string type is one of the core primitive types of the language. While
//! represented by the name `str`, the name `str` is not actually a valid type in
//! Rust. Each string must also be decorated with a pointer. `String` is used
//! for an owned string, so there is only one commonly-used `str` type in Rust:
//! `&str`.
//!
//! `&str` is the borrowed string type. This type of string can only be created
//! from other strings, unless it is a static string (see below). As the word
//! "borrowed" implies, this type of string is owned elsewhere, and this string
//! cannot be moved out of.
//!
//! As an example, here's some code that uses a string.
//!
//! ```rust
//! fn main() {
//! let borrowed_string = "This string is borrowed with the 'static lifetime";
//! }
//! ```
//!
//! From the example above, you can see that Rust's string literals have the
//! `'static` lifetime. This is akin to C's concept of a static string.
//!
//! String literals are allocated statically in the rodata of the
//! executable/library. The string then has the type `&'static str` meaning that
//! the string is valid for the `'static` lifetime, otherwise known as the
//! lifetime of the entire program. As can be inferred from the type, these static
//! strings are not mutable.
//!
//! # Representation
//!
//! Rust's string type, `str`, is a sequence of unicode scalar values encoded as a
//! stream of UTF-8 bytes. All strings are guaranteed to be validly encoded UTF-8
//! sequences. Additionally, strings are not null-terminated and can contain null
//! bytes.
//!
//! The actual representation of strings have direct mappings to slices: `&str`
//! is the same as `&[u8]`.
#![doc(primitive = "str")]
......@@ -88,34 +84,34 @@ fn main() {
Section: Creating a string
*/
/// Deprecated. Replaced by `String::from_utf8`
/// Deprecated. Replaced by `String::from_utf8`.
#[deprecated = "Replaced by `String::from_utf8`"]
pub fn from_utf8_owned(vv: Vec<u8>) -> Result<String, Vec<u8>> {
String::from_utf8(vv)
}
/// Deprecated. Replaced by `String::from_byte`
/// Deprecated. Replaced by `String::from_byte`.
#[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()` 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. 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
/// Methods for vectors of strings.
pub trait StrVector {
/// Concatenate a vector of strings.
/// Concatenates a vector of strings.
///
/// # Example
///
......@@ -127,7 +123,7 @@ pub trait StrVector {
/// ```
fn concat(&self) -> String;
/// Concatenate a vector of strings, placing a given separator between each.
/// Concatenates a vector of strings, placing a given separator between each.
///
/// # Example
///
......@@ -394,7 +390,7 @@ fn next(&mut self) -> Option<char> {
}
}
/// Replace all occurrences of one string with another
/// Replaces all occurrences of one string with another.
///
/// # Arguments
///
......@@ -404,7 +400,7 @@ fn next(&mut self) -> Option<char> {
///
/// # Return value
///
/// The original string with all occurrences of `from` replaced with `to`
/// The original string with all occurrences of `from` replaced with `to`.
///
/// # Example
///
......@@ -464,21 +460,21 @@ pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a> {
Section: MaybeOwned
*/
/// A `MaybeOwned` is a string that can hold either a `String` or a `&str`.
/// A string type that can hold either a `String` or a `&str`.
/// This can be useful as an optimization when an allocation is sometimes
/// needed but not always.
pub enum MaybeOwned<'a> {
/// A borrowed string
/// A borrowed string.
Slice(&'a str),
/// An owned string
/// An owned string.
Owned(String)
}
/// `SendStr` is a specialization of `MaybeOwned` to be sendable
/// A specialization of `MaybeOwned` to be sendable.
pub type SendStr = MaybeOwned<'static>;
impl<'a> MaybeOwned<'a> {
/// Returns `true` if this `MaybeOwned` wraps an owned string
/// Returns `true` if this `MaybeOwned` wraps an owned string.
///
/// # Example
///
......@@ -495,7 +491,7 @@ pub fn is_owned(&self) -> bool {
}
}
/// Returns `true` if this `MaybeOwned` wraps a borrowed string
/// Returns `true` if this `MaybeOwned` wraps a borrowed string.
///
/// # Example
///
......@@ -513,47 +509,47 @@ pub fn is_slice(&self) -> bool {
}
}
/// Trait for moving into a `MaybeOwned`
/// Trait for moving into a `MaybeOwned`.
pub trait IntoMaybeOwned<'a> {
/// Moves self into a `MaybeOwned`
/// Moves `self` into a `MaybeOwned`.
fn into_maybe_owned(self) -> MaybeOwned<'a>;
}
/// # Example
///
/// ```rust
/// let owned_string = String::from_str("orange");
/// let maybe_owned_string = owned_string.into_maybe_owned();
/// assert_eq!(true, maybe_owned_string.is_owned());
/// ```
impl<'a> IntoMaybeOwned<'a> for String {
/// # Example
///
/// ```rust
/// let owned_string = String::from_str("orange");
/// let maybe_owned_string = owned_string.into_maybe_owned();
/// assert_eq!(true, maybe_owned_string.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> {
Owned(self)
}
}
/// # Example
///
/// ```rust
/// let string = "orange";
/// let maybe_owned_str = string.as_slice().into_maybe_owned();
/// assert_eq!(false, maybe_owned_str.is_owned());
/// ```
impl<'a> IntoMaybeOwned<'a> for &'a str {
/// # Example
///
/// ```rust
/// let string = "orange";
/// let maybe_owned_str = string.as_slice().into_maybe_owned();
/// assert_eq!(false, maybe_owned_str.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> { Slice(self) }
}
/// # Example
///
/// ```rust
/// let str = "orange";
/// let maybe_owned_str = str.as_slice().into_maybe_owned();
/// let maybe_maybe_owned_str = maybe_owned_str.into_maybe_owned();
/// assert_eq!(false, maybe_maybe_owned_str.is_owned());
/// ```
impl<'a> IntoMaybeOwned<'a> for MaybeOwned<'a> {
/// # Example
///
/// ```rust
/// let str = "orange";
/// let maybe_owned_str = str.as_slice().into_maybe_owned();
/// let maybe_maybe_owned_str = maybe_owned_str.into_maybe_owned();
/// assert_eq!(false, maybe_maybe_owned_str.is_owned());
/// ```
#[inline]
fn into_maybe_owned(self) -> MaybeOwned<'a> { self }
}
......@@ -645,7 +641,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
}
/// Unsafe operations
/// Unsafe string operations.
pub mod raw {
use string;
use string::String;
......@@ -685,9 +681,9 @@ pub unsafe fn from_byte(u: u8) -> String {
Section: Trait implementations
*/
/// Any string that can be represented as a slice
/// Any string that can be represented as a slice.
pub trait StrAllocating: Str {
/// Convert `self` into a `String`, not making a copy if possible.
/// Converts `self` into a `String`, not making a copy if possible.
fn into_string(self) -> String;
#[allow(missing_doc)]
......@@ -696,7 +692,7 @@ fn into_owned(self) -> String {
self.into_string()
}
/// Escape each char in `s` with `char::escape_default`.
/// Escapes each char in `s` with `char::escape_default`.
fn escape_default(&self) -> String {
let me = self.as_slice();
let mut out = String::with_capacity(me.len());
......@@ -706,7 +702,7 @@ fn escape_default(&self) -> String {
out
}
/// Escape each char in `s` with `char::escape_unicode`.
/// Escapes each char in `s` with `char::escape_unicode`.
fn escape_unicode(&self) -> String {
let me = self.as_slice();
let mut out = String::with_capacity(me.len());
......@@ -716,7 +712,7 @@ fn escape_unicode(&self) -> String {
out
}
/// Replace all occurrences of one string with another.
/// Replaces all occurrences of one string with another.
///
/// # Arguments
///
......@@ -768,7 +764,7 @@ fn to_utf16(&self) -> Vec<u16> {
self.as_slice().utf16_units().collect::<Vec<u16>>()
}
/// Given a string, make a new string with repeated copies of it.
/// Given a string, makes a new string with repeated copies of it.
fn repeat(&self, nn: uint) -> String {
let me = self.as_slice();
let mut ret = String::with_capacity(nn * me.len());
......@@ -778,7 +774,7 @@ fn repeat(&self, nn: uint) -> String {
ret
}
/// Levenshtein Distance between two strings.
/// Returns the Levenshtein Distance between two strings.
fn lev_distance(&self, t: &str) -> uint {
let me = self.as_slice();
let slen = me.len();
......@@ -813,7 +809,7 @@ fn lev_distance(&self, t: &str) -> uint {
return dcol[tlen];
}
/// An Iterator over the string in Unicode Normalization Form D
/// Returns an iterator over the string in Unicode Normalization Form D
/// (canonical decomposition).
#[inline]
fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
......@@ -825,7 +821,7 @@ fn nfd_chars<'a>(&'a self) -> Decompositions<'a> {
}
}
/// An Iterator over the string in Unicode Normalization Form KD
/// Returns an iterator over the string in Unicode Normalization Form KD
/// (compatibility decomposition).
#[inline]
fn nfkd_chars<'a>(&'a self) -> Decompositions<'a> {
......
......@@ -120,8 +120,8 @@ pub fn from_utf8(vec: Vec<u8>) -> Result<String, Vec<u8>> {
}
}
/// Converts a vector of bytes to a new utf-8 string.
/// Any invalid utf-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
/// Converts a vector of bytes to a new UTF-8 string.
/// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
///
/// # Example
///
......@@ -289,7 +289,7 @@ pub fn from_utf16_lossy(v: &[u16]) -> String {
str::utf16_items(v).map(|c| c.to_char_lossy()).collect()
}
/// Convert a vector of chars to a string.
/// Convert a vector of `char`s to a `String`.
///
/// # Example
///
......@@ -317,8 +317,8 @@ pub fn into_bytes(self) -> Vec<u8> {
self.vec
}
/// Pushes the given string onto this buffer; then, returns `self` so that it can be used
/// again.
/// Pushes the given `String` onto this buffer then returns `self` so that it can be
/// used again.
///
/// # Example
///
......@@ -359,11 +359,11 @@ pub fn from_char(length: uint, ch: char) -> String {
buf
}
/// Convert a byte to a UTF-8 string.
/// Converts a byte to a UTF-8 string.
///
/// # Failure
///
/// Fails if invalid UTF-8
/// Fails with invalid UTF-8 (i.e., the byte is greater than 127).
///
/// # Example
///
......@@ -390,7 +390,7 @@ pub fn push_str(&mut self, string: &str) {
self.vec.push_all(string.as_bytes())
}
/// Push `ch` onto the given string `count` times.
/// Pushes `ch` onto the given string `count` times.
///
/// # Example
///
......@@ -560,7 +560,7 @@ pub unsafe fn as_mut_bytes<'a>(&'a mut self) -> &'a mut [u8] {
self.vec.as_mut_slice()
}
/// Shorten a string to the specified length.
/// Shortens a string to the specified length.
///
/// # Failure
///
......@@ -815,11 +815,11 @@ pub mod raw {
use super::String;
use vec::Vec;
/// Creates a new `String` from length, capacity, and a pointer.
/// Creates a new `String` from a length, capacity, and pointer.
///
/// This is unsafe because:
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`
/// * We assume that the `Vec` contains valid UTF-8
/// * We call `Vec::from_raw_parts` to get a `Vec<u8>`;
/// * We assume that the `Vec` contains valid UTF-8.
#[inline]
pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
String {
......@@ -827,11 +827,11 @@ pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String {
}
}
/// Create `String` from a *u8 buffer of the given length
/// Creates a `String` from a `*const u8` buffer of the given length.
///
/// This function is unsafe because of two reasons:
/// * A raw pointer is dereferenced and transmuted to `&[u8]`
/// * The slice is not checked to see whether it contains valid UTF-8
/// * A raw pointer is dereferenced and transmuted to `&[u8]`;
/// * The slice is not checked to see whether it contains valid UTF-8.
pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
use slice::CloneableVector;
let slice: &[u8] = mem::transmute(Slice {
......@@ -841,7 +841,7 @@ pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String {
self::from_utf8(slice.to_vec())
}
/// Create a `String` from a null-terminated *u8 buffer
/// Creates a `String` from a null-terminated `*const u8` buffer.
///
/// This function is unsafe because we dereference memory until we find the NUL character,
/// which is not guaranteed to be present. Additionally, the slice is not checked to see
......@@ -856,7 +856,7 @@ pub unsafe fn from_buf(buf: *const u8) -> String {
/// Converts a vector of bytes to a new `String` without checking if
/// it contains valid UTF-8. This is unsafe because it assumes that
/// the utf-8-ness of the vector has already been validated.
/// the UTF-8-ness of the vector has already been validated.
#[inline]
pub unsafe fn from_utf8(bytes: Vec<u8>) -> String {
String { vec: bytes }
......
......@@ -261,7 +261,7 @@ fn index_mut<'a>(&'a mut self, i: &K) -> &'a mut V {
}*/
impl<K: Ord, V> TreeMap<K, V> {
/// Create an empty `TreeMap`.
/// Creates an empty `TreeMap`.
///
/// # Example
///
......@@ -271,7 +271,7 @@ impl<K: Ord, V> TreeMap<K, V> {
/// ```
pub fn new() -> TreeMap<K, V> { TreeMap{root: None, length: 0} }
/// Get a lazy iterator over the keys in the map, in ascending order.
/// Gets a lazy iterator over the keys in the map, in ascending order.
///
/// # Example
///
......@@ -291,7 +291,7 @@ pub fn keys<'a>(&'a self) -> Keys<'a, K, V> {
self.iter().map(|(k, _v)| k)
}
/// Get a lazy iterator over the values in the map, in ascending order
/// Gets a lazy iterator over the values in the map, in ascending order
/// with respect to the corresponding keys.
///
/// # Example
......@@ -312,7 +312,7 @@ pub fn values<'a>(&'a self) -> Values<'a, K, V> {
self.iter().map(|(_k, v)| v)
}
/// Get a lazy iterator over the key-value pairs in the map, in ascending order.
/// Gets a lazy iterator over the key-value pairs in the map, in ascending order.
///
/// # Example
///
......@@ -337,7 +337,7 @@ pub fn iter<'a>(&'a self) -> Entries<'a, K, V> {
}
}
/// Get a lazy reverse iterator over the key-value pairs in the map, in descending order.
/// Gets a lazy reverse iterator over the key-value pairs in the map, in descending order.
///
/// # Example
///
......@@ -357,7 +357,7 @@ pub fn rev_iter<'a>(&'a self) -> RevEntries<'a, K, V> {
RevEntries{iter: self.iter()}
}
/// Get a lazy forward iterator over the key-value pairs in the
/// Gets a lazy forward iterator over the key-value pairs in the
/// map, with the values being mutable.
///
/// # Example
......@@ -387,7 +387,8 @@ pub fn mut_iter<'a>(&'a mut self) -> MutEntries<'a, K, V> {
remaining_max: self.length
}
}
/// Get a lazy reverse iterator over the key-value pairs in the
/// Gets a lazy reverse iterator over the key-value pairs in the
/// map, with the values being mutable.
///
/// # Example
......@@ -414,8 +415,7 @@ pub fn mut_rev_iter<'a>(&'a mut self) -> RevMutEntries<'a, K, V> {
}
/// Get a lazy iterator that consumes the treemap, it is not usable
/// after calling this.
/// Gets a lazy iterator that consumes the treemap.
///
/// # Example
///
......@@ -444,7 +444,7 @@ pub fn move_iter(self) -> MoveEntries<K, V> {
}
impl<K, V> TreeMap<K, V> {
/// Return the value for which `f(key)` returns `Equal`. `f` is invoked
/// 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.
///
......@@ -473,7 +473,7 @@ pub fn find_with<'a>(&'a self, f:|&K| -> Ordering) -> Option<&'a V> {
tree_find_with(&self.root, f)
}
/// Return the value for which `f(key)` returns `Equal`. `f` is invoked
/// 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.
///
......@@ -533,7 +533,7 @@ pub fn find_mut_with<'a>(&'a mut self, f:|&K| -> Ordering) -> Option<&'a mut V>
impl<K: Ord, V> TreeMap<K, V> {
/// Get a lazy iterator that should be initialized using
/// Gets a lazy iterator that should be initialized using
/// `traverse_left`/`traverse_right`/`traverse_complete`.
fn iter_for_traversal<'a>(&'a self) -> Entries<'a, K, V> {
Entries {
......@@ -544,7 +544,7 @@ fn iter_for_traversal<'a>(&'a self) -> Entries<'a, K, V> {
}
}
/// Return a lazy iterator to the first key-value pair whose key is not less than `k`
/// Returns a lazy iterator to the first key-value pair whose key is not less than `k`
/// If all keys in map are less than `k` an empty iterator is returned.
///
/// # Example
......@@ -566,7 +566,7 @@ pub fn lower_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> {
bound_setup!(self.iter_for_traversal(), k, true)
}
/// Return a lazy iterator to the first key-value pair whose key is greater than `k`
/// Returns a lazy iterator to the first key-value pair whose key is greater than `k`
/// If all keys in map are less than or equal to `k` an empty iterator is returned.
///
/// # Example
......@@ -588,7 +588,7 @@ pub fn upper_bound<'a>(&'a self, k: &K) -> Entries<'a, K, V> {
bound_setup!(self.iter_for_traversal(), k, false)
}
/// Get a lazy iterator that should be initialized using
/// Gets a lazy iterator that should be initialized using
/// `traverse_left`/`traverse_right`/`traverse_complete`.
fn mut_iter_for_traversal<'a>(&'a mut self) -> MutEntries<'a, K, V> {
MutEntries {
......@@ -599,7 +599,7 @@ fn mut_iter_for_traversal<'a>(&'a mut self) -> MutEntries<'a, K, V> {
}
}
/// Return a lazy value iterator to the first key-value pair (with
/// Returns a lazy value iterator to the first key-value pair (with
/// the value being mutable) whose key is not less than `k`.
///
/// If all keys in map are less than `k` an empty iterator is
......@@ -633,7 +633,7 @@ pub fn mut_lower_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
bound_setup!(self.mut_iter_for_traversal(), k, true)
}
/// Return a lazy iterator to the first key-value pair (with the
/// Returns a lazy iterator to the first key-value pair (with the
/// value being mutable) whose key is greater than `k`.
///
/// If all keys in map are less than or equal to `k` an empty iterator
......@@ -668,7 +668,7 @@ pub fn mut_upper_bound<'a>(&'a mut self, k: &K) -> MutEntries<'a, K, V> {
}
}
/// Lazy forward iterator over a map
/// A lazy forward iterator over a map.
pub struct Entries<'a, K, V> {
stack: Vec<&'a TreeNode<K, V>>,
// See the comment on MutEntries; this is just to allow
......@@ -679,12 +679,12 @@ pub struct Entries<'a, K, V> {
remaining_max: uint
}
/// Lazy backward iterator over a map
/// Lazy backward iterator over a map.
pub struct RevEntries<'a, K, V> {
iter: Entries<'a, K, V>,
}
/// Lazy forward iterator over a map that allows for the mutation of
/// A lazy forward iterator over a map that allows for the mutation of
/// the values.
pub struct MutEntries<'a, K, V> {
stack: Vec<&'a mut TreeNode<K, V>>,
......@@ -712,17 +712,17 @@ pub struct MutEntries<'a, K, V> {
remaining_max: uint
}
/// Lazy backward iterator over a map
/// Lazy backward iterator over a map.
pub struct RevMutEntries<'a, K, V> {
iter: MutEntries<'a, K, V>,
}
/// TreeMap keys iterator
/// TreeMap keys iterator.
pub type Keys<'a, K, V> =
iter::Map<'static, (&'a K, &'a V), &'a K, Entries<'a, K, V>>;
/// TreeMap values iterator
/// TreeMap values iterator.
pub type Values<'a, K, V> =
iter::Map<'static, (&'a K, &'a V), &'a V, Entries<'a, K, V>>;
......@@ -821,7 +821,7 @@ fn traverse_complete(&mut self) {
// the forward Iterator impl.
item!(impl<'a, K, V> Iterator<(&'a K, &'a $($addr_mut)* V)> for $name<'a, K, V> {
/// Advance the iterator to the next node (in order) and return a
/// Advances the iterator to the next node (in order) and return a
/// tuple with a reference to the key and value. If there are no
/// more nodes, return `None`.
fn next(&mut self) -> Option<(&'a K, &'a $($addr_mut)* V)> {
......@@ -887,7 +887,7 @@ fn mut_deref<K, V>(x: &mut Option<Box<TreeNode<K, V>>>)
/// Lazy forward iterator over a map that consumes the map while iterating
/// A lazy forward iterator over a map that consumes the map while iterating.
pub struct MoveEntries<K, V> {
stack: Vec<TreeNode<K, V>>,
remaining: uint
......@@ -951,7 +951,7 @@ fn next(&mut self) -> Option<&'a T> {
}
}
/// A implementation of the `Set` trait on top of the `TreeMap` container. The
/// An implementation of the `Set` trait on top of the `TreeMap` container. The
/// only requirement is that the type of the elements contained ascribes to the
/// `Ord` trait.
///
......@@ -1121,7 +1121,7 @@ fn default() -> TreeSet<T> { TreeSet::new() }
}
impl<T: Ord> TreeSet<T> {
/// Create an empty `TreeSet`.
/// Creates an empty `TreeSet`.
///
/// # Example
///
......@@ -1132,7 +1132,7 @@ impl<T: Ord> TreeSet<T> {
#[inline]
pub fn new() -> TreeSet<T> { TreeSet{map: TreeMap::new()} }
/// Get a lazy iterator over the values in the set, in ascending order.
/// Gets a lazy iterator over the values in the set, in ascending order.
///
/// # Example
///
......@@ -1150,7 +1150,7 @@ pub fn iter<'a>(&'a self) -> SetItems<'a, T> {
SetItems{iter: self.map.iter()}
}
/// Get a lazy iterator over the values in the set, in descending order.
/// Gets a lazy iterator over the values in the set, in descending order.
///
/// # Example
///
......@@ -1186,7 +1186,7 @@ pub fn move_iter(self) -> MoveSetItems<T> {
self.map.move_iter().map(|(value, _)| value)
}
/// Get a lazy iterator pointing to the first value not less than `v` (greater or equal).
/// Gets a lazy iterator pointing to the first value not less than `v` (greater or equal).
/// If all elements in the set are less than `v` empty iterator is returned.
///
/// # Example
......@@ -1204,7 +1204,7 @@ pub fn lower_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> {
SetItems{iter: self.map.lower_bound(v)}
}
/// Get a lazy iterator pointing to the first value greater than `v`.
/// Gets a lazy iterator pointing to the first value greater than `v`.
/// If all elements in the set are less than or equal to `v` an
/// empty iterator is returned.
///
......@@ -1223,7 +1223,7 @@ pub fn upper_bound<'a>(&'a self, v: &T) -> SetItems<'a, T> {
SetItems{iter: self.map.upper_bound(v)}
}
/// Visit the values representing the difference, in ascending order.
/// Visits the values representing the difference, in ascending order.
///
/// # Example
///
......@@ -1250,7 +1250,7 @@ pub fn difference<'a>(&'a self, other: &'a TreeSet<T>) -> DifferenceItems<'a, T>
DifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values representing the symmetric difference, in ascending order.
/// Visits the values representing the symmetric difference, in ascending order.
///
/// # Example
///
......@@ -1276,7 +1276,7 @@ pub fn symmetric_difference<'a>(&'a self, other: &'a TreeSet<T>)
SymDifferenceItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values representing the intersection, in ascending order.
/// Visits the values representing the intersection, in ascending order.
///
/// # Example
///
......@@ -1299,7 +1299,7 @@ pub fn intersection<'a>(&'a self, other: &'a TreeSet<T>)
IntersectionItems{a: self.iter().peekable(), b: other.iter().peekable()}
}
/// Visit the values representing the union, in ascending order.
/// Visits the values representing the union, in ascending order.
///
/// # Example
///
......@@ -1322,44 +1322,45 @@ pub fn union<'a>(&'a self, other: &'a TreeSet<T>) -> UnionItems<'a, T> {
}
}
/// Lazy forward iterator over a set
/// A lazy forward iterator over a set.
pub struct SetItems<'a, T> {
iter: Entries<'a, T, ()>
}
/// Lazy backward iterator over a set
/// Lazy backward iterator over a set.
pub struct RevSetItems<'a, T> {
iter: RevEntries<'a, T, ()>
}
/// Lazy forward iterator over a set that consumes the set while iterating
/// A lazy forward iterator over a set that consumes the set while iterating.
pub type MoveSetItems<T> = iter::Map<'static, (T, ()), T, MoveEntries<T, ()>>;
/// Lazy iterator producing elements in the set difference (in-order)
/// A lazy iterator producing elements in the set difference (in-order).
pub struct DifferenceItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set symmetric difference (in-order)
/// A lazy iterator producing elements in the set symmetric difference (in-order).
pub struct SymDifferenceItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set intersection (in-order)
/// A lazy iterator producing elements in the set intersection (in-order).
pub struct IntersectionItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Lazy iterator producing elements in the set union (in-order)
/// A lazy iterator producing elements in the set union (in-order).
pub struct UnionItems<'a, T> {
a: Peekable<&'a T, SetItems<'a, T>>,
b: Peekable<&'a T, SetItems<'a, T>>,
}
/// Compare `x` and `y`, but return `short` if x is None and `long` if y is None
/// Compare `x` and `y`, but return `short` if x is None and `long` if y is
/// `None`.
fn cmp_opt<T: Ord>(x: Option<&T>, y: Option<&T>,
short: Ordering, long: Ordering) -> Ordering {
match (x, y) {
......
......@@ -121,13 +121,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
impl<T> Collection for TrieMap<T> {
/// Return the number of elements in the map.
/// Returns the number of elements in the map.
#[inline]
fn len(&self) -> uint { self.length }
}
impl<T> Mutable for TrieMap<T> {
/// Clear the map, removing all values.
/// Clears the map, removing all values.
#[inline]
fn clear(&mut self) {
self.root = TrieNode::new();
......@@ -136,7 +136,7 @@ fn clear(&mut self) {
}
impl<T> Map<uint, T> for TrieMap<T> {
/// Return a reference to the value corresponding to the key.
/// Returns a reference to the value corresponding to the key.
#[inline]
fn find<'a>(&'a self, key: &uint) -> Option<&'a T> {
let mut node: &'a TrieNode<T> = &self.root;
......@@ -159,14 +159,14 @@ fn find<'a>(&'a self, key: &uint) -> Option<&'a T> {
}
impl<T> MutableMap<uint, T> for TrieMap<T> {
/// Return a mutable reference to the value corresponding to the key.
/// Returns a mutable reference to the value corresponding to the key.
#[inline]
fn find_mut<'a>(&'a mut self, key: &uint) -> Option<&'a mut T> {
find_mut(&mut self.root.children[chunk(*key, 0)], *key, 1)
}
/// Insert a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise None is returned.
/// Inserts a key-value pair from the map. If the key already had a value
/// present in the map, that value is returned. Otherwise, `None` is returned.
fn swap(&mut self, key: uint, value: T) -> Option<T> {
let ret = insert(&mut self.root.count,
&mut self.root.children[chunk(key, 0)],
......@@ -192,7 +192,7 @@ fn default() -> TrieMap<T> { TrieMap::new() }
}
impl<T> TrieMap<T> {
/// Create an empty TrieMap.
/// Creates an empty `TrieMap`.
///
/// # Example
///
......@@ -205,8 +205,8 @@ pub fn new() -> TrieMap<T> {
TrieMap{root: TrieNode::new(), length: 0}
}
/// Visit all key-value pairs in reverse order. Abort traversal when f returns false.
/// Return true if f returns true for all elements.
/// Visits all key-value pairs in reverse order. Aborts traversal when `f` returns `false`.
/// Returns `true` if `f` returns `true` for all elements.
///
/// # Example
///
......@@ -228,19 +228,19 @@ pub fn each_reverse<'a>(&'a self, f: |&uint, &'a T| -> bool) -> bool {
self.root.each_reverse(f)
}
/// Get an iterator visiting all keys in ascending order by the keys.
/// Iterator element type is `uint`.
/// Gets 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, T> {
self.iter().map(|(k, _v)| k)
}
/// Get an iterator visiting all values in ascending order by the keys.
/// Iterator element type is `&'r T`.
/// Gets an iterator visiting all values in ascending order by the keys.
/// The iterator's element type is `&'r T`.
pub fn values<'r>(&'r self) -> Values<'r, T> {
self.iter().map(|(_k, v)| v)
}
/// Get an iterator over the key-value pairs in the map, ordered by keys.
/// Gets an iterator over the key-value pairs in the map, ordered by keys.
///
/// # Example
///
......@@ -262,7 +262,7 @@ pub fn iter<'a>(&'a self) -> Entries<'a, T> {
iter
}
/// Get an iterator over the key-value pairs in the map, with the
/// Gets an iterator over the key-value pairs in the map, with the
/// ability to mutate the values.
///
/// # Example
......@@ -385,7 +385,7 @@ fn bound<'a>(&'a self, key: uint, upper: bool) -> Entries<'a, T> {
mutability = )
}
/// Get an iterator pointing to the first key-value pair whose key is not less than `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.
///
/// # Example
......@@ -402,7 +402,7 @@ pub fn lower_bound<'a>(&'a self, key: uint) -> Entries<'a, T> {
self.bound(key, false)
}
/// Get an iterator pointing to the first key-value pair whose key is greater than `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.
///
/// # Example
......@@ -427,7 +427,7 @@ fn mut_bound<'a>(&'a mut self, key: uint, upper: bool) -> MutEntries<'a, T> {
mutability = mut)
}
/// Get an iterator pointing to the first key-value pair whose key is not less than `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.
///
/// # Example
......@@ -452,7 +452,7 @@ pub fn mut_lower_bound<'a>(&'a mut self, key: uint) -> MutEntries<'a, T> {
self.mut_bound(key, false)
}
/// Get an iterator pointing to the first key-value pair whose key is greater than `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.
///
/// # Example
......@@ -565,13 +565,13 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
impl Collection for TrieSet {
/// Return the number of elements in the set.
/// Returns the number of elements in the set.
#[inline]
fn len(&self) -> uint { self.map.len() }
}
impl Mutable for TrieSet {
/// Clear the set, removing all values.
/// Clears the set, removing all values.
#[inline]
fn clear(&mut self) { self.map.clear() }
}
......@@ -616,7 +616,7 @@ fn default() -> TrieSet { TrieSet::new() }
}
impl TrieSet {
/// Create an empty TrieSet.
/// Creates an empty TrieSet.
///
/// # Example
///
......@@ -629,8 +629,8 @@ pub fn new() -> TrieSet {
TrieSet{map: TrieMap::new()}
}
/// Visit all values in reverse order. Abort traversal when `f` returns false.
/// Return `true` if `f` returns `true` for all elements.
/// Visits all values in reverse order. Aborts traversal when `f` returns `false`.
/// Returns `true` if `f` returns `true` for all elements.
///
/// # Example
///
......@@ -653,7 +653,7 @@ pub fn each_reverse(&self, f: |&uint| -> bool) -> bool {
self.map.each_reverse(|k, _| f(k))
}
/// Get an iterator over the values in the set, in sorted order.
/// Gets an iterator over the values in the set, in sorted order.
///
/// # Example
///
......@@ -676,7 +676,7 @@ pub fn iter<'a>(&'a self) -> SetItems<'a> {
SetItems{iter: self.map.iter()}
}
/// Get an iterator pointing to the first value that is not less than `val`.
/// Gets an iterator pointing to the first value that is not less than `val`.
/// If all values in the set are less than `val` an empty iterator is returned.
///
/// # Example
......@@ -693,7 +693,7 @@ pub fn lower_bound<'a>(&'a self, val: uint) -> SetItems<'a> {
SetItems{iter: self.map.lower_bound(val)}
}
/// Get an iterator pointing to the first value that key is greater than `val`.
/// Gets an iterator pointing to the first value that key is greater than `val`.
/// If all values in the set are less than or equal to `val` an empty iterator is returned.
///
/// # Example
......@@ -857,7 +857,7 @@ fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
return ret;
}
/// Forward iterator over a map.
/// A forward iterator over a map.
pub struct Entries<'a, T> {
stack: [slice::Items<'a, Child<T>>, .. NUM_CHUNKS],
length: uint,
......@@ -865,7 +865,7 @@ pub struct Entries<'a, T> {
remaining_max: uint
}
/// Forward iterator over the key-value pairs of a map, with the
/// A forward iterator over the key-value pairs of a map, with the
/// values being mutable.
pub struct MutEntries<'a, T> {
stack: [slice::MutItems<'a, Child<T>>, .. NUM_CHUNKS],
......@@ -874,11 +874,11 @@ pub struct MutEntries<'a, T> {
remaining_max: uint
}
/// Forward iterator over the keys of a map
/// A forward iterator over the keys of a map.
pub type Keys<'a, T> =
iter::Map<'static, (uint, &'a T), uint, Entries<'a, T>>;
/// Forward iterator over the values of a map
/// A forward iterator over the values of a map.
pub type Values<'a, T> =
iter::Map<'static, (uint, &'a T), &'a T, Entries<'a, T>>;
......@@ -999,7 +999,7 @@ fn size_hint(&self) -> (uint, Option<uint>) {
iterator_impl! { Entries, iter = iter, mutability = }
iterator_impl! { MutEntries, iter = mut_iter, mutability = mut }
/// Forward iterator over a set.
/// A forward iterator over a set.
pub struct SetItems<'a> {
iter: Entries<'a, ()>
}
......
......@@ -190,7 +190,7 @@ pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
}
}
/// Create a `Vec<T>` directly from the raw constituents.
/// Creates a `Vec<T>` directly from the raw constituents.
///
/// This is highly unsafe:
///
......@@ -399,7 +399,7 @@ pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
/// Partitions a vector based on a predicate.
///
/// Clones the elements of the vector, partitioning them into two `Vec`s
/// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
/// `(a, b)`, where all elements of `a` satisfy `f` and all elements of `b`
/// do not. The order of elements is preserved.
///
/// # Example
......@@ -635,7 +635,7 @@ pub fn reserve_exact(&mut self, capacity: uint) {
}
}
/// Shrink the capacity of the vector as much as possible
/// Shrinks the capacity of the vector as much as possible.
///
/// # Example
///
......@@ -706,7 +706,7 @@ pub fn truncate(&mut self, len: uint) {
}
}
/// Work with `self` as a mutable slice.
/// Returns a mutable slice of the elements of `self`.
///
/// # Example
///
......@@ -841,7 +841,7 @@ pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
self.as_mut_slice().mut_iter()
}
/// Sort the vector, in place, using `compare` to compare elements.
/// Sorts the vector, in place, using `compare` to compare elements.
///
/// This sort is `O(n log n)` worst-case and stable, but allocates
/// approximately `2 * n`, where `n` is the length of `self`.
......@@ -944,7 +944,7 @@ pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
self.as_mut_slice().mut_last()
}
/// Remove an element from anywhere in the vector and return it, replacing
/// Removes an element from anywhere in the vector and return it, replacing
/// it with the last element. This does not preserve ordering, but is O(1).
///
/// Returns `None` if `index` is out of bounds.
......@@ -973,7 +973,7 @@ pub fn swap_remove(&mut self, index: uint) -> Option<T> {
self.pop()
}
/// Prepend an element to the vector.
/// Prepends an element to the vector.
///
/// # Warning
///
......@@ -1014,8 +1014,8 @@ pub fn shift(&mut self) -> Option<T> {
self.remove(0)
}
/// Insert an element at position `index` within the vector, shifting all
/// elements after position i one position to the right.
/// Inserts an element at position `index` within the vector, shifting all
/// elements after position `i` one position to the right.
///
/// # Failure
///
......@@ -1052,7 +1052,7 @@ pub fn insert(&mut self, index: uint, element: T) {
}
}
/// Remove and return the element at position `index` within the vector,
/// Removes and returns the element at position `index` within the vector,
/// shifting all elements after position `index` one position to the left.
/// Returns `None` if `i` is out of bounds.
///
......@@ -1126,7 +1126,7 @@ pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
self.as_mut_slice().mut_slice(start, end)
}
/// Returns a mutable slice of self from `start` to the end of the vec.
/// Returns a mutable slice of `self` from `start` to the end of the `Vec`.
///
/// # Failure
///
......@@ -1143,7 +1143,7 @@ pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
self.as_mut_slice().mut_slice_from(start)
}
/// Returns a mutable slice of self from the start of the vec to `end`.
/// Returns a mutable slice of `self` from the start of the `Vec` to `end`.
///
/// # Failure
///
......@@ -1160,7 +1160,7 @@ pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
self.as_mut_slice().mut_slice_to(end)
}
/// Returns a pair of mutable slices that divides the vec at an index.
/// Returns a pair of mutable slices that divides the `Vec` at an index.
///
/// The first will contain all indices from `[0, mid)` (excluding
/// the index `mid` itself) and the second will contain all
......@@ -1199,7 +1199,7 @@ pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
self.as_mut_slice().mut_split_at(mid)
}
/// Reverse the order of elements in a vector, in place.
/// Reverses the order of elements in a vector, in place.
///
/// # Example
///
......@@ -1392,8 +1392,8 @@ fn clear(&mut self) {
}
}
impl<T:PartialEq> Vec<T> {
/// Return true if a vector contains an element with the given value
impl<T: PartialEq> Vec<T> {
/// Returns true if a vector contains an element equal to the given value.
///
/// # Example
///
......@@ -1406,7 +1406,7 @@ pub fn contains(&self, x: &T) -> bool {
self.as_slice().contains(x)
}
/// Remove consecutive repeated elements in the vector.
/// Removes consecutive repeated elements in the vector.
///
/// If the vector is sorted, this removes all duplicates.
///
......@@ -1503,7 +1503,7 @@ pub fn dedup(&mut self) {
}
impl<T> Slice<T> for Vec<T> {
/// Work with `self` as a slice.
/// Returns a slice into `self`.
///
/// # Example
///
......@@ -1558,7 +1558,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
}
impl<T> MutableSeq<T> for Vec<T> {
/// Append an element to the back of a collection.
/// Appends an element to the back of a collection.
///
/// # Failure
///
......@@ -1654,14 +1654,12 @@ fn drop(&mut self) {
}
}
/**
* Convert an iterator of pairs into a pair of vectors.
*
* Returns a tuple containing two vectors where the i-th element of the first
* vector contains the first element of the i-th tuple of the input iterator,
* and the i-th element of the second vector contains the second element
* of the i-th tuple of the input iterator.
*/
/// Converts an iterator of pairs into a pair of vectors.
///
/// Returns a tuple containing two vectors where the i-th element of the first
/// vector contains the first element of the i-th tuple of the input iterator,
/// and the i-th element of the second vector contains the second element
/// of the i-th tuple of the input iterator.
pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
let (lo, _) = iter.size_hint();
let mut ts = Vec::with_capacity(lo);
......@@ -1673,7 +1671,7 @@ pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
(ts, us)
}
/// Unsafe operations
/// Unsafe vector operations.
pub mod raw {
use super::Vec;
use core::ptr;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册