3Hren/msgpack-rust

Providing MessagePack literal macro

temeddix opened this issue · 3 comments

serde_json provides a json! macro for defining the map structure in the place. This is so convenient and intuitive.

https://docs.rs/serde_json/latest/serde_json/macro.json.html

let value = json!({
    "code": 200,
    "success": true,
    "payload": {
        "features": [
            "serde",
            "json"
        ]
    }
});

Could this crate provide this functionality as well? I think the macro code will resemble that of json_serde.

@kornelski can I work on this PR?

I don't understand what you'd use it for. AFAIK msgpack doesn't have a readable text representation like JSON. Would you reuse the JSON syntax?

Serde's json! gives you a Value object. That macro translates to Rust code that allocates Value objects one by one. This makes the binary larger than embedding an equivalent JSON literal string, and working with Value is less efficient than working with structs implementing (de)serialize.

I imagine you could want to have a msgpack binary representation embedded in the executable, since that's smaller than a JSON string. That would be useful to have literal syntax for, since binary format is not an editable source form, but that's different from the json! macro.

@temeddix I played a little bit with original json!() macro and made PoC for rmpv with following syntax:

    fn text_macro() {
        let mp = 
            msgpack!(
                [
                    [1, 2, 3],
                    ["!", "col2", null],
                    {
                        23: "Vasya",
                        "age": 23
                    }, 
                    ""
                ]
            );

        dbg!(mp);

It uses rmpv::Value::from(...) function under the hood.
We use it in unit-tests for preparing test data (not in production code).

Also it works as a shorthand for encoding scalar values msgpack!("123").

This is highly inspired by the original json!() macro: https://gist.github.com/karlovnv/c56481d35e04df11ab8744e9cde35a8a

@kornelski If your don't mind a can make finish this code and make a PR.