1

I have a protobuf file used to generate types in a project. One of the types looks like:

syntax = "proto3";

// ...

message myStruct {
    int32 obj_id = 1;
    string obj_code = 2;
    string obj_name = 3;
    // ... some more fields
}
// ... some more message, enum, etc ....

Then I can launch a tiny script that generates some Go code though protoc-gen-go, that gets later translated into Rust though another script using protoc-gen-rust.

The result is a Rust file that looks like:

// This file is generated by rust-protobuf 2.0.0. Do not edit
// @generated

// ...

pub struct myStruct {
    // message fields
    pub obj_id: i32,
    pub obj_code: ::std::string::String,
    pub obj_name: ::std::string::String,
    // ... some more fields
}
impl myStruct {
    // ... lots of constructors, getters, setters, etc
}

I don't want a better way to do generate the Rust types altogether, the project is massive and in prod, my job is not to rewrite/reorganize it but just to add some functionalities, for which I need some nice little vectors of flags to be added in a couple of structures.

I'd like to add some Vec fields in the myStruct struct, like those:

pub struct myClass {
    // ... some fields like obj_id etc ...

    // the fields I want to add
    bool_vec: Vec<bool>,
    bool_vec_vec: Vec<Vec<bool>>,
    // ...
}

Is it possible to do so using the proto-buf thing, or not? If yes, how can I do it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
m.raynal
  • 2,983
  • 2
  • 21
  • 34

1 Answers1

3

You could use protobuf repeated fields:

repeated: this field can be repeated any number of times (including zero) in a well-formed message. The order of the repeated values will be preserved.

Like:

message bool_vec{
    repeated bool element = 1;
}
message bool_vec_vec{
    repeated bool_vec element = 1;
}
message myStruct {
    ...
    bool_vec v = 100;
    bool_vec_vec vv = 101;
    ...
}

The documentation of RepeatedField from the protobuf C++ library (which represents repeated fields like the repeated bool here) shows that it has what we would expect from vectors: access by index and iterators. Your generated code will also have access by index and add/remove last methods.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
galka
  • 186
  • 7