format_args_conditional 0.1.1

A procedural macro that can expand to one macro or another based on whether `format_args!` input could be optimized as `write_str`
Documentation
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod inner_mod {
    macro_rules! opt_format {
        () => {
            (String::new(), true)
        };
        (@capture $($args:tt)*) => {
            (format!($($args)*), false)
        };
        (@nocapture $str:literal) => {
            (String::from($str), true)
        };
        ($msg:tt $(,)?) => {
            format_args_conditional::branch_on_format_capture!(
                $crate::inner_mod::opt_format {@capture},
                $crate::inner_mod::opt_format {@nocapture},
                $msg
            )
        };
        ($($args:tt)*) => {
            $crate::inner_mod::opt_format!(@capture $($args)*)
        };
    }

    pub(crate) use opt_format;
}

#[test]
fn optimizing_format() {
    let x = 1;
    macro_rules! test_opt_format {
        ($expect_opt:ident, $($tokens:tt)*) => {
            assert_eq!(inner_mod::opt_format!($($tokens)*), (format!($($tokens)*), $expect_opt));
        };
    }
    test_opt_format!(true, "hello");
    test_opt_format!(false, "hello {x}");
    test_opt_format!(false, "hello {}", 2);
    test_opt_format!(false, "hello {x}", x = 3);
    test_opt_format!(true, "hello {{x}}");
}