diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 1d6714430a8ed..0d9e4f0a1c230 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -77,7 +77,7 @@ struct ArcInner { } impl Arc { - /// Create an atomically reference counted wrapper. + /// Creates an atomically reference counted wrapper. #[inline] #[stable] pub fn new(data: T) -> Arc { @@ -101,7 +101,7 @@ impl Arc { 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 Weak { /// /// 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> { // 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. diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 58278d5664e5e..6a3e1fa28620b 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -1,4 +1,4 @@ -// 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 @@ use core::result::{Ok, Err, Result}; /// /// 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 @@ impl Default for Box { #[unstable] impl Clone for Box { - /// Return a copy of the owned box. + /// Returns a copy of the owned box. #[inline] fn clone(&self) -> Box { 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) { (**self).clone_from(&(**source)); @@ -86,7 +88,7 @@ impl Ord for Box { } impl Eq for Box {} -/// 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`"] pub trait BoxAny { diff --git a/src/liballoc/heap.rs b/src/liballoc/heap.rs index 3175c516d8eff..e2faa3240ede7 100644 --- a/src/liballoc/heap.rs +++ b/src/liballoc/heap.rs @@ -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, 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; diff --git a/src/liballoc/lib.rs b/src/liballoc/lib.rs index 7809c17d93898..cacb9e28989ed 100644 --- a/src/liballoc/lib.rs +++ b/src/liballoc/lib.rs @@ -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 diff --git a/src/liballoc/libc_heap.rs b/src/liballoc/libc_heap.rs index 25938ba0d5448..e3fa639929f05 100644 --- a/src/liballoc/libc_heap.rs +++ b/src/liballoc/libc_heap.rs @@ -1,4 +1,4 @@ -// 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 diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 060f9875bfcf9..ec19844a24abd 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -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 - // ...other fields -} - -fn main() { - // Create a reference counted Owner. - let gadget_owner : Rc = 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>> - // ...other fields -} - -struct Gadget { - id: int, - owner: Rc - // ...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 = 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. 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 +//! // ...other fields +//! } +//! +//! fn main() { +//! // Create a reference counted Owner. +//! let gadget_owner : Rc = 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>> +//! // ...other fields +//! } +//! +//! struct Gadget { +//! id: int, +//! owner: Rc +//! // ...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 = 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. 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 { weak: Cell } -/// Immutable reference counted pointer type +/// An immutable reference-counted pointer type. #[unsafe_no_drop_flag] #[stable] pub struct Rc { @@ -184,7 +181,7 @@ pub struct Rc { #[stable] impl Rc { - /// Construct a new reference-counted box + /// Constructs a new reference-counted pointer. pub fn new(value: T) -> Rc { unsafe { Rc { @@ -206,8 +203,8 @@ impl Rc { } impl Rc { - /// 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 { self.inc_weak(); Weak { @@ -234,7 +231,7 @@ pub fn is_unique(rc: &Rc) -> 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(rc: Rc) -> Result> { /// /// Returns `None` if the `Rc` does not have unique ownership. /// -/// # Example: +/// # Example /// /// ``` /// use std::rc::{mod, Rc}; @@ -312,7 +309,7 @@ impl Rc { #[experimental = "Deref is experimental."] impl Deref for Rc { - /// 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 @@ impl fmt::Show for Rc { } } -/// 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 { @@ -417,7 +414,10 @@ pub struct Weak { #[experimental = "Weak pointers may not belong in this module."] impl Weak { - /// 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> { if self.strong() == 0 { None diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index 5d316cdb51e37..c2f4ef3ac30d7 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -7,7 +7,7 @@ // , 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 @@ impl Chunk { /// A slower reflection-based arena that can allocate objects of any type. /// -/// This arena uses Vec as a backing store to allocate objects from. For +/// This arena uses `Vec` 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 @@ impl Arena { } } - /// 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(&self, op: || -> T) -> &T { unsafe { @@ -438,13 +438,13 @@ impl TypedArenaChunk { } impl TypedArena { - /// 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 { 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 { @@ -456,7 +456,7 @@ impl TypedArena { } } - /// 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 { diff --git a/src/libcollections/bitv.rs b/src/libcollections/bitv.rs index 1b3c6e148cdc4..88859a598fb16 100644 --- a/src/libcollections/bitv.rs +++ b/src/libcollections/bitv.rs @@ -112,7 +112,7 @@ struct BigBitv { #[deriving(Clone)] enum BitvVariant { Big(BigBitv), Small(SmallBitv) } -/// The bitvector type +/// The bitvector type. /// /// # Example /// @@ -225,7 +225,7 @@ impl Bitv { } } - /// Create an empty Bitv. + /// Creates an empty `Bitv`. /// /// # Example /// @@ -237,7 +237,7 @@ impl 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 @@ -259,11 +259,11 @@ impl 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 /// @@ -286,11 +286,11 @@ impl Bitv { 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 /// @@ -311,7 +311,7 @@ impl Bitv { else { self.storage[w] & !flag }; } - /// Set all bits to 1. + /// Sets all bits to 1. /// /// # Example /// @@ -330,7 +330,7 @@ impl Bitv { for w in self.storage.mut_iter() { *w = !0u; } } - /// Flip all bits. + /// Flips all bits. /// /// # Example /// @@ -349,14 +349,15 @@ impl Bitv { 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 /// @@ -378,14 +379,15 @@ impl Bitv { 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 /// @@ -407,15 +409,15 @@ impl Bitv { 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 /// @@ -467,7 +469,7 @@ impl Bitv { (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 /// @@ -482,7 +484,7 @@ impl Bitv { 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 /// @@ -499,7 +501,7 @@ impl Bitv { self.mask_words(0).all(|(_, w)| w == 0) } - /// Return `true` if any bit is 1. + /// Returns `true` if any bit is 1. /// /// # Example /// @@ -517,9 +519,9 @@ impl Bitv { !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 @@ -562,7 +564,7 @@ impl Bitv { ) } - /// Transform `self` into a `Vec` by turning each bit into a `bool`. + /// Transforms `self` into a `Vec` by turning each bit into a `bool`. /// /// # Example /// @@ -577,11 +579,12 @@ impl Bitv { 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 /// @@ -603,7 +606,7 @@ impl Bitv { 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. @@ -629,7 +632,7 @@ impl Bitv { } } - /// 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 /// @@ -649,7 +652,7 @@ impl Bitv { } } - /// 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 @@ -666,7 +669,7 @@ impl Bitv { 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 /// @@ -707,7 +710,7 @@ impl Bitv { self.nbits = new_nbits; } - /// Shorten by one and return the removed element. + /// Shortens by one element and returns the removed element. /// /// # Failure /// @@ -734,7 +737,7 @@ impl Bitv { ret } - /// Push a `bool` onto the end. + /// Pushes a `bool` onto the end. /// /// # Example /// @@ -756,7 +759,7 @@ impl Bitv { } } -/// 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. /// @@ -779,7 +782,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 @@ -1038,7 +1041,7 @@ impl cmp::PartialEq for BitvSet { 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 /// @@ -1051,7 +1054,7 @@ impl 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 @@ -1066,7 +1069,7 @@ impl 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 /// @@ -1119,7 +1122,7 @@ impl BitvSet { bitv.reserve(size) } - /// Consume this set to return the underlying bit vector. + /// Consumes this set to return the underlying bit vector. /// /// # Example /// @@ -1139,7 +1142,7 @@ impl BitvSet { bitv } - /// Return a reference to the underlying bit vector. + /// Returns a reference to the underlying bit vector. /// /// # Example /// @@ -1158,7 +1161,7 @@ impl BitvSet { bitv } - /// Return a mutable reference to the underlying bit vector. + /// Returns a mutable reference to the underlying bit vector. /// /// # Example /// @@ -1204,7 +1207,7 @@ impl BitvSet { } } - /// Truncate the underlying vector to the least length required. + /// Truncates the underlying vector to the least length required. /// /// # Example /// @@ -1235,7 +1238,7 @@ impl BitvSet { bitv.nbits = trunc_len * uint::BITS; } - /// Iterator over each uint stored in the BitvSet. + /// Iterator over each uint stored in the `BitvSet`. /// /// # Example /// @@ -1376,7 +1379,7 @@ impl BitvSet { } } - /// Union in-place with the specified other bit vector. + /// Unions in-place with the specified other bit vector. /// /// # Example /// @@ -1399,7 +1402,7 @@ impl 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 /// @@ -1422,7 +1425,8 @@ impl 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 /// @@ -1452,7 +1456,8 @@ impl 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 /// diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index ca4b4ee6e8310..f6011976b65d0 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -1,4 +1,4 @@ -// 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 { } impl BTree { - - ///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 { BTree { root: Node::new_leaf(vec!(LeafElt::new(k, v))), @@ -55,8 +52,8 @@ impl BTree { } } - ///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, length: uint, lb: uint) -> BTree { @@ -69,17 +66,17 @@ impl BTree { } } -//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 BTree { - ///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 { 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 { let (a, b) = self.root.clone().insert(k, v, self.upper_bound.clone()); if b { @@ -98,8 +95,6 @@ impl BTree { } impl Clone for BTree { - ///Implements the Clone trait for the BTree. - ///Uses a helper function/constructor to produce a new BTree. fn clone(&self) -> BTree { BTree::new_with_node_len(self.root.clone(), self.len, self.lower_bound) } @@ -120,46 +115,46 @@ impl PartialOrd for BTree { } impl Ord for BTree { - ///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) -> Ordering { self.root.cmp(&other.root) } } impl fmt::Show for BTree { - ///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 { LeafNode(Leaf), BranchNode(Branch) } -//Node functions/methods impl Node { - ///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>) -> Node { 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>, right: Box>) -> Node { 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 @@ impl Node { } } - ///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 { match self { &LeafNode(ref leaf) => leaf.bsearch_leaf(k), @@ -178,8 +173,8 @@ impl Node { } impl Node { - ///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 { match *self { LeafNode(ref leaf) => return leaf.get(k), @@ -187,7 +182,7 @@ impl Node { } } - ///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, bool) { match self { LeafNode(leaf) => leaf.insert(k, v, ub), @@ -197,7 +192,7 @@ impl Node { } impl Clone for Node { - ///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 { match *self { LeafNode(ref leaf) => { @@ -242,7 +237,7 @@ impl PartialOrd for Node { } impl Ord for Node { - ///Implementation of Ord for Nodes. + /// Implementation of `Ord` for `Node`s. fn cmp(&self, other: &Node) -> Ordering { match *self { LeafNode(ref leaf) => { @@ -262,10 +257,10 @@ impl Ord for Node { } impl fmt::Show for Node { - ///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 @@ impl fmt::Show for Node { } -//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 { elts: Vec> } -//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 { elts: Vec>, rightmost_child: Box>, @@ -289,15 +284,15 @@ struct Branch { impl Leaf { - ///Creates a new Leaf from a vector of LeafElts. + /// Creates a new `Leaf` from a vector of `LeafElts`. fn new(vec: Vec>) -> Leaf { 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 { let mut high: uint = self.elts.len(); let mut low: uint = 0; @@ -349,7 +344,7 @@ impl Leaf { impl Leaf { - ///Returns the corresponding value to the supplied key. + /// Returns the corresponding value to the supplied key. fn get(&self, k: K) -> Option { for s in self.elts.iter() { let order = s.key.cmp(&k); @@ -361,7 +356,7 @@ impl Leaf { 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, bool) { let to_insert = LeafElt::new(k, v); let index: Option = self.bsearch_leaf(to_insert.clone().key); @@ -400,7 +395,7 @@ impl Leaf { } impl Clone for Leaf { - ///Returns a new Leaf with the same elts. + /// Returns a new `Leaf` with the same elts. fn clone(&self) -> Leaf { Leaf::new(self.elts.clone()) } @@ -421,7 +416,7 @@ impl PartialOrd for Leaf { } impl Ord for Leaf { - ///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) -> Ordering { if self.elts.len() > other.elts.len() { return Greater; @@ -435,7 +430,7 @@ impl Ord for Leaf { impl fmt::Show for Leaf { - ///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 @@ impl fmt::Show for Leaf { impl Branch { - ///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>, right: Box>) -> Branch { Branch { @@ -506,8 +501,8 @@ impl Branch { } impl Branch { - ///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 { for s in self.elts.iter() { let order = s.key.cmp(&k); @@ -520,7 +515,7 @@ impl Branch { 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, bool) { let mut new_branch = Node::new_branch(self.clone().elts, self.clone().rightmost_child); let mut outcome = false; @@ -630,7 +625,7 @@ impl Branch { } impl Clone for Branch { - ///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 { Branch::new(self.elts.clone(), self.rightmost_child.clone()) } @@ -651,7 +646,8 @@ impl PartialOrd for Branch { } impl Ord for Branch { - ///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) -> Ordering { if self.elts.len() > other.elts.len() { return Greater; @@ -664,7 +660,7 @@ impl Ord for Branch { } impl fmt::Show for Branch { - ///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 { } impl LeafElt { - ///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 { LeafElt { key: k, @@ -698,7 +694,7 @@ impl LeafElt { } impl Clone for LeafElt { - ///Returns a new LeafElt by cloning the key and value. + /// Returns a new `LeafElt` by cloning the key and value. fn clone(&self) -> LeafElt { LeafElt::new(self.key.clone(), self.value.clone()) } @@ -719,21 +715,21 @@ impl PartialOrd for LeafElt { } impl Ord for LeafElt { - ///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) -> Ordering { self.key.cmp(&other.key) } } impl fmt::Show for LeafElt { - ///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 BranchElt { - ///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>) -> BranchElt { BranchElt { left: n, @@ -745,7 +741,7 @@ impl BranchElt { impl Clone for BranchElt { - ///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 { BranchElt::new(self.key.clone(), self.value.clone(), @@ -768,15 +764,15 @@ impl PartialOrd for BranchElt { } impl Ord for BranchElt { - ///Fulfills Ord for BranchElts + /// Fulfills `Ord` for `BranchElts`. fn cmp(&self, other: &BranchElt) -> Ordering { self.key.cmp(&other.key) } } impl fmt::Show for BranchElt { - /// 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) diff --git a/src/libcollections/deque.rs b/src/libcollections/deque.rs index c56b265b43aca..d7970ed8d60c3 100644 --- a/src/libcollections/deque.rs +++ b/src/libcollections/deque.rs @@ -1,4 +1,4 @@ -// 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>(n: uint, - map: &mut M, - b: &mut Bencher) { + pub fn insert_rand_n>(n: uint, + map: &mut M, + b: &mut Bencher) { // setup let mut rng = rand::weak_rng(); @@ -37,9 +37,9 @@ pub mod bench { }) } - pub fn insert_seq_n>(n: uint, - map: &mut M, - b: &mut Bencher) { + pub fn insert_seq_n>(n: uint, + map: &mut M, + b: &mut Bencher) { // setup map.clear(); for i in range(0u, n) { diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 6f47780a0e6f5..2899bdc0ddb6f 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -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 { value: T, } -/// Double-ended DList iterator +/// An iterator over references to the items of a `DList`. pub struct Items<'a, T> { head: &'a Link, tail: Rawlink>, @@ -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, head: Rawlink>, @@ -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 { list: DList @@ -130,12 +130,17 @@ fn link_with_prev(mut next: Box>, prev: Rawlink>) } impl Collection for DList { - /// 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 @@ impl Collection for DList { } impl Mutable for DList { - /// 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 @@ impl DList { } impl Deque for DList { - /// 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 { self.pop_front_node().map(|box Node{value, ..}| value) } @@ -267,15 +277,15 @@ impl Default for DList { } impl DList { - /// Create an empty DList + /// Creates an empty `DList`. #[inline] pub fn new() -> DList { 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 @@ impl DList { }); } - /// 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 @@ impl DList { }); } - /// 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 @@ impl DList { } } - /// 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 @@ impl DList { 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 @@ impl DList { } } - /// 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, f: |&T, &T| -> bool) { { let mut it = self.mut_iter(); @@ -458,13 +469,13 @@ impl DList { } - /// 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 @@ impl DList { } - /// 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 { MoveItems{list: self} @@ -488,9 +499,9 @@ impl DList { } impl DList { - /// 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 @@ impl<'a, A> DoubleEndedIterator<&'a mut A> for MutItems<'a, 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 { - /// 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>; } diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index ca3f6a746f335..12456e9f79de9 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -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 { // We must maintain the invariant that no bits are set // for which no variant exists @@ -25,9 +25,9 @@ pub struct EnumSet { /// 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: E) -> uint { } impl EnumSet { - /// Returns an empty EnumSet. + /// Returns an empty `EnumSet`. pub fn empty() -> EnumSet { 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) -> bool { (self.bits & e.bits) != 0 } - /// Returns an intersection of both EnumSets. + /// Returns the intersection of both `EnumSets`. pub fn intersection(&self, e: EnumSet) -> EnumSet { 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) -> 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) -> EnumSet { 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 { Items::new(self.bits) } diff --git a/src/libcollections/hash/mod.rs b/src/libcollections/hash/mod.rs index 4ce39a683aea7..b867bb7be0422 100644 --- a/src/libcollections/hash/mod.rs +++ b/src/libcollections/hash/mod.rs @@ -77,18 +77,18 @@ pub use self::sip::hash as hash; 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 { - /// 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 { - /// Compute a hash of the value. + /// Compute the hash of a value. fn hash>(&self, value: &T) -> u64; } diff --git a/src/libcollections/hash/sip.rs b/src/libcollections/hash/sip.rs index b31d811c2c966..09a0edd9e3a9a 100644 --- a/src/libcollections/hash/sip.rs +++ b/src/libcollections/hash/sip.rs @@ -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 @@ macro_rules! compress ( ) 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 @@ impl 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 @@ impl SipState { 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 @@ impl Default for SipHasher { } } -/// Hash a value using the SipHash algorithm. +/// Hashes a value using the SipHash algorithm. #[inline] pub fn hash>(value: &T) -> u64 { let mut state = SipState::new(); @@ -259,7 +257,7 @@ pub fn hash>(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>(k0: u64, k1: u64, value: &T) -> u64 { let mut state = SipState::new_with_keys(k0, k1); diff --git a/src/libcollections/lib.rs b/src/libcollections/lib.rs index 5fdcee14f891e..a98d9ddb9db02 100644 --- a/src/libcollections/lib.rs +++ b/src/libcollections/lib.rs @@ -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 @@ pub mod hash; 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: 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: 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 @@ pub trait Map: Collection { } } -/// 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: Map + 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 @@ pub trait MutableMap: Map + Mutable { 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 @@ pub trait MutableMap: Map + Mutable { 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 @@ pub trait MutableMap: Map + Mutable { /// ``` fn pop(&mut self, k: &K) -> Option; - /// 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 @@ pub trait MutableMap: Map + Mutable { 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: 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: 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: 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: 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 @@ pub trait Set: Collection { // 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: Set + 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: Set + 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: Set + Mutable { } pub trait MutableSeq: 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: 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: Mutable { /// } /// ``` pub trait Deque : MutableSeq { - /// 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 : MutableSeq { /// ``` 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 : MutableSeq { /// ``` 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 : MutableSeq { /// ``` 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 : MutableSeq { /// ``` 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 : MutableSeq { /// ``` 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 : MutableSeq { #[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 @@ pub trait Deque : MutableSeq { #[deprecated = "use the `pop` method"] fn pop_back(&mut self) -> Option { 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 /// diff --git a/src/libcollections/macros.rs b/src/libcollections/macros.rs index db062a70bbb67..ba8b3b8c7d3e4 100644 --- a/src/libcollections/macros.rs +++ b/src/libcollections/macros.rs @@ -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. diff --git a/src/libcollections/priority_queue.rs b/src/libcollections/priority_queue.rs index 34cc02258157f..eedb61c0712de 100644 --- a/src/libcollections/priority_queue.rs +++ b/src/libcollections/priority_queue.rs @@ -167,12 +167,12 @@ pub struct PriorityQueue { } impl Collection for PriorityQueue { - /// Returns the length of the queue + /// Returns the length of the queue. fn len(&self) -> uint { self.data.len() } } impl Mutable for PriorityQueue { - /// Drop all items from the queue + /// Drops all items from the queue. fn clear(&mut self) { self.data.truncate(0) } } @@ -182,7 +182,7 @@ impl Default for PriorityQueue { } impl PriorityQueue { - /// Create an empty PriorityQueue as a max-heap. + /// Creates an empty `PriorityQueue` as a max-heap. /// /// # Example /// @@ -192,9 +192,9 @@ impl PriorityQueue { /// ``` pub fn new() -> PriorityQueue { 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 @@ impl PriorityQueue { 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 @@ impl PriorityQueue { 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 @@ impl PriorityQueue { /// ``` 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 @@ impl PriorityQueue { /// ``` 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 @@ impl PriorityQueue { 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 @@ impl PriorityQueue { #[deprecated="renamed to `pop`"] pub fn maybe_pop(&mut self) -> Option { self.pop() } - /// Push an item onto the queue. + /// Pushes an item onto the queue. /// /// # Example /// @@ -360,7 +360,8 @@ impl PriorityQueue { 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 @@ impl PriorityQueue { 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 @@ impl PriorityQueue { #[deprecated="renamed to `into_sorted_vec`"] fn to_sorted_vec(self) -> Vec { 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 @@ impl PriorityQueue { /// ``` pub fn into_vec(self) -> Vec { 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 @@ impl PriorityQueue { } } -/// PriorityQueue iterator. +/// `PriorityQueue` iterator. pub struct Items <'a, T> { iter: slice::Items<'a, T>, } diff --git a/src/libcollections/ringbuf.rs b/src/libcollections/ringbuf.rs index 9d074813343b3..c9b60e67edde3 100644 --- a/src/libcollections/ringbuf.rs +++ b/src/libcollections/ringbuf.rs @@ -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 @@ use vec::Vec; 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 { nelts: uint, @@ -36,12 +36,12 @@ pub struct RingBuf { } impl Collection for RingBuf { - /// Return the number of elements in the RingBuf + /// Returns the number of elements in the `RingBuf`. fn len(&self) -> uint { self.nelts } } impl Mutable for RingBuf { - /// 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 @@ impl Mutable for RingBuf { } impl Deque for RingBuf { - /// 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 { let result = self.elts.get_mut(self.lo).take(); if result.is_some() { @@ -81,7 +82,7 @@ impl Deque for RingBuf { 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 @@ impl Default for RingBuf { } impl RingBuf { - /// Create an empty RingBuf + /// Creates an empty `RingBuf`. pub fn new() -> RingBuf { 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 { 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 @@ impl RingBuf { } } - /// 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 @@ impl RingBuf { } } - /// 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 @@ impl RingBuf { 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 @@ impl RingBuf { 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 @@ impl RingBuf { } } -/// RingBuf iterator +/// `RingBuf` iterator. pub struct Items<'a, T> { lo: uint, index: uint, @@ -352,7 +346,7 @@ impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> { } } -/// RingBuf mutable iterator +/// `RingBuf` mutable iterator. pub struct MutItems<'a, T> { remaining1: &'a mut [Option], remaining2: &'a mut [Option], @@ -437,7 +431,7 @@ fn grow(nelts: uint, loptr: &mut uint, elts: &mut Vec>) { } } -/// 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 diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index 7190bbfbc012c..c137cc25b252a 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -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 use core::slice::{Found, NotFound}; pub trait VectorVector { // 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`. fn concat_vec(&self) -> Vec; /// Concatenate a vector of vectors, placing a given separator between each. @@ -138,7 +134,7 @@ impl<'a, T: Clone, V: Slice> VectorVector for &'a [V] { } } -/// 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 @@ impl<'a, T: Clone, V: Slice> VectorVector for &'a [V] { /// sequence to its initial order. pub struct ElementSwaps { sdir: Vec, - /// 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 @@ impl 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 @@ impl Iterator<(uint, uint)> for ElementSwaps { } } -/// 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 @@ impl Iterator> for Permutations { /// Extension methods for vector slices with cloneable elements pub trait CloneableVector { - /// Copy `self` into a new vector + /// Copies `self` into a new `Vec`. fn to_vec(&self) -> Vec; - /// Deprecated. Use `to_vec` + /// Deprecated. Use `to_vec`. #[deprecated = "Replaced by `to_vec`"] fn to_owned(&self) -> Vec { 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; /// Deprecated. Use `into_vec` @@ -283,7 +280,6 @@ pub trait CloneableVector { } } -/// Extension methods for vector slices impl<'a, T: Clone> CloneableVector for &'a [T] { /// Returns a copy of `v`. #[inline] @@ -295,11 +291,11 @@ impl<'a, T: Clone> CloneableVector for &'a [T] { /// Extension methods for vectors containing `Clone` elements. pub trait ImmutableCloneableVector { - /// 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, Vec); - /// 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 @@ fn merge_sort(v: &mut [T], compare: |&T, &T| -> Ordering) { /// 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, start: uint, end: uint) -> uint; } @@ -622,7 +616,7 @@ impl<'a,T> MutableSliceAllocating<'a, T> for &'a mut [T] { /// Methods for mutable vectors with orderable elements, such as /// in-place sorting. pub trait MutableOrdSlice { - /// 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 { /// 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 { /// 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 /// diff --git a/src/libcollections/smallintmap.rs b/src/libcollections/smallintmap.rs index 44db9147226b0..534262d79c94d 100644 --- a/src/libcollections/smallintmap.rs +++ b/src/libcollections/smallintmap.rs @@ -66,24 +66,24 @@ pub struct SmallIntMap { } impl Collection for SmallIntMap { - /// 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 Mutable for SmallIntMap { - /// Clear the map, removing all key-value pairs. + /// Clears the map, removing all key-value pairs. fn clear(&mut self) { self.v.clear() } } impl Map for SmallIntMap { - /// 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 @@ impl Map for SmallIntMap { } impl MutableMap for SmallIntMap { - /// 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 @@ impl MutableMap for SmallIntMap { } } - /// 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 @@ impl MutableMap for SmallIntMap { !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 { match self.find_mut(&key) { @@ -176,7 +176,7 @@ impl > Hash for SmallIntMap { } impl SmallIntMap { - /// Create an empty SmallIntMap. + /// Creates an empty `SmallIntMap`. /// /// # Example /// @@ -186,8 +186,8 @@ impl SmallIntMap { /// ``` pub fn new() -> SmallIntMap { 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 @@ impl SmallIntMap { 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 @@ impl SmallIntMap { } } - /// 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 @@ impl SmallIntMap { } } - /// 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 @@ impl SmallIntMap { } impl SmallIntMap { - /// 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 @@ impl SmallIntMap { 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 /// diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index 9ca1011f1666a..9120b3889e77f 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -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 @@ pub use unicode::str::{UnicodeStrSlice, Words, Graphemes, GraphemeIndices}; 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) -> Result> { 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 @@ impl<'a> Iterator for Recompositions<'a> { } } -/// Replace all occurrences of one string with another +/// Replaces all occurrences of one string with another. /// /// # Arguments /// @@ -404,7 +400,7 @@ impl<'a> Iterator for Recompositions<'a> { /// /// # 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 @@ impl<'a> MaybeOwned<'a> { } } - /// Returns `true` if this `MaybeOwned` wraps a borrowed string + /// Returns `true` if this `MaybeOwned` wraps a borrowed string. /// /// # Example /// @@ -513,47 +509,47 @@ impl<'a> MaybeOwned<'a> { } } -/// 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 @@ impl<'a> fmt::Show for MaybeOwned<'a> { } } -/// Unsafe operations +/// Unsafe string operations. pub mod raw { use string; use string::String; @@ -685,9 +681,9 @@ pub mod raw { 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 @@ pub trait StrAllocating: Str { 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 @@ pub trait StrAllocating: Str { 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 @@ pub trait StrAllocating: Str { out } - /// Replace all occurrences of one string with another. + /// Replaces all occurrences of one string with another. /// /// # Arguments /// @@ -768,7 +764,7 @@ pub trait StrAllocating: Str { self.as_slice().utf16_units().collect::>() } - /// 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 @@ pub trait StrAllocating: Str { 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 @@ pub trait StrAllocating: Str { 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 @@ pub trait StrAllocating: Str { } } - /// 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> { diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 66973fd410079..89fdc4d42fb88 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -120,8 +120,8 @@ impl String { } } - /// 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 @@ impl 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 @@ impl String { 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 @@ impl 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 @@ impl String { 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 @@ impl String { 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` - /// * We assume that the `Vec` contains valid UTF-8 + /// * We call `Vec::from_raw_parts` to get a `Vec`; + /// * 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 mod raw { } } - /// 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 mod raw { 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 mod raw { /// 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) -> String { String { vec: bytes } diff --git a/src/libcollections/treemap.rs b/src/libcollections/treemap.rs index 7787893925d53..4ab33b05aaa63 100644 --- a/src/libcollections/treemap.rs +++ b/src/libcollections/treemap.rs @@ -261,7 +261,7 @@ impl Index for TreeMap { }*/ impl TreeMap { - /// Create an empty `TreeMap`. + /// Creates an empty `TreeMap`. /// /// # Example /// @@ -271,7 +271,7 @@ impl TreeMap { /// ``` pub fn new() -> TreeMap { 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 @@ impl TreeMap { 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 @@ impl TreeMap { 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 @@ impl TreeMap { } } - /// 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 @@ impl TreeMap { 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 @@ impl TreeMap { 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 @@ impl TreeMap { } - /// 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 @@ impl TreeMap { } impl TreeMap { - /// 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 @@ impl TreeMap { 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 @@ macro_rules! bound_setup { impl TreeMap { - /// 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 @@ impl TreeMap { } } - /// 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 @@ impl TreeMap { 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 @@ impl TreeMap { 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 @@ impl TreeMap { } } - /// 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 @@ impl TreeMap { 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 @@ impl TreeMap { } } -/// Lazy forward iterator over a map +/// A lazy forward iterator over a map. pub struct Entries<'a, K, V> { stack: Vec<&'a TreeNode>, // 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>, @@ -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 @@ macro_rules! define_iterator { // 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(x: &mut Option>>) -/// 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 { stack: Vec>, remaining: uint @@ -951,7 +951,7 @@ impl<'a, T> Iterator<&'a T> for RevSetItems<'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 @@ impl Default for TreeSet { } impl TreeSet { - /// Create an empty `TreeSet`. + /// Creates an empty `TreeSet`. /// /// # Example /// @@ -1132,7 +1132,7 @@ impl TreeSet { #[inline] pub fn new() -> TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { 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 @@ impl TreeSet { } } -/// 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 = iter::Map<'static, (T, ()), T, MoveEntries>; -/// 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(x: Option<&T>, y: Option<&T>, short: Ordering, long: Ordering) -> Ordering { match (x, y) { diff --git a/src/libcollections/trie.rs b/src/libcollections/trie.rs index 911262e90cba7..7943c1da2c890 100644 --- a/src/libcollections/trie.rs +++ b/src/libcollections/trie.rs @@ -121,13 +121,13 @@ impl Show for TrieMap { } impl Collection for TrieMap { - /// Return the number of elements in the map. + /// Returns the number of elements in the map. #[inline] fn len(&self) -> uint { self.length } } impl Mutable for TrieMap { - /// 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 @@ impl Mutable for TrieMap { } impl Map for TrieMap { - /// 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 = &self.root; @@ -159,14 +159,14 @@ impl Map for TrieMap { } impl MutableMap for TrieMap { - /// 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 { let ret = insert(&mut self.root.count, &mut self.root.children[chunk(key, 0)], @@ -192,7 +192,7 @@ impl Default for TrieMap { } impl TrieMap { - /// Create an empty TrieMap. + /// Creates an empty `TrieMap`. /// /// # Example /// @@ -205,8 +205,8 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl TrieMap { 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 @@ impl Show for TrieSet { } 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 @@ impl Default for TrieSet { } impl TrieSet { - /// Create an empty TrieSet. + /// Creates an empty TrieSet. /// /// # Example /// @@ -629,8 +629,8 @@ impl 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 @@ impl TrieSet { 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 @@ impl TrieSet { 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 @@ impl TrieSet { 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(count: &mut uint, child: &mut Child, 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>, .. 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>, .. 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 @@ macro_rules! iterator_impl { 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, ()> } diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 6e4f2bc54819a..d67a01b6dee2d 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -190,7 +190,7 @@ impl Vec { } } - /// Create a `Vec` directly from the raw constituents. + /// Creates a `Vec` directly from the raw constituents. /// /// This is highly unsafe: /// @@ -399,7 +399,7 @@ impl Vec { /// 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 @@ impl Vec { } } - /// 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 @@ impl Vec { } } - /// Work with `self` as a mutable slice. + /// Returns a mutable slice of the elements of `self`. /// /// # Example /// @@ -841,7 +841,7 @@ impl Vec { 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 @@ impl Vec { 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 @@ impl Vec { self.pop() } - /// Prepend an element to the vector. + /// Prepends an element to the vector. /// /// # Warning /// @@ -1014,8 +1014,8 @@ impl Vec { 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 @@ impl Vec { } } - /// 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 @@ impl Vec { 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 @@ impl Vec { 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 @@ impl Vec { 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 @@ impl Vec { 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 @@ impl Mutable for Vec { } } -impl Vec { - /// Return true if a vector contains an element with the given value +impl Vec { + /// Returns true if a vector contains an element equal to the given value. /// /// # Example /// @@ -1406,7 +1406,7 @@ impl Vec { 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 @@ impl Vec { } impl Slice for Vec { - /// Work with `self` as a slice. + /// Returns a slice into `self`. /// /// # Example /// @@ -1558,7 +1558,7 @@ impl fmt::Show for Vec { } impl MutableSeq for Vec { - /// Append an element to the back of a collection. + /// Appends an element to the back of a collection. /// /// # Failure /// @@ -1654,14 +1654,12 @@ impl Drop for MoveItems { } } -/** - * 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>(mut iter: V) -> (Vec, Vec) { let (lo, _) = iter.size_hint(); let mut ts = Vec::with_capacity(lo); @@ -1673,7 +1671,7 @@ pub fn unzip>(mut iter: V) -> (Vec, Vec) { (ts, us) } -/// Unsafe operations +/// Unsafe vector operations. pub mod raw { use super::Vec; use core::ptr;