#wasmflow #json #codec #messagepack #deserialize-json #serde #serde-json

wasmflow-codec

JSON、Messagepack及原始serde值编解码库

3个版本

0.10.0 2022年7月29日
0.10.0-beta.42022年6月30日

#918 in WebAssembly

Download history 91/week @ 2024-03-31 22/week @ 2024-04-07 25/week @ 2024-04-14 51/week @ 2024-04-21 38/week @ 2024-04-28 22/week @ 2024-05-05 28/week @ 2024-05-12 18/week @ 2024-05-19 32/week @ 2024-05-26 23/week @ 2024-06-02 14/week @ 2024-06-09 17/week @ 2024-06-16 31/week @ 2024-06-23 6/week @ 2024-06-30 8/week @ 2024-07-07 34/week @ 2024-07-14

82 每月下载量
10 个crate中使用 (直接使用6个)

Apache-2.0

13KB
187 代码行

Maintenance

Wasmflow Codec crate 包含用于在 Wasmflow 组件内外通信的序列化和反序列化函数和结构。

JSON

序列化到可以打印为JSON字符串的 serde_json::Value

json::序列化

use wasmflow_codec::{json, Error};
use serde::{Serialize, Deserialize};

pub fn main() -> Result<(), Error> {

  #[derive(Serialize, Deserialize)]
  struct Point {
    x: i32,
    y: i32,
  }

  let point = Point { x: 200, y: 193 };

  let value = json::serialize(&point)?;
  println!("{:?}", value);

  assert_eq!(value, r#"{"x":200,"y":193}"#);
  Ok(())
}

json::反序列化

use wasmflow_codec::{json, Error};
use serde::{Serialize, Deserialize};

pub fn main() -> Result<(), Error> {
  #[derive(Serialize, Deserialize, Debug, PartialEq)]
  struct Point {
    x: i32,
    y: i32,
  }

  let json = r#"{"x":200,"y":193}"#;

  let instance: Point = json::deserialize(&json)?;

  assert_eq!(instance, Point { x: 200, y: 193 });
  Ok(())
}

MessagePack

序列化到MessagePack [Vec]。

messagepack::序列化

use wasmflow_codec::{messagepack, Error};
use serde::{Serialize, Deserialize};

pub fn main() -> Result<(), Error> {
  #[derive(Serialize, Deserialize)]
  struct Point {
    x: i32,
    y: i32,
  }

  let point = Point { x: 200, y: 193 };

  let value = messagepack::serialize(&point)?;
  println!("{:?}", value);

  let expected: Vec<u8> = vec![130, 161, 120, 204, 200, 161, 121, 204, 193];
  assert_eq!(value, expected);
  Ok(())
}

messagepack::反序列化

use wasmflow_codec::{messagepack, Error};
use serde::{Serialize, Deserialize};

pub fn main() -> Result<(), Error> {
  #[derive(Serialize, Deserialize, Debug, PartialEq)]
  struct Point {
    x: i32,
    y: i32,
  }

  let slice = vec![146, 204, 200, 204, 193];

  let instance: Point = messagepack::deserialize(&slice)?;

  assert_eq!(instance, Point { x: 200, y: 193 });
  Ok(())
}

原始

原始 [raw] 模块使用 [serde_value] 作为中间格式来传递。

use wasmflow_codec::{raw, Error};
use serde::{Serialize, Deserialize};

pub fn main() -> Result<(), Error> {
  #[derive(Serialize, Deserialize, Debug, PartialEq)]
  struct Point {
    x: i32,
    y: i32,
  }

  let point = Point { x: 200, y: 193 };

  let value = raw::serialize(&point)?;
  let instance: Point = raw::deserialize(value)?;

  assert_eq!(instance, Point { x: 200, y: 193 });
  Ok(())
}

依赖

~1.2–2MB
~44K SLoC