Macro esp_idf_svc::sys::const_format::str_splice

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

Replaces a substring in a &'static str constant. Returns both the new resulting &'static str, and the replaced substring.

§Signature

This macro acts like a function of this signature:

fn str_splice(
    input: &'static str,
    range: impl SomeIndex,
    replace_with: &'static str,
) -> const_format::SplicedStr

and is evaluated at compile-time.

§range argument

The range parameter determines what part of input is replaced, and can be any of these types:

  • usize: the starting index of a char, only includes that char.
  • Range<usize>
  • RangeTo<usize>
  • RangeFrom<usize>
  • RangeInclusive<usize>
  • RangeToInclusive<usize>
  • RangeFull

SplicedStr contains:

  • output: a &'static str with the substring at range in input replaced with replace_with.
  • removed: the substring at range in input.

§Example

use const_format::{str_splice, SplicedStr};

const OUT: SplicedStr = str_splice!("foo bar baz", 4..=6, "is");
assert_eq!(OUT , SplicedStr{output: "foo is baz", removed: "bar"});

// You can pass `const`ants to this macro, not just literals
{
    const IN: &str = "this is bad";
    const INDEX: std::ops::RangeFrom<usize> = 8..;
    const REPLACE_WITH: &str = "... fine";
    const OUT: SplicedStr = str_splice!(IN, INDEX, REPLACE_WITH);
    assert_eq!(OUT , SplicedStr{output: "this is ... fine", removed: "bad"});
}
{
    const OUT: SplicedStr = str_splice!("ABC豆-", 3, "DEFGH");
    assert_eq!(OUT , SplicedStr{output: "ABCDEFGH-", removed: "豆"});
}

§Invalid index

Invalid indices cause compilation errors.

const_format::str_splice!("foo", 0..10, "");