Macro shadow_rs::str_get

source ·
macro_rules! str_get {
    ($string:expr, $index:expr $(,)*) => { ... };
}
Expand description

Indexes a &'static str constant, returning None when the index is not on a character boundary.

§Signature

This macro acts like a function of this signature:

fn str_get(input: &'static str, range: impl SomeIndex) -> Option<&'static str>

and is evaluated at compile-time.

This accepts the same range arguments as str_splice

§Example

use const_format::str_get;

use std::ops::RangeFrom;

assert_eq!(str_get!("foo 鉄 baz", ..7), Some("foo 鉄"));
assert_eq!(str_get!("foo 鉄 baz", 4..7), Some("鉄"));
assert_eq!(str_get!("foo 鉄 baz", 4..100), None);


{
    const IN: &str = "hello 鉄";
    const INDEX: RangeFrom<usize> = 6..;
    // You can pass `const`ants to this macro, not just literals
    const OUT: Option<&str> = str_get!(IN, INDEX);
    assert_eq!(OUT, Some("鉄"));
}
{
    const OUT: Option<&str> = str_get!("hello 鉄", 4);
    assert_eq!(OUT, Some("o"));
}
{
    // End index not on a character boundary
    const OUT: Option<&str> = str_get!("hello 鉄", 0..7);
    assert_eq!(OUT, None);
}
{
    // Out of bounds indexing
    const OUT: Option<&str> = str_get!("hello 鉄", 0..1000 );
    assert_eq!(OUT, None);
}