Skip to content

Instantly share code, notes, and snippets.

@muhamadazmy
Created August 7, 2019 13:04
Show Gist options
  • Save muhamadazmy/3cba610047f8f24acff2874c3af13db3 to your computer and use it in GitHub Desktop.
Save muhamadazmy/3cba610047f8f24acff2874c3af13db3 to your computer and use it in GitHub Desktop.
Test msgpack compatibility accross go and rust.

Quick test for msgpack compatibility

The code below (data encoded in Go) and then decoded in Rust. works fine.

Rust decoder

extern crate rmp_serde as rmps;
extern crate serde;

#[macro_use]
extern crate serde_derive;

use rmps::{Deserializer, Serializer};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct Child {
    name: String,
    age: f64,
}

#[derive(Debug, PartialEq, Deserialize, Serialize)]
struct Person {
    name: String,
    age: f64,
    children: Vec<Child>,
}

fn main() {
    let data = std::fs::read("/tmp/msg.pack").unwrap();

    let person: Person = rmps::from_slice(&data).unwrap();

    println!("{:?}", person);
}

Go Encoder

package main

import (
	"os"

	"github.com/vmihailenco/msgpack"
)

type Child struct {
	Name string  `msgpack:"name"`
	Age  float64 `msgpack:"age"`
}
type Person struct {
	Name     string  `msgpack:"name"`
	Age      float64 `msgpack:"age"`
	Children []Child `msgpack:"children"`
}

func main() {
	f, err := os.Create("/tmp/msg.pack")
	if err != nil {
		panic(err)
	}
	enc := msgpack.NewEncoder(f)
	p := Person{
		Name: "azmy",
		Age:  37,
		Children: []Child{
			{Name: "yahia", Age: 6},
			{Name: "yassine", Age: 5},
		},
	}

	if err := enc.Encode(p); err != nil {
		panic(err)
	}
}
@muhamadazmy
Copy link
Author

We just need to make sure that the encoder/decoder uses the same field names (lower case in this test).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment