| Documentation | Crate informations | Repository |
This crate provide traits to describe common operations available on data structures. This is particularly useful when building new types on top of generic data structures without relying on the actual implementation of the underlying data structure.
Here is an example of the kind of traits provided by this crate: ```rust /// Mutable collection where new elements can be inserted. pub trait Insert: Collection { /// The output of the insertion function. type Output;
/// Insert a new element in the collection.
fn insert(&mut self, element: Self::Item) -> Self::Output;
} ```
Such traits can be used to define collections with special properties,
independently of the actual internal data structure.
For instance the following code defines an Ordered<S> stack collection,
guarantying the well-sortedness of the elements in the stack.
```rust use cc_traits::{ Collection, Back, PushBack };
/// Ordered stack.
pub struct Ordered {
inner: S
}
impl Ordered {
pub fn new() -> Self where S: Default {
Ordered {
inner: S::default()
}
}
}
impl Ordered {
/// Push the given element on the stack iff it is grater or equal
/// to every other element already in the stack.
pub fn trypushS must be a stack providing back and push_back.
for<'a> S::ItemRef<'a>: PartialOrd<&'a T> // The reference type must be comparable with other reference types.
{
if self.inner.back().map(|back| back <= &element).unwrap
let mut vec: OrderedVec is a stack so it works.
assert!(vec.trypush(1).isok()); assert!(vec.trypush(2).isok()); assert!(vec.trypush(0).iserr());
use std::collections::VecDeque;
let mut deque: OrderedVecDeque is also a stack.
assert!(deque.trypush(1).isok()); assert!(deque.trypush(2).isok()); assert!(deque.trypush(0).iserr()); ```
By enabling the nightly you can get access to
some trait alias definitions that can be useful to reduce the
verbosity of your code.
Here is an example of such aliases defining the common interface of stacks:
rust
pub trait Stack<T> = Collection<Item=T> + Len + Back;
pub trait StackMut<T> = Stack<T> + BackMut + PushBack + PopBack;
By default, all the traits defined in this crate are implemented (when relevent)
for the standard library collections.
You can disable it by using the nostd feature.
In addition to the standard library, traits are implemented for some popular crates if you enable the feature of the same name. Here are the supported crates:
slab providing the Slab collection.smallvec providing the SmallVec collection.serde_json providing the Map<String, Value> collection for JSON objects.ijson providing the IObject and IArray collections.Licensed under either of
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.