[−][src]Crate index_ext
Adds more index types.
There are cases where an index type might not be usize
, many of them for compatibility
reasons. For example, an archive format may choose to always represent its offsets as u32
or
the io::Seek
trait which uses i64
for that purpose. Translating these indices into the
platform native offset type is error prone, potentially lossy, and in case it is done
incorrectly leads to subtle platform dependent bugs.
Wouldn't it be better for this conversion to happen implicitly and correctly where the actual
indexing takes place? That's precisely what Index
provides. (It's a method and a trait of
the same name, for both panicking and fallible accessors).
use index_ext::Int; let fine = [0u8; 2][Int(1u32)]; let also = [0u8; 2][Int(1u128)]; assert_eq!([0u8; 2].get_int(u128::max_value()), None);
Nightly features
- The
RangeTo
type is a const generics enabled index that return arrays[T; N]
instead of slices. Due to recent advances in parameter deduction, the length parameter need not even be named.
use index_ext::array::RangeTo; // Grab an array of three element from a slice. let [r, g, b] = &slice[RangeTo];
Unfinished features
The marker WIP means it is worked on, Planned that it will be worked on, and Idea that it is still unevaluated but might be interesting.
[Planned]: An index type CharAt(n: usize)
that dereferences to the characters of a string at
a particular position, represented by a string wrapper that allows converting into a char
.
Note that a generic Chars
would not be constant time which may be surprising if used in index
position.
[Idea]: An index type InsertWith
for HashMap
and BTreeMap
that will construct an
element when an entry is missing, similar to C++, and thus be a panic free alternative. Maybe
we could index a Vec<_>
with this type as well, extending as necessary, but this would again
not be constant time.
[Idea]: An adapter OrEmpty
that uses get
internally and substitutes an empty slice instead
of panicking.
Design notes
The extension traits offered here have a slight ergonomic problem compared to being included in
the standard library. Its ops::Index
impls on slices are provided by the SliceIndex
trait.
Since this is a nightly trait and sealed by design we can not use it. However, we also can
not use a generic impl for all T: crate::SliceIndex<[U]>
as this is forbidden by coherence
rules for foreign types. We thus utilize two kinds of indexing: Implement the Index trait
directly for all concrete applicable types and provide a single newtype which acts as a proxy
for the otherwise unconstrained type parameter of the generic impl. If the types were added to
core
then this indirection would not be necessary and ergonomics would improve.
Modules
int |
Traits
Int | An extension trait allowing slices to be indexed by everything convertible to |
IntSliceIndex | A trait for integer based indices. |
Functions
Int | Convert an arbitrary integer into an index. |