#string #replace #format #compile #macro #procedural #proc-macro

macro exact_format

A procedural macro for compile time string replacement without using the standard format placeholder syntax ({}). This is most useful when dealing with strings that contain { } blocks you do no wish to interpolate e.g. writing javascript.

2 releases

new 0.2.1 Mar 7, 2025
0.2.0 Mar 7, 2025

#389 in Procedural macros

Download history 119/week @ 2025-03-02

119 downloads per month

Apache-2.0

8KB
103 lines

exact_format

A procedural macro for compile time string replacement without using the standard format placeholder syntax ({}). This is most useful when dealing with strings that contain { } blocks you do no wish to interpolate e.g. writing javascript.

Usage

The exact_format! macro allows you to replace exact string matches within a template:

use exact_format::exact_format;

// Basic replacement
let result = exact_format!("Hello {name}", "{name}" => "World");
assert_eq!(result, "Hello World");

// JavaScript-style template string replacement
let user_id = 42;
let user_name = "John";
let result = exact_format!("const user = { id: USERID, name: 'USERNAME' };",
                         "USERID" => user_id.to_string(),
                         "USERNAME" => user_name);
assert_eq!(result, "const user = { id: 42, name: 'John' };");

How It Works

The macro expands to a format! call that handles the replacements. For example:

exact_format!("const user = { id: USERID, name: 'USERNAME' };",
             "USERID" => user_id.to_string(),
             "USERNAME" => user_name);

Expands to:

{
    let __value0__ = user_id.to_string();
    let __value1__ = user_name;
    format!("{}{}{}{}{}",
            "const user = { id: ",
            __value0__,
            ", name: '",
            __value1__,
            "' };"
        )
}

Rules

  1. The first argument must be a string literal
  2. Each replacement key must be a string literal
  3. Replacement values can be any expression that can be formatted with {}
  4. The order of replacements matters when keys overlap

Dependencies

~215–660KB
~16K SLoC