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.

use format_args_conditional::branch_on_format_capture;

#[derive(Clone, Copy, Debug, PartialEq)]
enum HasCapture {
    Capture,
    NoCapture,
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum HasCaptureArgs {
    Capture(&'static [&'static str]),
    NoCapture(&'static [&'static str]),
}

macro_rules! nocapture {
    ($str:literal $(,)?) => { HasCapture::NoCapture };
    ($str:literal $(, $($args:tt)*)+) => { HasCaptureArgs::NoCapture(
        &[$(
            stringify!($($args)*),
        )*]
    ) };
}

macro_rules! capture {
    ($format_str:literal $(,)?) => { HasCapture::Capture };
    ($str:literal, $($($args:tt)*),+ $(,)?) => { HasCaptureArgs::Capture(
        &[$(
            stringify!($($args)*),
        )*]
    ) };
}

#[test]
fn no_args() {
    use HasCapture::*;

    assert_eq!(branch_on_format_capture!(capture, nocapture, ""), NoCapture);
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "plain string"),
        NoCapture
    );
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "{{x}}"),
        NoCapture
    );
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "{x}"),
        Capture
    );
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "hello {} is {y}"),
        Capture
    );
}

#[test]
fn with_args() {
    use HasCaptureArgs::*;

    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "blah", x = 2),
        NoCapture(&["x = 2"])
    );
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "{x}", x = 5),
        Capture(&["x = 5"])
    );
    assert_eq!(
        branch_on_format_capture!(capture, nocapture, "hello {{}}", "blue"),
        NoCapture(&["\"blue\""])
    );
}