Basic protobuf example

This commit is contained in:
Oskar Thoren 2019-08-07 15:11:58 +08:00
parent 6955e4c162
commit de733f2ff6
No known key found for this signature in database
GPG Key ID: B2ECCFD3BC2EF77E
1 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,38 @@
import protobuf, streams
# Define protobuf spec and generate Nim code to use it
const protoSpec = """
syntax = "proto3";
message ExampleMessage {
int32 number = 1;
string text = 2;
SubMessage nested = 3;
message SubMessage {
int32 a_field = 1;
}
}
"""
parseProto(protoSpec)
# Example follows:
#--------------------------------------------------------
# Create our message
var msg = new ExampleMessage
msg.number = 10
msg.text = "Hello world"
msg.nested = initExampleMessage_SubMessage(aField = 100)
# Write it to a stream
var stream = newStringStream()
stream.write msg
# Read the message from the stream and output the data, if it's all present
stream.setPosition(0)
var readMsg = stream.readExampleMessage()
if readMsg.has(number, text, nested) and readMsg.nested.has(aField):
echo readMsg.number
echo readMsg.text
echo readMsg.nested.aField