3Hren / msgpack-rust

MessagePack implementation for Rust / msgpack.org[Rust]
MIT License
1.17k stars 130 forks source link

Providing MessagePack literal macro #330

Closed temeddix closed 1 year ago

temeddix commented 1 year ago

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.

temeddix commented 1 year ago

@kornelski can I work on this PR?

kornelski commented 1 year ago

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.

karlovnv commented 6 months ago

@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.