#protobuf #json #serde #serde-json

pbjson-build-any

为prost消息类型生成Serialize和Deserialize实现

1个不稳定版本

0.2.3 2022年2月1日

#222 in #serde-json

每月下载量40次
2 crates 中使用

MIT 许可证

70KB
2K SLoC

pbjson-build 消耗 prost-build 的描述符输出,并生成符合 protobuf JSON映射serde::Serializeserde::Deserialize 实现

用法

建议您首先按照 prost-build 中的示例操作,以熟悉 prost

prost-buildprostpbjsonpbjson-buildpbjson-types 添加到您的 Cargo.toml

[dependencies]
prost = <prost-version>
pbjson = <pbjson-version>
pbjson-types = <pbjson-version>

[build-dependencies]
prost-build = <prost-version>
pbjson-build = <pbjson-version>

接下来创建一个包含以下内容的 build.rs

// This assumes protobuf files are under a directory called `protos`
// and in a protobuf package `mypackage`

let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("protos");
let proto_files = vec![root.join("myproto.proto")];

// Tell cargo to recompile if any of these proto files are changed
for proto_file in &proto_files {
    println!("cargo:rerun-if-changed={}", proto_file.display());
}

let descriptor_path = PathBuf::from(env::var("OUT_DIR").unwrap())
    .join("proto_descriptor.bin");

prost_build::Config::new()
    // Save descriptors to file
    .file_descriptor_set_path(&descriptor_path)
    // Override prost-types with pbjson-types
    .compile_well_known_types()
    .extern_path(".google.protobuf", "::pbjson_types_any")
    // Generate prost structs
    .compile_protos(&proto_files, &[root])?;

let descriptor_set = std::fs::read(descriptor_path)?;
pbjson_build::Builder::new()
    .register_descriptors(&descriptor_set)?
    .build(&[".mypackage"])?;

最后,在 lib.rs

/// Generated by [`prost-build`]
include!(concat!(env!("OUT_DIR"), "/mypackage.rs"));
/// Generated by [`pbjson-build`]
include!(concat!(env!("OUT_DIR"), "/mypackage.serde.rs"));

模块现在将包含您protobuf定义生成的prost结构以及符合 serde::Serializeserde::Deserialize 的实现

依赖项

~3MB
~60K SLoC