[][src]Macro const_format::formatcp

macro_rules! formatcp {
    ($format_string:expr $( $(, $expr:expr )+ )? $(,)? ) => { ... };
}

Formats constants of primitive types into a &'static str

For examples look here

formatcp stands for "format constants (of) primitives"

Syntax

This macro uses a limited version of the syntax from the standard library format macro, it can do these things:

  • Take positional arguments: formatcp!("{}{0}", "hello" )

  • Take named arguments: formatcp!("{a}{a}", a = "hello" )

  • Use constants from scope as arguments: formatcp!("{FOO}"), equivalent to the format_args_implicits RFC

  • Use Debug-like formatting (eg: formatcp!("{:?}", "hello" ): Similar to how Debug formatting in the standard library works, except that it does not escape unicode characters.

  • Use Hexsadecimal formatting (eg: formatcp!("{:x}", "hello" )): Formats numbers as capitalized hexadecimal, The alternate version (written as "{:#x}"), prefixes the number with 0x

  • Use Binary formatting (eg: formatcp!("{:b}", "hello" )). The alternate version (written as "{:#b}"), prefixes the number with 0b

  • Use Display formatting: formatcp!("{}", "hello" )

Limitations

This macro can only take constants of these types as inputs:

  • &str

  • i*/u* (all the primitive integer types).

  • bool

This macro also shares the limitations described in here as well.

Format specifiers

Debug-like

The {:?} formatter formats things similarly to how Debug does it.

For &'static str it does these things:

  • Prepend and append the double quote character (").
  • Escape the '\t','\n','\r','\\', '\'', and'\"' characters.
  • Escape control characters with \xYY, where YY is the hexadecimal value of the control character.

Example:

use const_format::formatcp;

assert_eq!(formatcp!("{:?}", r#" \ " ó "#), r#"" \\ \" ó ""#);

Display

The {}/{:} formatter works the same as in format.

Examples

Implicit argument

use const_format::formatcp;

const NAME: &str = "John";

const MSG: &str = formatcp!("Hello {NAME}, your name is {} bytes long", NAME.len());

assert_eq!(MSG, "Hello John, your name is 4 bytes long");

Repeating arguments

use const_format::formatcp;

const MSG: &str = formatcp!("{0}{S}{0}{S}{0}", "SPAM", S = "   ");

assert_eq!(MSG, "SPAM   SPAM   SPAM");

Debug-like and Display formatting

use const_format::formatcp;

const TEXT: &str = r#"hello " \ world"#;
const MSG: &str = formatcp!("{TEXT}____{TEXT:?}");

assert_eq!(MSG, r#"hello " \ world____"hello \" \\ world""#);