Skip to main content

Crate try_index

Crate try_index 

Source
Expand description

A boilerplate library that provides traits TryIndex and TryIndexMut. Unlike the ones in try_traits, this gives explicit implementations for all standard library collections, which can actually fail. In exchange, no blanket implementation is provided.

The idea is to provide a single definition of these traits that other crates may use to interface with each other in a generic way, while carrying no further code with it.

This crate has a default std feature that may be disabled for no_std support, as well as an alloc feature that enables no_std alloc container types.

§Examples

§Basic usage

The methods in this crate return None on failure rather than panicking.

use try_index::*;

let foo = vec![4, 3, 6, 2];
assert_eq!(foo.try_index(2), Some(&6));
assert_eq!(foo.try_index(4), None);
assert_eq!(foo.try_index(1..=2), Some(&[3, 6][..]));

§Implementing on custom type

With this, you can provide fallible indexing for your own types.

use try_index::*;

struct YourType {
}

impl TryIndex<usize> for YourType {
    type Output = u8;
     
    fn try_index(&self, index: usize) -> Option<&Self::Output> {
        todo!() // your implementation
    }
}

let foo = YourType {};
// now, simply call foo.try_index()

§Implementing on third-party type

This allows you to glue together libraries not providing TryIndex and others requiring it, within your code.

use try_index::*;

// defined elsewhere
pub struct NotYourType {
}

// can't implement directly, so we use a wrapper
#[repr(transparent)]
struct YourWrapper<'a> {
    inner: &'a NotYourType,
}

impl<'a> TryIndex<usize> for YourWrapper<'a> {
    type Output = u8;
     
    fn try_index(&self, index: usize) -> Option<&Self::Output> {
        todo!() // your implementation
    }
}

let foo = NotYourType {};
let wrapper = YourWrapper {inner: &foo};
// now, call wrapper.try_index() or pass wrapper around

Traits§

TryIndex
A fallible version of Index that will return None if the indexing operation fails.
TryIndexMut
A fallible version of IndexMut that will return None if the indexing operation fails.