macro_rules! staticstring {
    ($val:expr) => { ... };
    ($val:expr, $n:expr) => { ... };
}
Expand description

Creates a new StaticString from an &str literal. This macro can be used in const contexts, in keeping with the other ones in this crate.

The staticstring! macro comes in two forms: one that solely takes an &str literal, where the resulting StaticString will have a total capacity and initial length exactly equal to the number of bytes in the literal, and one that takes an additional integral constant which is then used to specify the constant-generic capacity independently from the length of the input string.

Implementing it this way allows the macro to be more flexible than would otherwise be possible due to the required level of type inference being beyond what the compiler is (currently at least) capable of.

Example usage:

use staticvec::{staticstring, StaticString};

// Usage at runtime, creating a `StaticString` with both a length and capacity of 10:
let s1 = staticstring!("ABCDEFGHIJ");
assert_eq!(s1, "ABCDEFGHIJ");

// Usage at runtime, creating a `StaticString` with a length of 10 but a capacity of 20:
let s2 = staticstring!("ABCDEFGHIJ", 20);
assert_eq!(s2, "ABCDEFGHIJ");

// Usage at compile time, creating a `StaticString` with both a length and capacity of 10:
const S3: StaticString<10> = staticstring!("ABCDEFGHIJ");
assert_eq!(S3, "ABCDEFGHIJ");

// Usage at compile time, creating a `StaticString` with a length of 18 but a capacity of 36,
// keeping in mind that length is measured in bytes and not characters of course:
const S4: StaticString<36> = staticstring!("BC🤔BC🤔BC🤔", 36);
assert_eq!(S4, "BC🤔BC🤔BC🤔");
assert_eq!(S4.len(), 18);
assert_eq!(S4.capacity(), 36);

// Differing length and capacity in the context of compile-time initialization is more useful
// with `static mut` variables than it is `const` or regular `static` variables, obviously. For
// example:
static mut S5: StaticString<8> = staticstring!("ABCD", 8);
unsafe {
  assert_eq!(S5, "ABCD");
  assert_eq!(S5.len(), 4);
  assert_eq!(S5.capacity(), 8);
  assert_eq!(S5.remaining_capacity(), 4);
  S5.push_str("EFGH");
  assert_eq!(S5, "ABCDEFGH");
  assert_eq!(S5.len(), 8);
  assert_eq!(S5.remaining_capacity(), 0);
}

Note that attempting to explicitly provide a capacity that is less than the number of bytes in the input string will fail a compile-time static assertion in both const and runtime contexts.

For example, this would give a compile-time error:

const S5: StaticString<1> = staticstring!("ABCDEFG", 1);

As would the following:

let s6 = staticstring!("🤔🤔🤔🤔🤔🤔", 0);