pub enum Index {
Num(usize),
Next,
}
Expand description
Represents an abstract index into an array.
If provided an upper bound with Self::for_len
or Self::for_len_incl
,
will produce a concrete numerical index.
Variants§
Num(usize)
A non-negative integer value
Next
The -
token, the position of the next would-be item in the array
Implementations§
Source§impl Index
impl Index
Sourcepub fn for_len(&self, length: usize) -> Result<usize, OutOfBoundsError>
pub fn for_len(&self, length: usize) -> Result<usize, OutOfBoundsError>
Bounds the index for a given array length (exclusive).
The upper range is exclusive, so only indices that are less than the given length will be accepted as valid. This ensures that the resolved numerical index can be used to access an existing array element.
Self::Next
, by consequence, is always considered invalid, since
it resolves to the array length itself.
See also Self::for_len_incl
for an alternative if you wish to accept
Self::Next
(or its numerical equivalent) as valid.
§Examples
assert_eq!(Index::Num(0).for_len(1), Ok(0));
assert!(Index::Num(1).for_len(1).is_err());
assert!(Index::Next.for_len(1).is_err());
§Errors
Returns OutOfBoundsError
if the index is out of bounds.
Sourcepub fn for_len_incl(&self, length: usize) -> Result<usize, OutOfBoundsError>
pub fn for_len_incl(&self, length: usize) -> Result<usize, OutOfBoundsError>
Bounds the index for a given array length (inclusive).
The upper range is inclusive, so an index pointing to the position after the last element will be considered valid. Be careful when using the resulting numerical index for accessing an array.
Self::Next
is always considered valid.
See also Self::for_len
for an alternative if you wish to ensure that
the resolved index can be used to access an existing array element.
§Examples
assert_eq!(Index::Num(1).for_len_incl(1), Ok(1));
assert_eq!(Index::Next.for_len_incl(1), Ok(1));
assert!(Index::Num(2).for_len_incl(1).is_err());
§Errors
Returns OutOfBoundsError
if the index is out of bounds.
Sourcepub fn for_len_unchecked(&self, length: usize) -> usize
pub fn for_len_unchecked(&self, length: usize) -> usize
Resolves the index for a given array length.
No bound checking will take place. If you wish to ensure the
index can be used to access an existing element in the array, use
Self::for_len
- or use Self::for_len_incl
if you wish to accept
Self::Next
as valid as well.
§Examples
assert_eq!(Index::Num(42).for_len_unchecked(30), 42);
assert_eq!(Index::Next.for_len_unchecked(30), 30);
// no bounds checks
assert_eq!(Index::Num(34).for_len_unchecked(40), 34);
assert_eq!(Index::Next.for_len_unchecked(34), 34);