4 /* pb_encode.h: Functions to encode protocol buffers. Depends on pb_encode.c.
5 * The main function is pb_encode. You also need an output stream, structures
6 * and their field descriptions (just like with pb_decode).
12 /* Lightweight output stream.
13 * You can provide callback for writing or use pb_ostream_from_buffer.
15 * Alternatively, callback can be NULL in which case the stream will just
16 * count the number of bytes that would have been written. In this case
17 * max_size is not checked.
20 * 1) Return false on IO errors. This will cause encoding to abort.
22 * 2) You can use state to store your own data (e.g. buffer pointer).
24 * 3) pb_write will update bytes_written after your callback runs.
26 * 4) Substreams will modify max_size and bytes_written. Don't use them to
27 * calculate any pointers.
31 bool (*callback)(pb_ostream_t *stream, const uint8_t *buf, size_t count);
32 void *state; /* Free field for use by callback implementation */
33 size_t max_size; /* Limit number of output bytes written (or use SIZE_MAX). */
37 pb_ostream_t pb_ostream_from_buffer(uint8_t *buf, size_t bufsize);
38 bool pb_write(pb_ostream_t *stream, const uint8_t *buf, size_t count);
40 /* Encode struct to given output stream.
41 * Returns true on success, false on any failure.
42 * The actual struct pointed to by src_struct must match the description in fields.
43 * All required fields in the struct are assumed to have been filled in.
45 bool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);
47 /* --- Helper functions ---
48 * You may want to use these from your caller or callbacks.
51 bool pb_encode_varint(pb_ostream_t *stream, uint64_t value);
52 bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, int field_number);
53 /* Encode tag based on LTYPE and field number defined in the field structure. */
54 bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);
55 /* Write length as varint and then the contents of buffer. */
56 bool pb_encode_string(pb_ostream_t *stream, const uint8_t *buffer, size_t size);
58 /* --- Field encoders ---
59 * Each encoder writes the content for the field.
60 * The tag/wire type has been written already.
63 bool pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
64 bool pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
65 bool pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src);
66 bool pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src);
68 bool pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src);
69 bool pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src);
70 bool pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src);