Crate of the Week

I would like to self-nominate docstr which is a crate that provides the macro docstr! for ergonomically creating multi-line string literals using documentation comments

use docstr::docstr;

let hello_world_in_c: &'static str = docstr!(
    /// #include <stdio.h>
    ///
    /// int main(int argc, char **argv) {
    ///     printf("hello world\n");
    ///     return 0;
    /// }
);

assert_eq!(hello_world_in_c, r#"#include <stdio.h>

int main(int argc, char **argv) {
    printf("hello world\n");
    return 0;
}"#)

My favorite feature about docstr! is that it supports composition. Instead of creating docstr_println!, docstr_format!, docstr_format_args!, etc - docstr! takes another macro as the first argument, and passes the generated string literal into the passed macro.

use docstr::docstr;

let age = 21;
let name = "Bob";
let colors = ["red", "green", "blue"];

let greeting: String = docstr!(format!
                             //^^^^^^^ the generated string is passed to `format!`
                             //        as the 1st argument
    /// Hello, my name is {name}.
    /// I am {age} years old!
    ///
    /// My favorite color is: {}

    // anything after the doc comments is passed directly at the end
    colors[1]
);
//^ above expands to: format!("...", colors[1])

assert_eq!(greeting, "Hello, my name is Bob.\nI am 21 years old!\n\nMy favorite color is: green");

Ever since I made docstr, I ended up incorporating it into virtually every single one of my projects. Especially when writing tests. Here is a use-case for tests in one of my projects cargo-reedme that I just wrote a few minutes ago:

#[test]
fn update() {
    let output = t(
        docstr!(
            /// Header
            ///
            /// <!-- cargo-reedme: start -->
            ///
            /// hello world
            ///
            /// <!-- cargo-reedme: end -->
            ///
            /// Footer
        ),
        "goodbye moon",
    )
    .unwrap();

    assert_str_eq!(
        output,
        docstr!(format!
            /// Header
            ///
            /// <!-- cargo-reedme: start -->
            ///
            /// {}
            ///
            /// goodbye moon
            ///
            /// <!-- cargo-reedme: end -->
            ///
            /// Footer
            alert()
        )
    );
}
5 Likes