Files
nanopb/tests/test_encode_callbacks.c
Michael Poole 43b8e20744 Create a message descriptor type.
This replaces the sentinel at the end of the pb_field_t
array for each message type.

git-svn-id: https://svn.kapsi.fi/jpa/nanopb-dev@1007 e3a754e5-d11d-0410-8d38-ebb782a927b9
2012-01-05 22:01:17 +02:00

69 lines
1.9 KiB
C

/* Encoding testcase for callback fields */
#include <stdio.h>
#include <string.h>
#include <pb_encode.h>
#include "callbacks.pb.h"
bool encode_string(pb_ostream_t *stream, const pb_field_t *field, const void *arg)
{
char *str = "Hello world!";
if (!pb_encode_tag_for_field(stream, field))
return false;
return pb_encode_string(stream, (uint8_t*)str, strlen(str));
}
bool encode_int32(pb_ostream_t *stream, const pb_field_t *field, const void *arg)
{
if (!pb_encode_tag_for_field(stream, field))
return false;
return pb_encode_varint(stream, 42);
}
bool encode_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *arg)
{
if (!pb_encode_tag_for_field(stream, field))
return false;
uint32_t value = 42;
return pb_enc_fixed32(stream, field, &value);
}
bool encode_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *arg)
{
if (!pb_encode_tag_for_field(stream, field))
return false;
uint64_t value = 42;
return pb_enc_fixed64(stream, field, &value);
}
int main()
{
uint8_t buffer[1024];
pb_ostream_t stream = pb_ostream_from_buffer(buffer, 1024);
TestMessage testmessage = {};
testmessage.stringvalue.funcs.encode = &encode_string;
testmessage.int32value.funcs.encode = &encode_int32;
testmessage.fixed32value.funcs.encode = &encode_fixed32;
testmessage.fixed64value.funcs.encode = &encode_fixed64;
testmessage.has_submsg = true;
testmessage.submsg.stringvalue.funcs.encode = &encode_string;
testmessage.submsg.int32value.funcs.encode = &encode_int32;
testmessage.submsg.fixed32value.funcs.encode = &encode_fixed32;
testmessage.submsg.fixed64value.funcs.encode = &encode_fixed64;
if (!pb_encode(&stream, TestMessage_msg, &testmessage))
return 1;
if (fwrite(buffer, stream.bytes_written, 1, stdout) != 1)
return 2;
return 0;
}