aboutsummaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/Makefile21
-rw-r--r--tests/SConstruct146
-rw-r--r--tests/alltypes/SConscript35
-rw-r--r--tests/alltypes/alltypes.options3
-rw-r--r--tests/alltypes/alltypes.proto114
-rw-r--r--tests/alltypes/decode_alltypes.c213
-rw-r--r--tests/alltypes/encode_alltypes.c145
-rw-r--r--tests/alltypes_callback/SConscript23
-rw-r--r--tests/alltypes_callback/alltypes.options3
-rw-r--r--tests/alltypes_callback/decode_alltypes_callback.c423
-rw-r--r--tests/alltypes_callback/encode_alltypes_callback.c397
-rw-r--r--tests/alltypes_pointer/SConscript48
-rw-r--r--tests/alltypes_pointer/alltypes.options3
-rw-r--r--tests/alltypes_pointer/decode_alltypes_pointer.c173
-rw-r--r--tests/alltypes_pointer/encode_alltypes_pointer.c188
-rw-r--r--tests/backwards_compatibility/SConscript11
-rw-r--r--tests/backwards_compatibility/alltypes_legacy.c93
-rw-r--r--tests/backwards_compatibility/alltypes_legacy.h178
-rw-r--r--tests/backwards_compatibility/decode_legacy.c202
-rw-r--r--tests/backwards_compatibility/encode_legacy.c135
-rw-r--r--tests/basic_buffer/SConscript12
-rw-r--r--tests/basic_buffer/decode_buffer.c88
-rw-r--r--tests/basic_buffer/encode_buffer.c38
-rw-r--r--tests/basic_stream/SConscript12
-rw-r--r--tests/basic_stream/decode_stream.c84
-rw-r--r--tests/basic_stream/encode_stream.c40
-rw-r--r--tests/buffer_only/SConscript27
-rw-r--r--tests/callbacks/SConscript14
-rw-r--r--tests/callbacks/callbacks.proto16
-rw-r--r--tests/callbacks/decode_callbacks.c97
-rw-r--r--tests/callbacks/encode_callbacks.c92
-rw-r--r--tests/common/SConscript17
-rw-r--r--tests/common/person.proto20
-rw-r--r--tests/common/test_helpers.h17
-rw-r--r--tests/common/unittestproto.proto36
-rw-r--r--tests/common/unittests.h14
-rw-r--r--tests/cxx_main_program/SConscript24
-rw-r--r--tests/decode_unittests/SConscript4
-rw-r--r--tests/decode_unittests/decode_unittests.c306
-rw-r--r--tests/encode_unittests/SConscript5
-rw-r--r--tests/encode_unittests/encode_unittests.c337
-rw-r--r--tests/extensions/SConscript16
-rw-r--r--tests/extensions/decode_extensions.c60
-rw-r--r--tests/extensions/encode_extensions.c54
-rw-r--r--tests/extensions/extensions.options1
-rw-r--r--tests/extensions/extensions.proto17
-rw-r--r--tests/extra_fields/SConscript16
-rw-r--r--tests/extra_fields/alltypes_with_extra_fields.pbbin0 -> 523 bytes
-rw-r--r--tests/extra_fields/person_with_extra_field.expected14
-rw-r--r--tests/extra_fields/person_with_extra_field.pbbin0 -> 124 bytes
-rw-r--r--tests/field_size_16/SConscript28
-rw-r--r--tests/field_size_16/alltypes.options3
-rw-r--r--tests/field_size_16/alltypes.proto111
-rw-r--r--tests/field_size_32/SConscript28
-rw-r--r--tests/field_size_32/alltypes.options3
-rw-r--r--tests/field_size_32/alltypes.proto111
-rw-r--r--tests/message_sizes/SConscript11
-rw-r--r--tests/message_sizes/dummy.c9
-rw-r--r--tests/message_sizes/messages1.proto27
-rw-r--r--tests/message_sizes/messages2.proto8
-rw-r--r--tests/missing_fields/SConscript8
-rw-r--r--tests/missing_fields/missing_fields.c53
-rw-r--r--tests/missing_fields/missing_fields.proto138
-rw-r--r--tests/multiple_files/SConscript13
-rw-r--r--tests/multiple_files/callbacks.proto16
-rw-r--r--tests/multiple_files/callbacks2.proto9
-rw-r--r--tests/multiple_files/test_multiple_files.c12
-rw-r--r--tests/no_errmsg/SConscript27
-rw-r--r--tests/no_messages/SConscript7
-rw-r--r--tests/no_messages/no_messages.proto7
-rw-r--r--tests/options/SConscript9
-rw-r--r--tests/options/options.expected7
-rw-r--r--tests/options/options.proto73
-rw-r--r--tests/package_name/SConscript36
-rw-r--r--tests/site_scons/site_init.py98
-rw-r--r--tests/site_scons/site_tools/nanopb.py126
-rw-r--r--tests/special_characters/SConscript6
-rw-r--r--tests/special_characters/funny-proto+name has.characters.proto0
-rw-r--r--tests/splint/SConscript13
-rw-r--r--tests/splint/splint.rc37
80 files changed, 5066 insertions, 0 deletions
diff --git a/tests/Makefile b/tests/Makefile
new file mode 100644
index 0000000..3c4e0b0
--- /dev/null
+++ b/tests/Makefile
@@ -0,0 +1,21 @@
+all:
+ scons
+
+clean:
+ scons -c
+
+coverage:
+ rm -rf build coverage
+
+ # LCOV does not like the newer gcov format
+ scons CC=gcc-4.6 CXX=gcc-4.6
+
+ # We are only interested in pb_encode.o and pb_decode.o
+ find build -name '*.gcda' -and \! \( -name '*pb_encode*' -or -name '*pb_decode*' \) -exec rm '{}' \;
+
+ # Collect the data
+ mkdir build/coverage
+ lcov --base-directory . --directory build/ --gcov-tool gcov-4.6 -c -o build/coverage/nanopb.info
+
+ # Generate HTML
+ genhtml -o build/coverage build/coverage/nanopb.info
diff --git a/tests/SConstruct b/tests/SConstruct
new file mode 100644
index 0000000..7a27844
--- /dev/null
+++ b/tests/SConstruct
@@ -0,0 +1,146 @@
+Help('''
+Type 'scons' to build and run all the available test cases.
+It will automatically detect your platform and C compiler and
+build appropriately.
+
+You can modify the behavious using following options:
+CC Name of C compiler
+CXX Name of C++ compiler
+CCFLAGS Flags to pass to the C compiler
+CXXFLAGS Flags to pass to the C++ compiler
+
+For example, for a clang build, use:
+scons CC=clang CXX=clang++
+''')
+
+import os
+env = Environment(ENV = os.environ, tools = ['default', 'nanopb'])
+
+# Allow overriding the compiler with scons CC=???
+if 'CC' in ARGUMENTS: env.Replace(CC = ARGUMENTS['CC'])
+if 'CXX' in ARGUMENTS: env.Replace(CXX = ARGUMENTS['CXX'])
+if 'CCFLAGS' in ARGUMENTS: env.Append(CCFLAGS = ARGUMENTS['CCFLAGS'])
+if 'CXXFLAGS' in ARGUMENTS: env.Append(CXXFLAGS = ARGUMENTS['CXXFLAGS'])
+
+# Add the builders defined in site_init.py
+add_nanopb_builders(env)
+
+# Path to the files shared by tests, and to the nanopb core.
+env.Append(CPPPATH = ["#../", "$COMMON"])
+
+# Path for finding nanopb.proto
+env.Append(PROTOCPATH = '#../generator')
+
+# Check the compilation environment, unless we are just cleaning up.
+if not env.GetOption('clean'):
+ def check_ccflags(context, flags, linkflags = ''):
+ '''Check if given CCFLAGS are supported'''
+ context.Message('Checking support for CCFLAGS="%s"... ' % flags)
+ oldflags = context.env['CCFLAGS']
+ oldlinkflags = context.env['CCFLAGS']
+ context.env.Append(CCFLAGS = flags)
+ context.env.Append(LINKFLAGS = linkflags)
+ result = context.TryCompile("int main() {return 0;}", '.c')
+ context.env.Replace(CCFLAGS = oldflags)
+ context.env.Replace(LINKFLAGS = oldlinkflags)
+ context.Result(result)
+ return result
+
+ conf = Configure(env, custom_tests = {'CheckCCFLAGS': check_ccflags})
+
+ # If the platform doesn't support C99, use our own header file instead.
+ stdbool = conf.CheckCHeader('stdbool.h')
+ stdint = conf.CheckCHeader('stdint.h')
+ stddef = conf.CheckCHeader('stddef.h')
+ string = conf.CheckCHeader('string.h')
+ stdlib = conf.CheckCHeader('stdlib.h')
+ if not stdbool or not stdint or not stddef or not string:
+ conf.env.Append(CPPDEFINES = {'PB_SYSTEM_HEADER': '\\"pb_syshdr.h\\"'})
+ conf.env.Append(CPPPATH = "#../extra")
+
+ if stdbool: conf.env.Append(CPPDEFINES = {'HAVE_STDBOOL_H': 1})
+ if stdint: conf.env.Append(CPPDEFINES = {'HAVE_STDINT_H': 1})
+ if stddef: conf.env.Append(CPPDEFINES = {'HAVE_STDDEF_H': 1})
+ if string: conf.env.Append(CPPDEFINES = {'HAVE_STRING_H': 1})
+ if stdlib: conf.env.Append(CPPDEFINES = {'HAVE_STDLIB_H': 1})
+
+ # Check if we can use pkg-config to find protobuf include path
+ status, output = conf.TryAction('pkg-config protobuf --variable=includedir > $TARGET')
+ if status:
+ conf.env.Append(PROTOCPATH = output.strip())
+ else:
+ conf.env.Append(PROTOCPATH = '/usr/include')
+
+ # Check if libmudflap is available (only with GCC)
+ if 'gcc' in env['CC']:
+ if conf.CheckLib('mudflap'):
+ conf.env.Append(CCFLAGS = '-fmudflap')
+ conf.env.Append(LINKFLAGS = '-fmudflap')
+
+ # Check if we can use extra strict warning flags (only with GCC)
+ extra = '-Wcast-qual -Wlogical-op -Wconversion'
+ extra += ' -fstrict-aliasing -Wstrict-aliasing=1'
+ extra += ' -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls'
+ extra += ' -Wstack-protector '
+ if 'gcc' in env['CC']:
+ if conf.CheckCCFLAGS(extra):
+ conf.env.Append(CORECFLAGS = extra)
+
+ # Check if we can use undefined behaviour sanitizer (only with clang)
+ extra = '-fsanitize=undefined '
+ if 'clang' in env['CC']:
+ if conf.CheckCCFLAGS(extra, linkflags = extra):
+ conf.env.Append(CORECFLAGS = extra)
+ conf.env.Append(LINKFLAGS = extra)
+
+ # End the config stuff
+ env = conf.Finish()
+
+# Initialize the CCFLAGS according to the compiler
+if 'gcc' in env['CC']:
+ # GNU Compiler Collection
+
+ # Debug info, warnings as errors
+ env.Append(CFLAGS = '-ansi -pedantic -g -Wall -Werror -fprofile-arcs -ftest-coverage -fstack-protector-all')
+ env.Append(CORECFLAGS = '-Wextra')
+ env.Append(LINKFLAGS = '-g --coverage')
+
+ # We currently need uint64_t anyway, even though ANSI C90 otherwise..
+ env.Append(CFLAGS = '-Wno-long-long')
+elif 'clang' in env['CC']:
+ # CLang
+ env.Append(CFLAGS = '-ansi -g -Wall -Werror')
+ env.Append(CORECFLAGS = ' -Wextra -Wcast-qual -Wconversion')
+elif 'cl' in env['CC']:
+ # Microsoft Visual C++
+
+ # Debug info on, warning level 2 for tests, warnings as errors
+ env.Append(CFLAGS = '/Zi /W2 /WX')
+ env.Append(LINKFLAGS = '/DEBUG')
+
+ # More strict checks on the nanopb core
+ env.Append(CORECFLAGS = '/W4')
+
+ # PB_RETURN_ERROR triggers C4127 because of while(0)
+ env.Append(CFLAGS = '/wd4127')
+elif 'tcc' in env['CC']:
+ # Tiny C Compiler
+ env.Append(CFLAGS = '-Wall -Werror -g')
+
+env.SetDefault(CORECFLAGS = '')
+
+if 'clang' in env['CXX']:
+ env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers')
+elif 'g++' in env['CXX'] or 'gcc' in env['CXX']:
+ env.Append(CXXFLAGS = '-g -Wall -Werror -Wextra -Wno-missing-field-initializers')
+elif 'cl' in env['CXX']:
+ env.Append(CXXFLAGS = '/Zi /W2 /WX')
+
+# Now include the SConscript files from all subdirectories
+import os.path
+env['VARIANT_DIR'] = 'build'
+env['BUILD'] = '#' + env['VARIANT_DIR']
+env['COMMON'] = '#' + env['VARIANT_DIR'] + '/common'
+for subdir in Glob('*/SConscript'):
+ SConscript(subdir, exports = 'env', variant_dir = env['VARIANT_DIR'] + '/' + os.path.dirname(str(subdir)))
+
diff --git a/tests/alltypes/SConscript b/tests/alltypes/SConscript
new file mode 100644
index 0000000..9c9072b
--- /dev/null
+++ b/tests/alltypes/SConscript
@@ -0,0 +1,35 @@
+# Build and run a test that encodes and decodes a message that contains
+# all of the Protocol Buffers data types.
+
+Import("env")
+
+env.NanopbProto(["alltypes", "alltypes.options"])
+enc = env.Program(["encode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_decode.o"])
+
+# Test the round-trip from nanopb encoder to nanopb decoder
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
+
+# Re-encode the data using protoc, and check that the results from nanopb
+# match byte-per-byte to the protoc output.
+env.Decode("encode_alltypes.output.decoded",
+ ["encode_alltypes.output", "alltypes.proto"],
+ MESSAGE='AllTypes')
+env.Encode("encode_alltypes.output.recoded",
+ ["encode_alltypes.output.decoded", "alltypes.proto"],
+ MESSAGE='AllTypes')
+env.Compare(["encode_alltypes.output", "encode_alltypes.output.recoded"])
+
+# Do the same checks with the optional fields present.
+env.RunTest("optionals.output", enc, ARGS = ['1'])
+env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1'])
+env.Decode("optionals.output.decoded",
+ ["optionals.output", "alltypes.proto"],
+ MESSAGE='AllTypes')
+env.Encode("optionals.output.recoded",
+ ["optionals.output.decoded", "alltypes.proto"],
+ MESSAGE='AllTypes')
+env.Compare(["optionals.output", "optionals.output.recoded"])
+
+
diff --git a/tests/alltypes/alltypes.options b/tests/alltypes/alltypes.options
new file mode 100644
index 0000000..b31e3cf
--- /dev/null
+++ b/tests/alltypes/alltypes.options
@@ -0,0 +1,3 @@
+* max_size:16
+* max_count:5
+
diff --git a/tests/alltypes/alltypes.proto b/tests/alltypes/alltypes.proto
new file mode 100644
index 0000000..db83c9a
--- /dev/null
+++ b/tests/alltypes/alltypes.proto
@@ -0,0 +1,114 @@
+message SubMessage {
+ required string substuff1 = 1 [default = "1"];
+ required int32 substuff2 = 2 [default = 2];
+ optional fixed32 substuff3 = 3 [default = 3];
+}
+
+message EmptyMessage {
+
+}
+
+enum HugeEnum {
+ Negative = -2147483647; /* protoc doesn't accept -2147483648 here */
+ Positive = 2147483647;
+}
+
+message Limits {
+ required int32 int32_min = 1 [default = 2147483647];
+ required int32 int32_max = 2 [default = -2147483647];
+ required uint32 uint32_min = 3 [default = 4294967295];
+ required uint32 uint32_max = 4 [default = 0];
+ required int64 int64_min = 5 [default = 9223372036854775807];
+ required int64 int64_max = 6 [default = -9223372036854775807];
+ required uint64 uint64_min = 7 [default = 18446744073709551615];
+ required uint64 uint64_max = 8 [default = 0];
+ required HugeEnum enum_min = 9 [default = Positive];
+ required HugeEnum enum_max = 10 [default = Negative];
+}
+
+enum MyEnum {
+ Zero = 0;
+ First = 1;
+ Second = 2;
+ Truth = 42;
+}
+
+message AllTypes {
+ required int32 req_int32 = 1;
+ required int64 req_int64 = 2;
+ required uint32 req_uint32 = 3;
+ required uint64 req_uint64 = 4;
+ required sint32 req_sint32 = 5;
+ required sint64 req_sint64 = 6;
+ required bool req_bool = 7;
+
+ required fixed32 req_fixed32 = 8;
+ required sfixed32 req_sfixed32= 9;
+ required float req_float = 10;
+
+ required fixed64 req_fixed64 = 11;
+ required sfixed64 req_sfixed64= 12;
+ required double req_double = 13;
+
+ required string req_string = 14;
+ required bytes req_bytes = 15;
+ required SubMessage req_submsg = 16;
+ required MyEnum req_enum = 17;
+ required EmptyMessage req_emptymsg = 18;
+
+
+ repeated int32 rep_int32 = 21 [packed = true];
+ repeated int64 rep_int64 = 22 [packed = true];
+ repeated uint32 rep_uint32 = 23 [packed = true];
+ repeated uint64 rep_uint64 = 24 [packed = true];
+ repeated sint32 rep_sint32 = 25 [packed = true];
+ repeated sint64 rep_sint64 = 26 [packed = true];
+ repeated bool rep_bool = 27 [packed = true];
+
+ repeated fixed32 rep_fixed32 = 28 [packed = true];
+ repeated sfixed32 rep_sfixed32= 29 [packed = true];
+ repeated float rep_float = 30 [packed = true];
+
+ repeated fixed64 rep_fixed64 = 31 [packed = true];
+ repeated sfixed64 rep_sfixed64= 32 [packed = true];
+ repeated double rep_double = 33 [packed = true];
+
+ repeated string rep_string = 34;
+ repeated bytes rep_bytes = 35;
+ repeated SubMessage rep_submsg = 36;
+ repeated MyEnum rep_enum = 37 [packed = true];
+ repeated EmptyMessage rep_emptymsg = 38;
+
+ optional int32 opt_int32 = 41 [default = 4041];
+ optional int64 opt_int64 = 42 [default = 4042];
+ optional uint32 opt_uint32 = 43 [default = 4043];
+ optional uint64 opt_uint64 = 44 [default = 4044];
+ optional sint32 opt_sint32 = 45 [default = 4045];
+ optional sint64 opt_sint64 = 46 [default = 4046];
+ optional bool opt_bool = 47 [default = false];
+
+ optional fixed32 opt_fixed32 = 48 [default = 4048];
+ optional sfixed32 opt_sfixed32= 49 [default = 4049];
+ optional float opt_float = 50 [default = 4050];
+
+ optional fixed64 opt_fixed64 = 51 [default = 4051];
+ optional sfixed64 opt_sfixed64= 52 [default = 4052];
+ optional double opt_double = 53 [default = 4053];
+
+ optional string opt_string = 54 [default = "4054"];
+ optional bytes opt_bytes = 55 [default = "4055"];
+ optional SubMessage opt_submsg = 56;
+ optional MyEnum opt_enum = 57 [default = Second];
+ optional EmptyMessage opt_emptymsg = 58;
+
+ // Check that extreme integer values are handled correctly
+ required Limits req_limits = 98;
+
+ // Just to make sure that the size of the fields has been calculated
+ // properly, i.e. otherwise a bug in last field might not be detected.
+ required int32 end = 99;
+
+
+ extensions 200 to 255;
+}
+
diff --git a/tests/alltypes/decode_alltypes.c b/tests/alltypes/decode_alltypes.c
new file mode 100644
index 0000000..db72bb9
--- /dev/null
+++ b/tests/alltypes/decode_alltypes.c
@@ -0,0 +1,213 @@
+/* Tests the decoding of all types.
+ * This is the counterpart of test_encode3.
+ * Run e.g. ./test_encode3 | ./test_decode3
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <pb_decode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+#define TEST(x) if (!(x)) { \
+ printf("Test " #x " failed.\n"); \
+ return false; \
+ }
+
+/* This function is called once from main(), it handles
+ the decoding and checks the fields. */
+bool check_alltypes(pb_istream_t *stream, int mode)
+{
+ AllTypes alltypes;
+
+ /* Fill with garbage to better detect initialization errors */
+ memset(&alltypes, 0xAA, sizeof(alltypes));
+
+ if (!pb_decode(stream, AllTypes_fields, &alltypes))
+ return false;
+
+ TEST(alltypes.req_int32 == -1001);
+ TEST(alltypes.req_int64 == -1002);
+ TEST(alltypes.req_uint32 == 1003);
+ TEST(alltypes.req_uint64 == 1004);
+ TEST(alltypes.req_sint32 == -1005);
+ TEST(alltypes.req_sint64 == -1006);
+ TEST(alltypes.req_bool == true);
+
+ TEST(alltypes.req_fixed32 == 1008);
+ TEST(alltypes.req_sfixed32 == -1009);
+ TEST(alltypes.req_float == 1010.0f);
+
+ TEST(alltypes.req_fixed64 == 1011);
+ TEST(alltypes.req_sfixed64 == -1012);
+ TEST(alltypes.req_double == 1013.0f);
+
+ TEST(strcmp(alltypes.req_string, "1014") == 0);
+ TEST(alltypes.req_bytes.size == 4);
+ TEST(memcmp(alltypes.req_bytes.bytes, "1015", 4) == 0);
+ TEST(strcmp(alltypes.req_submsg.substuff1, "1016") == 0);
+ TEST(alltypes.req_submsg.substuff2 == 1016);
+ TEST(alltypes.req_submsg.substuff3 == 3);
+ TEST(alltypes.req_enum == MyEnum_Truth);
+
+ TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0);
+ TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0);
+ TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0);
+ TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0);
+ TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0);
+ TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0);
+ TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false);
+
+ TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0);
+ TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0);
+ TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f);
+
+ TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0);
+ TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0);
+ TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0);
+
+ TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0');
+ TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0);
+ TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0);
+
+ TEST(alltypes.rep_submsg_count == 5);
+ TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0');
+ TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0);
+ TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 3);
+
+ TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero);
+ TEST(alltypes.rep_emptymsg_count == 5);
+
+ if (mode == 0)
+ {
+ /* Expect default values */
+ TEST(alltypes.has_opt_int32 == false);
+ TEST(alltypes.opt_int32 == 4041);
+ TEST(alltypes.has_opt_int64 == false);
+ TEST(alltypes.opt_int64 == 4042);
+ TEST(alltypes.has_opt_uint32 == false);
+ TEST(alltypes.opt_uint32 == 4043);
+ TEST(alltypes.has_opt_uint64 == false);
+ TEST(alltypes.opt_uint64 == 4044);
+ TEST(alltypes.has_opt_sint32 == false);
+ TEST(alltypes.opt_sint32 == 4045);
+ TEST(alltypes.has_opt_sint64 == false);
+ TEST(alltypes.opt_sint64 == 4046);
+ TEST(alltypes.has_opt_bool == false);
+ TEST(alltypes.opt_bool == false);
+
+ TEST(alltypes.has_opt_fixed32 == false);
+ TEST(alltypes.opt_fixed32 == 4048);
+ TEST(alltypes.has_opt_sfixed32 == false);
+ TEST(alltypes.opt_sfixed32 == 4049);
+ TEST(alltypes.has_opt_float == false);
+ TEST(alltypes.opt_float == 4050.0f);
+
+ TEST(alltypes.has_opt_fixed64 == false);
+ TEST(alltypes.opt_fixed64 == 4051);
+ TEST(alltypes.has_opt_sfixed64 == false);
+ TEST(alltypes.opt_sfixed64 == 4052);
+ TEST(alltypes.has_opt_double == false);
+ TEST(alltypes.opt_double == 4053.0);
+
+ TEST(alltypes.has_opt_string == false);
+ TEST(strcmp(alltypes.opt_string, "4054") == 0);
+ TEST(alltypes.has_opt_bytes == false);
+ TEST(alltypes.opt_bytes.size == 4);
+ TEST(memcmp(alltypes.opt_bytes.bytes, "4055", 4) == 0);
+ TEST(alltypes.has_opt_submsg == false);
+ TEST(strcmp(alltypes.opt_submsg.substuff1, "1") == 0);
+ TEST(alltypes.opt_submsg.substuff2 == 2);
+ TEST(alltypes.opt_submsg.substuff3 == 3);
+ TEST(alltypes.has_opt_enum == false);
+ TEST(alltypes.opt_enum == MyEnum_Second);
+ TEST(alltypes.has_opt_emptymsg == false);
+ }
+ else
+ {
+ /* Expect filled-in values */
+ TEST(alltypes.has_opt_int32 == true);
+ TEST(alltypes.opt_int32 == 3041);
+ TEST(alltypes.has_opt_int64 == true);
+ TEST(alltypes.opt_int64 == 3042);
+ TEST(alltypes.has_opt_uint32 == true);
+ TEST(alltypes.opt_uint32 == 3043);
+ TEST(alltypes.has_opt_uint64 == true);
+ TEST(alltypes.opt_uint64 == 3044);
+ TEST(alltypes.has_opt_sint32 == true);
+ TEST(alltypes.opt_sint32 == 3045);
+ TEST(alltypes.has_opt_sint64 == true);
+ TEST(alltypes.opt_sint64 == 3046);
+ TEST(alltypes.has_opt_bool == true);
+ TEST(alltypes.opt_bool == true);
+
+ TEST(alltypes.has_opt_fixed32 == true);
+ TEST(alltypes.opt_fixed32 == 3048);
+ TEST(alltypes.has_opt_sfixed32 == true);
+ TEST(alltypes.opt_sfixed32 == 3049);
+ TEST(alltypes.has_opt_float == true);
+ TEST(alltypes.opt_float == 3050.0f);
+
+ TEST(alltypes.has_opt_fixed64 == true);
+ TEST(alltypes.opt_fixed64 == 3051);
+ TEST(alltypes.has_opt_sfixed64 == true);
+ TEST(alltypes.opt_sfixed64 == 3052);
+ TEST(alltypes.has_opt_double == true);
+ TEST(alltypes.opt_double == 3053.0);
+
+ TEST(alltypes.has_opt_string == true);
+ TEST(strcmp(alltypes.opt_string, "3054") == 0);
+ TEST(alltypes.has_opt_bytes == true);
+ TEST(alltypes.opt_bytes.size == 4);
+ TEST(memcmp(alltypes.opt_bytes.bytes, "3055", 4) == 0);
+ TEST(alltypes.has_opt_submsg == true);
+ TEST(strcmp(alltypes.opt_submsg.substuff1, "3056") == 0);
+ TEST(alltypes.opt_submsg.substuff2 == 3056);
+ TEST(alltypes.opt_submsg.substuff3 == 3);
+ TEST(alltypes.has_opt_enum == true);
+ TEST(alltypes.opt_enum == MyEnum_Truth);
+ TEST(alltypes.has_opt_emptymsg == true);
+ }
+
+ TEST(alltypes.req_limits.int32_min == INT32_MIN);
+ TEST(alltypes.req_limits.int32_max == INT32_MAX);
+ TEST(alltypes.req_limits.uint32_min == 0);
+ TEST(alltypes.req_limits.uint32_max == UINT32_MAX);
+ TEST(alltypes.req_limits.int64_min == INT64_MIN);
+ TEST(alltypes.req_limits.int64_max == INT64_MAX);
+ TEST(alltypes.req_limits.uint64_min == 0);
+ TEST(alltypes.req_limits.uint64_max == UINT64_MAX);
+ TEST(alltypes.req_limits.enum_min == HugeEnum_Negative);
+ TEST(alltypes.req_limits.enum_max == HugeEnum_Positive);
+
+ TEST(alltypes.end == 1099);
+
+ return true;
+}
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ size_t count;
+ pb_istream_t stream;
+
+ /* Whether to expect the optional values or the default values. */
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Read the data into buffer */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+
+ /* Construct a pb_istream_t for reading from the buffer */
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Decode and print out the stuff */
+ if (!check_alltypes(&stream, mode))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ } else {
+ return 0;
+ }
+}
diff --git a/tests/alltypes/encode_alltypes.c b/tests/alltypes/encode_alltypes.c
new file mode 100644
index 0000000..fa8eec9
--- /dev/null
+++ b/tests/alltypes/encode_alltypes.c
@@ -0,0 +1,145 @@
+/* Attempts to test all the datatypes supported by ProtoBuf.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+int main(int argc, char **argv)
+{
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Initialize the structure with constants */
+ AllTypes alltypes = {0};
+
+ alltypes.req_int32 = -1001;
+ alltypes.req_int64 = -1002;
+ alltypes.req_uint32 = 1003;
+ alltypes.req_uint64 = 1004;
+ alltypes.req_sint32 = -1005;
+ alltypes.req_sint64 = -1006;
+ alltypes.req_bool = true;
+
+ alltypes.req_fixed32 = 1008;
+ alltypes.req_sfixed32 = -1009;
+ alltypes.req_float = 1010.0f;
+
+ alltypes.req_fixed64 = 1011;
+ alltypes.req_sfixed64 = -1012;
+ alltypes.req_double = 1013.0;
+
+ strcpy(alltypes.req_string, "1014");
+ alltypes.req_bytes.size = 4;
+ memcpy(alltypes.req_bytes.bytes, "1015", 4);
+ strcpy(alltypes.req_submsg.substuff1, "1016");
+ alltypes.req_submsg.substuff2 = 1016;
+ alltypes.req_enum = MyEnum_Truth;
+
+ alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001;
+ alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002;
+ alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003;
+ alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004;
+ alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005;
+ alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006;
+ alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true;
+
+ alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008;
+ alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009;
+ alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f;
+
+ alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011;
+ alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012;
+ alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0;
+
+ alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014");
+ alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4;
+ memcpy(alltypes.rep_bytes[4].bytes, "2015", 4);
+
+ alltypes.rep_submsg_count = 5;
+ strcpy(alltypes.rep_submsg[4].substuff1, "2016");
+ alltypes.rep_submsg[4].substuff2 = 2016;
+ alltypes.rep_submsg[4].has_substuff3 = true;
+ alltypes.rep_submsg[4].substuff3 = 2016;
+
+ alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth;
+ alltypes.rep_emptymsg_count = 5;
+
+ alltypes.req_limits.int32_min = INT32_MIN;
+ alltypes.req_limits.int32_max = INT32_MAX;
+ alltypes.req_limits.uint32_min = 0;
+ alltypes.req_limits.uint32_max = UINT32_MAX;
+ alltypes.req_limits.int64_min = INT64_MIN;
+ alltypes.req_limits.int64_max = INT64_MAX;
+ alltypes.req_limits.uint64_min = 0;
+ alltypes.req_limits.uint64_max = UINT64_MAX;
+ alltypes.req_limits.enum_min = HugeEnum_Negative;
+ alltypes.req_limits.enum_max = HugeEnum_Positive;
+
+ if (mode != 0)
+ {
+ /* Fill in values for optional fields */
+ alltypes.has_opt_int32 = true;
+ alltypes.opt_int32 = 3041;
+ alltypes.has_opt_int64 = true;
+ alltypes.opt_int64 = 3042;
+ alltypes.has_opt_uint32 = true;
+ alltypes.opt_uint32 = 3043;
+ alltypes.has_opt_uint64 = true;
+ alltypes.opt_uint64 = 3044;
+ alltypes.has_opt_sint32 = true;
+ alltypes.opt_sint32 = 3045;
+ alltypes.has_opt_sint64 = true;
+ alltypes.opt_sint64 = 3046;
+ alltypes.has_opt_bool = true;
+ alltypes.opt_bool = true;
+
+ alltypes.has_opt_fixed32 = true;
+ alltypes.opt_fixed32 = 3048;
+ alltypes.has_opt_sfixed32 = true;
+ alltypes.opt_sfixed32 = 3049;
+ alltypes.has_opt_float = true;
+ alltypes.opt_float = 3050.0f;
+
+ alltypes.has_opt_fixed64 = true;
+ alltypes.opt_fixed64 = 3051;
+ alltypes.has_opt_sfixed64 = true;
+ alltypes.opt_sfixed64 = 3052;
+ alltypes.has_opt_double = true;
+ alltypes.opt_double = 3053.0;
+
+ alltypes.has_opt_string = true;
+ strcpy(alltypes.opt_string, "3054");
+ alltypes.has_opt_bytes = true;
+ alltypes.opt_bytes.size = 4;
+ memcpy(alltypes.opt_bytes.bytes, "3055", 4);
+ alltypes.has_opt_submsg = true;
+ strcpy(alltypes.opt_submsg.substuff1, "3056");
+ alltypes.opt_submsg.substuff2 = 3056;
+ alltypes.has_opt_enum = true;
+ alltypes.opt_enum = MyEnum_Truth;
+ alltypes.has_opt_emptymsg = true;
+ }
+
+ alltypes.end = 1099;
+
+ {
+ uint8_t buffer[AllTypes_size];
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, AllTypes_fields, &alltypes))
+ {
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+ }
+}
diff --git a/tests/alltypes_callback/SConscript b/tests/alltypes_callback/SConscript
new file mode 100644
index 0000000..71b0160
--- /dev/null
+++ b/tests/alltypes_callback/SConscript
@@ -0,0 +1,23 @@
+# Test the AllTypes encoding & decoding using callbacks for all fields.
+
+Import("env")
+
+c = Copy("$TARGET", "$SOURCE")
+env.Command("alltypes.proto", "#alltypes/alltypes.proto", c)
+
+env.NanopbProto(["alltypes", "alltypes.options"])
+enc = env.Program(["encode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_alltypes_callback.c", "alltypes.pb.c", "$COMMON/pb_decode.o"])
+
+refdec = "$BUILD/alltypes/decode_alltypes$PROGSUFFIX"
+
+# Encode and compare results
+env.RunTest(enc)
+env.RunTest("decode_alltypes.output", [refdec, "encode_alltypes_callback.output"])
+env.RunTest("decode_alltypes_callback.output", [dec, "encode_alltypes_callback.output"])
+
+# Do the same thing with the optional fields present
+env.RunTest("optionals.output", enc, ARGS = ['1'])
+env.RunTest("optionals.refdecout", [refdec, "optionals.output"], ARGS = ['1'])
+env.RunTest("optionals.decout", [dec, "optionals.output"], ARGS = ['1'])
+
diff --git a/tests/alltypes_callback/alltypes.options b/tests/alltypes_callback/alltypes.options
new file mode 100644
index 0000000..a9c55ec
--- /dev/null
+++ b/tests/alltypes_callback/alltypes.options
@@ -0,0 +1,3 @@
+# Generate all fields as callbacks.
+AllTypes.* type:FT_CALLBACK
+SubMessage.substuff1 max_size:16
diff --git a/tests/alltypes_callback/decode_alltypes_callback.c b/tests/alltypes_callback/decode_alltypes_callback.c
new file mode 100644
index 0000000..81274f6
--- /dev/null
+++ b/tests/alltypes_callback/decode_alltypes_callback.c
@@ -0,0 +1,423 @@
+/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields.
+ * Note that normally there would be no reason to use callback fields for this,
+ * because each encoder defined here only gives a single field.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <pb_decode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+#define TEST(x) if (!(x)) { \
+ printf("Test " #x " failed (in field %d).\n", field->tag); \
+ return false; \
+ }
+
+static bool read_varint(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint64_t value;
+ if (!pb_decode_varint(stream, &value))
+ return false;
+
+ TEST((int64_t)value == (long)*arg);
+ return true;
+}
+
+static bool read_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ int64_t value;
+ if (!pb_decode_svarint(stream, &value))
+ return false;
+
+ TEST(value == (long)*arg);
+ return true;
+}
+
+static bool read_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint32_t value;
+ if (!pb_decode_fixed32(stream, &value))
+ return false;
+
+ TEST(value == *(uint32_t*)*arg);
+ return true;
+}
+
+static bool read_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint64_t value;
+ if (!pb_decode_fixed64(stream, &value))
+ return false;
+
+ TEST(value == *(uint64_t*)*arg);
+ return true;
+}
+
+static bool read_string(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint8_t buf[16] = {0};
+ size_t len = stream->bytes_left;
+
+ if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len))
+ return false;
+
+ TEST(strcmp((char*)buf, *arg) == 0);
+ return true;
+}
+
+static bool read_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ SubMessage submsg = {""};
+
+ if (!pb_decode(stream, SubMessage_fields, &submsg))
+ return false;
+
+ TEST(memcmp(&submsg, *arg, sizeof(submsg)));
+ return true;
+}
+
+static bool read_emptymsg(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ EmptyMessage emptymsg = {0};
+ return pb_decode(stream, EmptyMessage_fields, &emptymsg);
+}
+
+static bool read_repeated_varint(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ int32_t** expected = (int32_t**)arg;
+ uint64_t value;
+ if (!pb_decode_varint(stream, &value))
+ return false;
+
+ TEST(*(*expected)++ == value);
+ return true;
+}
+
+static bool read_repeated_svarint(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ int32_t** expected = (int32_t**)arg;
+ int64_t value;
+ if (!pb_decode_svarint(stream, &value))
+ return false;
+
+ TEST(*(*expected)++ == value);
+ return true;
+}
+
+static bool read_repeated_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint32_t** expected = (uint32_t**)arg;
+ uint32_t value;
+ if (!pb_decode_fixed32(stream, &value))
+ return false;
+
+ TEST(*(*expected)++ == value);
+ return true;
+}
+
+static bool read_repeated_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint64_t** expected = (uint64_t**)arg;
+ uint64_t value;
+ if (!pb_decode_fixed64(stream, &value))
+ return false;
+
+ TEST(*(*expected)++ == value);
+ return true;
+}
+
+static bool read_repeated_string(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint8_t*** expected = (uint8_t***)arg;
+ uint8_t buf[16] = {0};
+ size_t len = stream->bytes_left;
+
+ if (len > sizeof(buf) - 1 || !pb_read(stream, buf, len))
+ return false;
+
+ TEST(strcmp((char*)*(*expected)++, (char*)buf) == 0);
+ return true;
+}
+
+static bool read_repeated_submsg(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ SubMessage** expected = (SubMessage**)arg;
+ SubMessage decoded = {""};
+ if (!pb_decode(stream, SubMessage_fields, &decoded))
+ return false;
+
+ TEST(memcmp((*expected)++, &decoded, sizeof(decoded)) == 0);
+ return true;
+}
+
+static bool read_limits(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ Limits decoded = {0};
+ if (!pb_decode(stream, Limits_fields, &decoded))
+ return false;
+
+ TEST(decoded.int32_min == INT32_MIN);
+ TEST(decoded.int32_max == INT32_MAX);
+ TEST(decoded.uint32_min == 0);
+ TEST(decoded.uint32_max == UINT32_MAX);
+ TEST(decoded.int64_min == INT64_MIN);
+ TEST(decoded.int64_max == INT64_MAX);
+ TEST(decoded.uint64_min == 0);
+ TEST(decoded.uint64_max == UINT64_MAX);
+ TEST(decoded.enum_min == HugeEnum_Negative);
+ TEST(decoded.enum_max == HugeEnum_Positive);
+
+ return true;
+}
+
+/* This function is called once from main(), it handles
+ the decoding and checks the fields. */
+bool check_alltypes(pb_istream_t *stream, int mode)
+{
+ /* Values for use from callbacks through pointers. */
+ uint32_t req_fixed32 = 1008;
+ int32_t req_sfixed32 = -1009;
+ float req_float = 1010.0f;
+ uint64_t req_fixed64 = 1011;
+ int64_t req_sfixed64 = -1012;
+ double req_double = 1013.0;
+ SubMessage req_submsg = {"1016", 1016};
+
+ int32_t rep_int32[5] = {0, 0, 0, 0, -2001};
+ int32_t rep_int64[5] = {0, 0, 0, 0, -2002};
+ int32_t rep_uint32[5] = {0, 0, 0, 0, 2003};
+ int32_t rep_uint64[5] = {0, 0, 0, 0, 2004};
+ int32_t rep_sint32[5] = {0, 0, 0, 0, -2005};
+ int32_t rep_sint64[5] = {0, 0, 0, 0, -2006};
+ int32_t rep_bool[5] = {false, false, false, false, true};
+ uint32_t rep_fixed32[5] = {0, 0, 0, 0, 2008};
+ int32_t rep_sfixed32[5] = {0, 0, 0, 0, -2009};
+ float rep_float[5] = {0, 0, 0, 0, 2010.0f};
+ uint64_t rep_fixed64[5] = {0, 0, 0, 0, 2011};
+ int64_t rep_sfixed64[5] = {0, 0, 0, 0, -2012};
+ double rep_double[5] = {0, 0, 0, 0, 2013.0};
+ char* rep_string[5] = {"", "", "", "", "2014"};
+ char* rep_bytes[5] = {"", "", "", "", "2015"};
+ SubMessage rep_submsg[5] = {{"", 0, 0, 3},
+ {"", 0, 0, 3},
+ {"", 0, 0, 3},
+ {"", 0, 0, 3},
+ {"2016", 2016, true, 2016}};
+ int32_t rep_enum[5] = {0, 0, 0, 0, MyEnum_Truth};
+
+ uint32_t opt_fixed32 = 3048;
+ int32_t opt_sfixed32 = 3049;
+ float opt_float = 3050.0f;
+ uint64_t opt_fixed64 = 3051;
+ int64_t opt_sfixed64 = 3052;
+ double opt_double = 3053.0f;
+ SubMessage opt_submsg = {"3056", 3056};
+
+ /* Bind callbacks for required fields */
+ AllTypes alltypes;
+
+ /* Fill with garbage to better detect initialization errors */
+ memset(&alltypes, 0xAA, sizeof(alltypes));
+
+ alltypes.req_int32.funcs.decode = &read_varint;
+ alltypes.req_int32.arg = (void*)-1001;
+
+ alltypes.req_int64.funcs.decode = &read_varint;
+ alltypes.req_int64.arg = (void*)-1002;
+
+ alltypes.req_uint32.funcs.decode = &read_varint;
+ alltypes.req_uint32.arg = (void*)1003;
+
+ alltypes.req_uint32.funcs.decode = &read_varint;
+ alltypes.req_uint32.arg = (void*)1003;
+
+ alltypes.req_uint64.funcs.decode = &read_varint;
+ alltypes.req_uint64.arg = (void*)1004;
+
+ alltypes.req_sint32.funcs.decode = &read_svarint;
+ alltypes.req_sint32.arg = (void*)-1005;
+
+ alltypes.req_sint64.funcs.decode = &read_svarint;
+ alltypes.req_sint64.arg = (void*)-1006;
+
+ alltypes.req_bool.funcs.decode = &read_varint;
+ alltypes.req_bool.arg = (void*)true;
+
+ alltypes.req_fixed32.funcs.decode = &read_fixed32;
+ alltypes.req_fixed32.arg = &req_fixed32;
+
+ alltypes.req_sfixed32.funcs.decode = &read_fixed32;
+ alltypes.req_sfixed32.arg = &req_sfixed32;
+
+ alltypes.req_float.funcs.decode = &read_fixed32;
+ alltypes.req_float.arg = &req_float;
+
+ alltypes.req_fixed64.funcs.decode = &read_fixed64;
+ alltypes.req_fixed64.arg = &req_fixed64;
+
+ alltypes.req_sfixed64.funcs.decode = &read_fixed64;
+ alltypes.req_sfixed64.arg = &req_sfixed64;
+
+ alltypes.req_double.funcs.decode = &read_fixed64;
+ alltypes.req_double.arg = &req_double;
+
+ alltypes.req_string.funcs.decode = &read_string;
+ alltypes.req_string.arg = "1014";
+
+ alltypes.req_bytes.funcs.decode = &read_string;
+ alltypes.req_bytes.arg = "1015";
+
+ alltypes.req_submsg.funcs.decode = &read_submsg;
+ alltypes.req_submsg.arg = &req_submsg;
+
+ alltypes.req_enum.funcs.decode = &read_varint;
+ alltypes.req_enum.arg = (void*)MyEnum_Truth;
+
+ alltypes.req_emptymsg.funcs.decode = &read_emptymsg;
+
+ /* Bind callbacks for repeated fields */
+ alltypes.rep_int32.funcs.decode = &read_repeated_varint;
+ alltypes.rep_int32.arg = rep_int32;
+
+ alltypes.rep_int64.funcs.decode = &read_repeated_varint;
+ alltypes.rep_int64.arg = rep_int64;
+
+ alltypes.rep_uint32.funcs.decode = &read_repeated_varint;
+ alltypes.rep_uint32.arg = rep_uint32;
+
+ alltypes.rep_uint64.funcs.decode = &read_repeated_varint;
+ alltypes.rep_uint64.arg = rep_uint64;
+
+ alltypes.rep_sint32.funcs.decode = &read_repeated_svarint;
+ alltypes.rep_sint32.arg = rep_sint32;
+
+ alltypes.rep_sint64.funcs.decode = &read_repeated_svarint;
+ alltypes.rep_sint64.arg = rep_sint64;
+
+ alltypes.rep_bool.funcs.decode = &read_repeated_varint;
+ alltypes.rep_bool.arg = rep_bool;
+
+ alltypes.rep_fixed32.funcs.decode = &read_repeated_fixed32;
+ alltypes.rep_fixed32.arg = rep_fixed32;
+
+ alltypes.rep_sfixed32.funcs.decode = &read_repeated_fixed32;
+ alltypes.rep_sfixed32.arg = rep_sfixed32;
+
+ alltypes.rep_float.funcs.decode = &read_repeated_fixed32;
+ alltypes.rep_float.arg = rep_float;
+
+ alltypes.rep_fixed64.funcs.decode = &read_repeated_fixed64;
+ alltypes.rep_fixed64.arg = rep_fixed64;
+
+ alltypes.rep_sfixed64.funcs.decode = &read_repeated_fixed64;
+ alltypes.rep_sfixed64.arg = rep_sfixed64;
+
+ alltypes.rep_double.funcs.decode = &read_repeated_fixed64;
+ alltypes.rep_double.arg = rep_double;
+
+ alltypes.rep_string.funcs.decode = &read_repeated_string;
+ alltypes.rep_string.arg = rep_string;
+
+ alltypes.rep_bytes.funcs.decode = &read_repeated_string;
+ alltypes.rep_bytes.arg = rep_bytes;
+
+ alltypes.rep_submsg.funcs.decode = &read_repeated_submsg;
+ alltypes.rep_submsg.arg = rep_submsg;
+
+ alltypes.rep_enum.funcs.decode = &read_repeated_varint;
+ alltypes.rep_enum.arg = rep_enum;
+
+ alltypes.rep_emptymsg.funcs.decode = &read_emptymsg;
+
+ alltypes.req_limits.funcs.decode = &read_limits;
+
+ alltypes.end.funcs.decode = &read_varint;
+ alltypes.end.arg = (void*)1099;
+
+ /* Bind callbacks for optional fields */
+ if (mode == 1)
+ {
+ alltypes.opt_int32.funcs.decode = &read_varint;
+ alltypes.opt_int32.arg = (void*)3041;
+
+ alltypes.opt_int64.funcs.decode = &read_varint;
+ alltypes.opt_int64.arg = (void*)3042;
+
+ alltypes.opt_uint32.funcs.decode = &read_varint;
+ alltypes.opt_uint32.arg = (void*)3043;
+
+ alltypes.opt_uint64.funcs.decode = &read_varint;
+ alltypes.opt_uint64.arg = (void*)3044;
+
+ alltypes.opt_sint32.funcs.decode = &read_svarint;
+ alltypes.opt_sint32.arg = (void*)3045;
+
+ alltypes.opt_sint64.funcs.decode = &read_svarint;
+ alltypes.opt_sint64.arg = (void*)3046;
+
+ alltypes.opt_bool.funcs.decode = &read_varint;
+ alltypes.opt_bool.arg = (void*)true;
+
+ alltypes.opt_fixed32.funcs.decode = &read_fixed32;
+ alltypes.opt_fixed32.arg = &opt_fixed32;
+
+ alltypes.opt_sfixed32.funcs.decode = &read_fixed32;
+ alltypes.opt_sfixed32.arg = &opt_sfixed32;
+
+ alltypes.opt_float.funcs.decode = &read_fixed32;
+ alltypes.opt_float.arg = &opt_float;
+
+ alltypes.opt_fixed64.funcs.decode = &read_fixed64;
+ alltypes.opt_fixed64.arg = &opt_fixed64;
+
+ alltypes.opt_sfixed64.funcs.decode = &read_fixed64;
+ alltypes.opt_sfixed64.arg = &opt_sfixed64;
+
+ alltypes.opt_double.funcs.decode = &read_fixed64;
+ alltypes.opt_double.arg = &opt_double;
+
+ alltypes.opt_string.funcs.decode = &read_string;
+ alltypes.opt_string.arg = "3054";
+
+ alltypes.opt_bytes.funcs.decode = &read_string;
+ alltypes.opt_bytes.arg = "3055";
+
+ alltypes.opt_submsg.funcs.decode = &read_submsg;
+ alltypes.opt_submsg.arg = &opt_submsg;
+
+ alltypes.opt_enum.funcs.decode = &read_varint;
+ alltypes.opt_enum.arg = (void*)MyEnum_Truth;
+
+ alltypes.opt_emptymsg.funcs.decode = &read_emptymsg;
+ }
+
+ return pb_decode(stream, AllTypes_fields, &alltypes);
+}
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ size_t count;
+ pb_istream_t stream;
+
+ /* Whether to expect the optional values or the default values. */
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Read the data into buffer */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+
+ /* Construct a pb_istream_t for reading from the buffer */
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Decode and print out the stuff */
+ if (!check_alltypes(&stream, mode))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ } else {
+ return 0;
+ }
+}
diff --git a/tests/alltypes_callback/encode_alltypes_callback.c b/tests/alltypes_callback/encode_alltypes_callback.c
new file mode 100644
index 0000000..10560b1
--- /dev/null
+++ b/tests/alltypes_callback/encode_alltypes_callback.c
@@ -0,0 +1,397 @@
+/* Attempts to test all the datatypes supported by ProtoBuf when used as callback fields.
+ * Note that normally there would be no reason to use callback fields for this,
+ * because each encoder defined here only gives a single field.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+static bool write_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, (long)*arg);
+}
+
+static bool write_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, (long)*arg);
+}
+
+static bool write_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_fixed32(stream, *arg);
+}
+
+static bool write_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_fixed64(stream, *arg);
+}
+
+static bool write_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, *arg, strlen(*arg));
+}
+
+static bool write_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, *arg);
+}
+
+static bool write_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ EmptyMessage emptymsg = {0};
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg);
+}
+
+static bool write_repeated_varint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_varint(stream, (long)*arg);
+}
+
+static bool write_repeated_svarint(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_svarint(stream, (long)*arg);
+}
+
+static bool write_repeated_fixed32(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ uint32_t dummy = 0;
+
+ /* Make it a packed field */
+ return pb_encode_tag(stream, PB_WT_STRING, field->tag) &&
+ pb_encode_varint(stream, 5 * 4) && /* Number of bytes */
+ pb_encode_fixed32(stream, &dummy) &&
+ pb_encode_fixed32(stream, &dummy) &&
+ pb_encode_fixed32(stream, &dummy) &&
+ pb_encode_fixed32(stream, &dummy) &&
+ pb_encode_fixed32(stream, *arg);
+}
+
+static bool write_repeated_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ uint64_t dummy = 0;
+
+ /* Make it a packed field */
+ return pb_encode_tag(stream, PB_WT_STRING, field->tag) &&
+ pb_encode_varint(stream, 5 * 8) && /* Number of bytes */
+ pb_encode_fixed64(stream, &dummy) &&
+ pb_encode_fixed64(stream, &dummy) &&
+ pb_encode_fixed64(stream, &dummy) &&
+ pb_encode_fixed64(stream, &dummy) &&
+ pb_encode_fixed64(stream, *arg);
+}
+
+static bool write_repeated_string(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, 0, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, 0, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, 0, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, 0, 0) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_string(stream, *arg, strlen(*arg));
+}
+
+static bool write_repeated_submsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ SubMessage dummy = {""};
+
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, &dummy) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, &dummy) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, &dummy) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, &dummy) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, SubMessage_fields, *arg);
+}
+
+static bool write_limits(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ Limits limits = {0};
+ limits.int32_min = INT32_MIN;
+ limits.int32_max = INT32_MAX;
+ limits.uint32_min = 0;
+ limits.uint32_max = UINT32_MAX;
+ limits.int64_min = INT64_MIN;
+ limits.int64_max = INT64_MAX;
+ limits.uint64_min = 0;
+ limits.uint64_max = UINT64_MAX;
+ limits.enum_min = HugeEnum_Negative;
+ limits.enum_max = HugeEnum_Positive;
+
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, Limits_fields, &limits);
+}
+
+static bool write_repeated_emptymsg(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ EmptyMessage emptymsg = {0};
+ return pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg) &&
+ pb_encode_tag_for_field(stream, field) &&
+ pb_encode_submessage(stream, EmptyMessage_fields, &emptymsg);
+}
+
+int main(int argc, char **argv)
+{
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Values for use from callbacks through pointers. */
+ uint32_t req_fixed32 = 1008;
+ int32_t req_sfixed32 = -1009;
+ float req_float = 1010.0f;
+ uint64_t req_fixed64 = 1011;
+ int64_t req_sfixed64 = -1012;
+ double req_double = 1013.0;
+ SubMessage req_submsg = {"1016", 1016};
+
+ uint32_t rep_fixed32 = 2008;
+ int32_t rep_sfixed32 = -2009;
+ float rep_float = 2010.0f;
+ uint64_t rep_fixed64 = 2011;
+ int64_t rep_sfixed64 = -2012;
+ double rep_double = 2013.0;
+ SubMessage rep_submsg = {"2016", 2016, true, 2016};
+
+ uint32_t opt_fixed32 = 3048;
+ int32_t opt_sfixed32 = 3049;
+ float opt_float = 3050.0f;
+ uint64_t opt_fixed64 = 3051;
+ int64_t opt_sfixed64 = 3052;
+ double opt_double = 3053.0f;
+ SubMessage opt_submsg = {"3056", 3056};
+
+ /* Bind callbacks for required fields */
+ AllTypes alltypes = {{{0}}};
+
+ alltypes.req_int32.funcs.encode = &write_varint;
+ alltypes.req_int32.arg = (void*)-1001;
+
+ alltypes.req_int64.funcs.encode = &write_varint;
+ alltypes.req_int64.arg = (void*)-1002;
+
+ alltypes.req_uint32.funcs.encode = &write_varint;
+ alltypes.req_uint32.arg = (void*)1003;
+
+ alltypes.req_uint32.funcs.encode = &write_varint;
+ alltypes.req_uint32.arg = (void*)1003;
+
+ alltypes.req_uint64.funcs.encode = &write_varint;
+ alltypes.req_uint64.arg = (void*)1004;
+
+ alltypes.req_sint32.funcs.encode = &write_svarint;
+ alltypes.req_sint32.arg = (void*)-1005;
+
+ alltypes.req_sint64.funcs.encode = &write_svarint;
+ alltypes.req_sint64.arg = (void*)-1006;
+
+ alltypes.req_bool.funcs.encode = &write_varint;
+ alltypes.req_bool.arg = (void*)true;
+
+ alltypes.req_fixed32.funcs.encode = &write_fixed32;
+ alltypes.req_fixed32.arg = &req_fixed32;
+
+ alltypes.req_sfixed32.funcs.encode = &write_fixed32;
+ alltypes.req_sfixed32.arg = &req_sfixed32;
+
+ alltypes.req_float.funcs.encode = &write_fixed32;
+ alltypes.req_float.arg = &req_float;
+
+ alltypes.req_fixed64.funcs.encode = &write_fixed64;
+ alltypes.req_fixed64.arg = &req_fixed64;
+
+ alltypes.req_sfixed64.funcs.encode = &write_fixed64;
+ alltypes.req_sfixed64.arg = &req_sfixed64;
+
+ alltypes.req_double.funcs.encode = &write_fixed64;
+ alltypes.req_double.arg = &req_double;
+
+ alltypes.req_string.funcs.encode = &write_string;
+ alltypes.req_string.arg = "1014";
+
+ alltypes.req_bytes.funcs.encode = &write_string;
+ alltypes.req_bytes.arg = "1015";
+
+ alltypes.req_submsg.funcs.encode = &write_submsg;
+ alltypes.req_submsg.arg = &req_submsg;
+
+ alltypes.req_enum.funcs.encode = &write_varint;
+ alltypes.req_enum.arg = (void*)MyEnum_Truth;
+
+ alltypes.req_emptymsg.funcs.encode = &write_emptymsg;
+
+ /* Bind callbacks for repeated fields */
+ alltypes.rep_int32.funcs.encode = &write_repeated_varint;
+ alltypes.rep_int32.arg = (void*)-2001;
+
+ alltypes.rep_int64.funcs.encode = &write_repeated_varint;
+ alltypes.rep_int64.arg = (void*)-2002;
+
+ alltypes.rep_uint32.funcs.encode = &write_repeated_varint;
+ alltypes.rep_uint32.arg = (void*)2003;
+
+ alltypes.rep_uint64.funcs.encode = &write_repeated_varint;
+ alltypes.rep_uint64.arg = (void*)2004;
+
+ alltypes.rep_sint32.funcs.encode = &write_repeated_svarint;
+ alltypes.rep_sint32.arg = (void*)-2005;
+
+ alltypes.rep_sint64.funcs.encode = &write_repeated_svarint;
+ alltypes.rep_sint64.arg = (void*)-2006;
+
+ alltypes.rep_bool.funcs.encode = &write_repeated_varint;
+ alltypes.rep_bool.arg = (void*)true;
+
+ alltypes.rep_fixed32.funcs.encode = &write_repeated_fixed32;
+ alltypes.rep_fixed32.arg = &rep_fixed32;
+
+ alltypes.rep_sfixed32.funcs.encode = &write_repeated_fixed32;
+ alltypes.rep_sfixed32.arg = &rep_sfixed32;
+
+ alltypes.rep_float.funcs.encode = &write_repeated_fixed32;
+ alltypes.rep_float.arg = &rep_float;
+
+ alltypes.rep_fixed64.funcs.encode = &write_repeated_fixed64;
+ alltypes.rep_fixed64.arg = &rep_fixed64;
+
+ alltypes.rep_sfixed64.funcs.encode = &write_repeated_fixed64;
+ alltypes.rep_sfixed64.arg = &rep_sfixed64;
+
+ alltypes.rep_double.funcs.encode = &write_repeated_fixed64;
+ alltypes.rep_double.arg = &rep_double;
+
+ alltypes.rep_string.funcs.encode = &write_repeated_string;
+ alltypes.rep_string.arg = "2014";
+
+ alltypes.rep_bytes.funcs.encode = &write_repeated_string;
+ alltypes.rep_bytes.arg = "2015";
+
+ alltypes.rep_submsg.funcs.encode = &write_repeated_submsg;
+ alltypes.rep_submsg.arg = &rep_submsg;
+
+ alltypes.rep_enum.funcs.encode = &write_repeated_varint;
+ alltypes.rep_enum.arg = (void*)MyEnum_Truth;
+
+ alltypes.rep_emptymsg.funcs.encode = &write_repeated_emptymsg;
+
+ alltypes.req_limits.funcs.encode = &write_limits;
+
+ /* Bind callbacks for optional fields */
+ if (mode != 0)
+ {
+ alltypes.opt_int32.funcs.encode = &write_varint;
+ alltypes.opt_int32.arg = (void*)3041;
+
+ alltypes.opt_int64.funcs.encode = &write_varint;
+ alltypes.opt_int64.arg = (void*)3042;
+
+ alltypes.opt_uint32.funcs.encode = &write_varint;
+ alltypes.opt_uint32.arg = (void*)3043;
+
+ alltypes.opt_uint64.funcs.encode = &write_varint;
+ alltypes.opt_uint64.arg = (void*)3044;
+
+ alltypes.opt_sint32.funcs.encode = &write_svarint;
+ alltypes.opt_sint32.arg = (void*)3045;
+
+ alltypes.opt_sint64.funcs.encode = &write_svarint;
+ alltypes.opt_sint64.arg = (void*)3046;
+
+ alltypes.opt_bool.funcs.encode = &write_varint;
+ alltypes.opt_bool.arg = (void*)true;
+
+ alltypes.opt_fixed32.funcs.encode = &write_fixed32;
+ alltypes.opt_fixed32.arg = &opt_fixed32;
+
+ alltypes.opt_sfixed32.funcs.encode = &write_fixed32;
+ alltypes.opt_sfixed32.arg = &opt_sfixed32;
+
+ alltypes.opt_float.funcs.encode = &write_fixed32;
+ alltypes.opt_float.arg = &opt_float;
+
+ alltypes.opt_fixed64.funcs.encode = &write_fixed64;
+ alltypes.opt_fixed64.arg = &opt_fixed64;
+
+ alltypes.opt_sfixed64.funcs.encode = &write_fixed64;
+ alltypes.opt_sfixed64.arg = &opt_sfixed64;
+
+ alltypes.opt_double.funcs.encode = &write_fixed64;
+ alltypes.opt_double.arg = &opt_double;
+
+ alltypes.opt_string.funcs.encode = &write_string;
+ alltypes.opt_string.arg = "3054";
+
+ alltypes.opt_bytes.funcs.encode = &write_string;
+ alltypes.opt_bytes.arg = "3055";
+
+ alltypes.opt_submsg.funcs.encode = &write_submsg;
+ alltypes.opt_submsg.arg = &opt_submsg;
+
+ alltypes.opt_enum.funcs.encode = &write_varint;
+ alltypes.opt_enum.arg = (void*)MyEnum_Truth;
+
+ alltypes.opt_emptymsg.funcs.encode = &write_emptymsg;
+ }
+
+ alltypes.end.funcs.encode = &write_varint;
+ alltypes.end.arg = (void*)1099;
+
+ {
+ uint8_t buffer[2048];
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, AllTypes_fields, &alltypes))
+ {
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+ }
+}
diff --git a/tests/alltypes_pointer/SConscript b/tests/alltypes_pointer/SConscript
new file mode 100644
index 0000000..e48d6aa
--- /dev/null
+++ b/tests/alltypes_pointer/SConscript
@@ -0,0 +1,48 @@
+# Encode the AllTypes message using pointers for all fields, and verify the
+# output against the normal AllTypes test case.
+
+Import("env")
+
+# We need our own pb_decode.o for the malloc support
+env = env.Clone()
+env.Append(CPPDEFINES = {'PB_ENABLE_MALLOC': 1});
+
+# Disable libmudflap, because it will confuse valgrind
+# and other memory leak detection tools.
+if '-fmudflap' in env["CCFLAGS"]:
+ env["CCFLAGS"].remove("-fmudflap")
+ env["LINKFLAGS"].remove("-fmudflap")
+ env["LIBS"].remove("mudflap")
+
+strict = env.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode_with_malloc.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode_with_malloc.o", "$NANOPB/pb_encode.c")
+
+c = Copy("$TARGET", "$SOURCE")
+env.Command("alltypes.proto", "#alltypes/alltypes.proto", c)
+
+env.NanopbProto(["alltypes", "alltypes.options"])
+enc = env.Program(["encode_alltypes_pointer.c", "alltypes.pb.c", "pb_encode_with_malloc.o"])
+dec = env.Program(["decode_alltypes_pointer.c", "alltypes.pb.c", "pb_decode_with_malloc.o"])
+
+# Encode and compare results to non-pointer alltypes test case
+env.RunTest(enc)
+env.Compare(["encode_alltypes_pointer.output", "$BUILD/alltypes/encode_alltypes.output"])
+
+# Decode (under valgrind if available)
+valgrind = env.WhereIs('valgrind')
+kwargs = {}
+if valgrind:
+ kwargs['COMMAND'] = valgrind
+ kwargs['ARGS'] = ["-q", dec[0].abspath]
+
+env.RunTest("decode_alltypes.output", [dec, "encode_alltypes_pointer.output"], **kwargs)
+
+# Do the same thing with the optional fields present
+env.RunTest("optionals.output", enc, ARGS = ['1'])
+env.Compare(["optionals.output", "$BUILD/alltypes/optionals.output"])
+
+kwargs['ARGS'] = kwargs.get('ARGS', []) + ['1']
+env.RunTest("optionals.decout", [dec, "optionals.output"], **kwargs)
+
diff --git a/tests/alltypes_pointer/alltypes.options b/tests/alltypes_pointer/alltypes.options
new file mode 100644
index 0000000..52abeb7
--- /dev/null
+++ b/tests/alltypes_pointer/alltypes.options
@@ -0,0 +1,3 @@
+# Generate all fields as pointers.
+* type:FT_POINTER
+
diff --git a/tests/alltypes_pointer/decode_alltypes_pointer.c b/tests/alltypes_pointer/decode_alltypes_pointer.c
new file mode 100644
index 0000000..889676b
--- /dev/null
+++ b/tests/alltypes_pointer/decode_alltypes_pointer.c
@@ -0,0 +1,173 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <pb_decode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+#define TEST(x) if (!(x)) { \
+ fprintf(stderr, "Test " #x " failed.\n"); \
+ status = false; \
+ }
+
+/* This function is called once from main(), it handles
+ the decoding and checks the fields. */
+bool check_alltypes(pb_istream_t *stream, int mode)
+{
+ bool status = true;
+ AllTypes alltypes;
+
+ /* Fill with garbage to better detect initialization errors */
+ memset(&alltypes, 0xAA, sizeof(alltypes));
+
+ if (!pb_decode(stream, AllTypes_fields, &alltypes))
+ return false;
+
+ TEST(alltypes.req_int32 && *alltypes.req_int32 == -1001);
+ TEST(alltypes.req_int64 && *alltypes.req_int64 == -1002);
+ TEST(alltypes.req_uint32 && *alltypes.req_uint32 == 1003);
+ TEST(alltypes.req_uint64 && *alltypes.req_uint64 == 1004);
+ TEST(alltypes.req_sint32 && *alltypes.req_sint32 == -1005);
+ TEST(alltypes.req_sint64 && *alltypes.req_sint64 == -1006);
+ TEST(alltypes.req_bool && *alltypes.req_bool == true);
+
+ TEST(alltypes.req_fixed32 && *alltypes.req_fixed32 == 1008);
+ TEST(alltypes.req_sfixed32 && *alltypes.req_sfixed32 == -1009);
+ TEST(alltypes.req_float && *alltypes.req_float == 1010.0f);
+
+ TEST(alltypes.req_fixed64 && *alltypes.req_fixed64 == 1011);
+ TEST(alltypes.req_sfixed64 && *alltypes.req_sfixed64 == -1012);
+ TEST(alltypes.req_double && *alltypes.req_double == 1013.0f);
+
+ TEST(alltypes.req_string && strcmp(alltypes.req_string, "1014") == 0);
+ TEST(alltypes.req_bytes && alltypes.req_bytes->size == 4);
+ TEST(alltypes.req_bytes && memcmp(&alltypes.req_bytes->bytes, "1015", 4) == 0);
+ TEST(alltypes.req_submsg && alltypes.req_submsg->substuff1
+ && strcmp(alltypes.req_submsg->substuff1, "1016") == 0);
+ TEST(alltypes.req_submsg && alltypes.req_submsg->substuff2
+ && *alltypes.req_submsg->substuff2 == 1016);
+ TEST(*alltypes.req_enum == MyEnum_Truth);
+
+ TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0);
+ TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0);
+ TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0);
+ TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0);
+ TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0);
+ TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0);
+ TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false);
+
+ TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0);
+ TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0);
+ TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f);
+
+ TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0);
+ TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0);
+ TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0);
+
+ TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0');
+ TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4]->size == 4 && alltypes.rep_bytes[0]->size == 0);
+ TEST(memcmp(&alltypes.rep_bytes[4]->bytes, "2015", 4) == 0);
+
+ TEST(alltypes.rep_submsg_count == 5);
+ TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0');
+ TEST(*alltypes.rep_submsg[4].substuff2 == 2016 && *alltypes.rep_submsg[0].substuff2 == 0);
+ TEST(*alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == NULL);
+
+ TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero);
+ TEST(alltypes.rep_emptymsg_count == 5);
+
+ if (mode == 0)
+ {
+ /* Expect that optional values are not present */
+ TEST(alltypes.opt_int32 == NULL);
+ TEST(alltypes.opt_int64 == NULL);
+ TEST(alltypes.opt_uint32 == NULL);
+ TEST(alltypes.opt_uint64 == NULL);
+ TEST(alltypes.opt_sint32 == NULL);
+ TEST(alltypes.opt_sint64 == NULL);
+ TEST(alltypes.opt_bool == NULL);
+
+ TEST(alltypes.opt_fixed32 == NULL);
+ TEST(alltypes.opt_sfixed32 == NULL);
+ TEST(alltypes.opt_float == NULL);
+ TEST(alltypes.opt_fixed64 == NULL);
+ TEST(alltypes.opt_sfixed64 == NULL);
+ TEST(alltypes.opt_double == NULL);
+
+ TEST(alltypes.opt_string == NULL);
+ TEST(alltypes.opt_bytes == NULL);
+ TEST(alltypes.opt_submsg == NULL);
+ TEST(alltypes.opt_enum == NULL);
+ }
+ else
+ {
+ /* Expect filled-in values */
+ TEST(alltypes.opt_int32 && *alltypes.opt_int32 == 3041);
+ TEST(alltypes.opt_int64 && *alltypes.opt_int64 == 3042);
+ TEST(alltypes.opt_uint32 && *alltypes.opt_uint32 == 3043);
+ TEST(alltypes.opt_uint64 && *alltypes.opt_uint64 == 3044);
+ TEST(alltypes.opt_sint32 && *alltypes.opt_sint32 == 3045);
+ TEST(alltypes.opt_sint64 && *alltypes.opt_sint64 == 3046);
+ TEST(alltypes.opt_bool && *alltypes.opt_bool == true);
+
+ TEST(alltypes.opt_fixed32 && *alltypes.opt_fixed32 == 3048);
+ TEST(alltypes.opt_sfixed32 && *alltypes.opt_sfixed32== 3049);
+ TEST(alltypes.opt_float && *alltypes.opt_float == 3050.0f);
+ TEST(alltypes.opt_fixed64 && *alltypes.opt_fixed64 == 3051);
+ TEST(alltypes.opt_sfixed64 && *alltypes.opt_sfixed64== 3052);
+ TEST(alltypes.opt_double && *alltypes.opt_double == 3053.0);
+
+ TEST(alltypes.opt_string && strcmp(alltypes.opt_string, "3054") == 0);
+ TEST(alltypes.opt_bytes && alltypes.opt_bytes->size == 4);
+ TEST(alltypes.opt_bytes && memcmp(&alltypes.opt_bytes->bytes, "3055", 4) == 0);
+ TEST(alltypes.opt_submsg && strcmp(alltypes.opt_submsg->substuff1, "3056") == 0);
+ TEST(alltypes.opt_submsg && *alltypes.opt_submsg->substuff2 == 3056);
+ TEST(alltypes.opt_enum && *alltypes.opt_enum == MyEnum_Truth);
+ TEST(alltypes.opt_emptymsg);
+ }
+
+ TEST(alltypes.req_limits->int32_min && *alltypes.req_limits->int32_min == INT32_MIN);
+ TEST(alltypes.req_limits->int32_max && *alltypes.req_limits->int32_max == INT32_MAX);
+ TEST(alltypes.req_limits->uint32_min && *alltypes.req_limits->uint32_min == 0);
+ TEST(alltypes.req_limits->uint32_max && *alltypes.req_limits->uint32_max == UINT32_MAX);
+ TEST(alltypes.req_limits->int64_min && *alltypes.req_limits->int64_min == INT64_MIN);
+ TEST(alltypes.req_limits->int64_max && *alltypes.req_limits->int64_max == INT64_MAX);
+ TEST(alltypes.req_limits->uint64_min && *alltypes.req_limits->uint64_min == 0);
+ TEST(alltypes.req_limits->uint64_max && *alltypes.req_limits->uint64_max == UINT64_MAX);
+ TEST(alltypes.req_limits->enum_min && *alltypes.req_limits->enum_min == HugeEnum_Negative);
+ TEST(alltypes.req_limits->enum_max && *alltypes.req_limits->enum_max == HugeEnum_Positive);
+
+ TEST(alltypes.end && *alltypes.end == 1099);
+
+ pb_release(AllTypes_fields, &alltypes);
+
+ return status;
+}
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ size_t count;
+ pb_istream_t stream;
+
+ /* Whether to expect the optional values or the default values. */
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Read the data into buffer */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+
+ /* Construct a pb_istream_t for reading from the buffer */
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Decode and verify the message */
+ if (!check_alltypes(&stream, mode))
+ {
+ fprintf(stderr, "Test failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ }
+ else
+ {
+ return 0;
+ }
+}
diff --git a/tests/alltypes_pointer/encode_alltypes_pointer.c b/tests/alltypes_pointer/encode_alltypes_pointer.c
new file mode 100644
index 0000000..c128569
--- /dev/null
+++ b/tests/alltypes_pointer/encode_alltypes_pointer.c
@@ -0,0 +1,188 @@
+/* Attempts to test all the datatypes supported by ProtoBuf.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "alltypes.pb.h"
+#include "test_helpers.h"
+
+int main(int argc, char **argv)
+{
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Values for required fields */
+ int32_t req_int32 = -1001;
+ int64_t req_int64 = -1002;
+ uint32_t req_uint32 = 1003;
+ uint64_t req_uint64 = 1004;
+ int32_t req_sint32 = -1005;
+ int64_t req_sint64 = -1006;
+ bool req_bool = true;
+ uint32_t req_fixed32 = 1008;
+ int32_t req_sfixed32 = -1009;
+ float req_float = 1010.0f;
+ uint64_t req_fixed64 = 1011;
+ int64_t req_sfixed64 = -1012;
+ double req_double = 1013.0;
+ char* req_string = "1014";
+ PB_BYTES_ARRAY_T(4) req_bytes = {4, {'1', '0', '1', '5'}};
+ static int32_t req_substuff = 1016;
+ SubMessage req_submsg = {"1016", &req_substuff};
+ MyEnum req_enum = MyEnum_Truth;
+ EmptyMessage req_emptymsg = {0};
+
+ int32_t end = 1099;
+
+ /* Values for repeated fields */
+ int32_t rep_int32[5] = {0, 0, 0, 0, -2001};
+ int64_t rep_int64[5] = {0, 0, 0, 0, -2002};
+ uint32_t rep_uint32[5] = {0, 0, 0, 0, 2003};
+ uint64_t rep_uint64[5] = {0, 0, 0, 0, 2004};
+ int32_t rep_sint32[5] = {0, 0, 0, 0, -2005};
+ int64_t rep_sint64[5] = {0, 0, 0, 0, -2006};
+ bool rep_bool[5] = {false, false, false, false, true};
+ uint32_t rep_fixed32[5] = {0, 0, 0, 0, 2008};
+ int32_t rep_sfixed32[5] = {0, 0, 0, 0, -2009};
+ float rep_float[5] = {0, 0, 0, 0, 2010.0f};
+ uint64_t rep_fixed64[5] = {0, 0, 0, 0, 2011};
+ int64_t rep_sfixed64[5] = {0, 0, 0, 0, -2012};
+ double rep_double[5] = {0, 0, 0, 0, 2013.0f};
+ char* rep_string[5] = {"", "", "", "", "2014"};
+ static PB_BYTES_ARRAY_T(4) rep_bytes_4 = {4, {'2', '0', '1', '5'}};
+ pb_bytes_array_t *rep_bytes[5]= {NULL, NULL, NULL, NULL, (pb_bytes_array_t*)&rep_bytes_4};
+ static int32_t rep_sub2zero = 0;
+ static int32_t rep_substuff2 = 2016;
+ static uint32_t rep_substuff3 = 2016;
+ SubMessage rep_submsg[5] = {{"", &rep_sub2zero},
+ {"", &rep_sub2zero},
+ {"", &rep_sub2zero},
+ {"", &rep_sub2zero},
+ {"2016", &rep_substuff2, &rep_substuff3}};
+ MyEnum rep_enum[5] = {0, 0, 0, 0, MyEnum_Truth};
+ EmptyMessage rep_emptymsg[5] = {{0}, {0}, {0}, {0}, {0}};
+
+ /* Values for optional fields */
+ int32_t opt_int32 = 3041;
+ int64_t opt_int64 = 3042;
+ uint32_t opt_uint32 = 3043;
+ uint64_t opt_uint64 = 3044;
+ int32_t opt_sint32 = 3045;
+ int64_t opt_sint64 = 3046;
+ bool opt_bool = true;
+ uint32_t opt_fixed32 = 3048;
+ int32_t opt_sfixed32 = 3049;
+ float opt_float = 3050.0f;
+ uint64_t opt_fixed64 = 3051;
+ int64_t opt_sfixed64 = 3052;
+ double opt_double = 3053.0;
+ char* opt_string = "3054";
+ PB_BYTES_ARRAY_T(4) opt_bytes = {4, {'3', '0', '5', '5'}};
+ static int32_t opt_substuff = 3056;
+ SubMessage opt_submsg = {"3056", &opt_substuff};
+ MyEnum opt_enum = MyEnum_Truth;
+ EmptyMessage opt_emptymsg = {0};
+
+ /* Values for the Limits message. */
+ static int32_t int32_min = INT32_MIN;
+ static int32_t int32_max = INT32_MAX;
+ static uint32_t uint32_min = 0;
+ static uint32_t uint32_max = UINT32_MAX;
+ static int64_t int64_min = INT64_MIN;
+ static int64_t int64_max = INT64_MAX;
+ static uint64_t uint64_min = 0;
+ static uint64_t uint64_max = UINT64_MAX;
+ static HugeEnum enum_min = HugeEnum_Negative;
+ static HugeEnum enum_max = HugeEnum_Positive;
+ Limits req_limits = {&int32_min, &int32_max,
+ &uint32_min, &uint32_max,
+ &int64_min, &int64_max,
+ &uint64_min, &uint64_max,
+ &enum_min, &enum_max};
+
+ /* Initialize the message struct with pointers to the fields. */
+ AllTypes alltypes = {0};
+
+ alltypes.req_int32 = &req_int32;
+ alltypes.req_int64 = &req_int64;
+ alltypes.req_uint32 = &req_uint32;
+ alltypes.req_uint64 = &req_uint64;
+ alltypes.req_sint32 = &req_sint32;
+ alltypes.req_sint64 = &req_sint64;
+ alltypes.req_bool = &req_bool;
+ alltypes.req_fixed32 = &req_fixed32;
+ alltypes.req_sfixed32 = &req_sfixed32;
+ alltypes.req_float = &req_float;
+ alltypes.req_fixed64 = &req_fixed64;
+ alltypes.req_sfixed64 = &req_sfixed64;
+ alltypes.req_double = &req_double;
+ alltypes.req_string = req_string;
+ alltypes.req_bytes = (pb_bytes_array_t*)&req_bytes;
+ alltypes.req_submsg = &req_submsg;
+ alltypes.req_enum = &req_enum;
+ alltypes.req_emptymsg = &req_emptymsg;
+ alltypes.req_limits = &req_limits;
+
+ alltypes.rep_int32_count = 5; alltypes.rep_int32 = rep_int32;
+ alltypes.rep_int64_count = 5; alltypes.rep_int64 = rep_int64;
+ alltypes.rep_uint32_count = 5; alltypes.rep_uint32 = rep_uint32;
+ alltypes.rep_uint64_count = 5; alltypes.rep_uint64 = rep_uint64;
+ alltypes.rep_sint32_count = 5; alltypes.rep_sint32 = rep_sint32;
+ alltypes.rep_sint64_count = 5; alltypes.rep_sint64 = rep_sint64;
+ alltypes.rep_bool_count = 5; alltypes.rep_bool = rep_bool;
+ alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32 = rep_fixed32;
+ alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32 = rep_sfixed32;
+ alltypes.rep_float_count = 5; alltypes.rep_float = rep_float;
+ alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64 = rep_fixed64;
+ alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64 = rep_sfixed64;
+ alltypes.rep_double_count = 5; alltypes.rep_double = rep_double;
+ alltypes.rep_string_count = 5; alltypes.rep_string = rep_string;
+ alltypes.rep_bytes_count = 5; alltypes.rep_bytes = rep_bytes;
+ alltypes.rep_submsg_count = 5; alltypes.rep_submsg = rep_submsg;
+ alltypes.rep_enum_count = 5; alltypes.rep_enum = rep_enum;
+ alltypes.rep_emptymsg_count = 5; alltypes.rep_emptymsg = rep_emptymsg;
+
+ if (mode != 0)
+ {
+ /* Fill in values for optional fields */
+ alltypes.opt_int32 = &opt_int32;
+ alltypes.opt_int64 = &opt_int64;
+ alltypes.opt_uint32 = &opt_uint32;
+ alltypes.opt_uint64 = &opt_uint64;
+ alltypes.opt_sint32 = &opt_sint32;
+ alltypes.opt_sint64 = &opt_sint64;
+ alltypes.opt_bool = &opt_bool;
+ alltypes.opt_fixed32 = &opt_fixed32;
+ alltypes.opt_sfixed32 = &opt_sfixed32;
+ alltypes.opt_float = &opt_float;
+ alltypes.opt_fixed64 = &opt_fixed64;
+ alltypes.opt_sfixed64 = &opt_sfixed64;
+ alltypes.opt_double = &opt_double;
+ alltypes.opt_string = opt_string;
+ alltypes.opt_bytes = (pb_bytes_array_t*)&opt_bytes;
+ alltypes.opt_submsg = &opt_submsg;
+ alltypes.opt_enum = &opt_enum;
+ alltypes.opt_emptymsg = &opt_emptymsg;
+ }
+
+ alltypes.end = &end;
+
+ {
+ uint8_t buffer[4096];
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, AllTypes_fields, &alltypes))
+ {
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+ }
+}
diff --git a/tests/backwards_compatibility/SConscript b/tests/backwards_compatibility/SConscript
new file mode 100644
index 0000000..777ef40
--- /dev/null
+++ b/tests/backwards_compatibility/SConscript
@@ -0,0 +1,11 @@
+# Check that the old generated .pb.c/.pb.h files are still compatible with the
+# current version of nanopb.
+
+Import("env")
+
+enc = env.Program(["encode_legacy.c", "alltypes_legacy.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_legacy.c", "alltypes_legacy.c", "$COMMON/pb_decode.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_legacy.output"])
+
diff --git a/tests/backwards_compatibility/alltypes_legacy.c b/tests/backwards_compatibility/alltypes_legacy.c
new file mode 100644
index 0000000..9134d5e
--- /dev/null
+++ b/tests/backwards_compatibility/alltypes_legacy.c
@@ -0,0 +1,93 @@
+/* Automatically generated nanopb constant definitions */
+/* Generated by 0.2.0-dev at Sun Feb 17 00:09:53 2013. */
+/* This is a file generated using nanopb-0.2.0-dev.
+ * It is used as a part of test suite in order to detect any
+ * incompatible changes made to the generator in future versions.
+ */
+
+#include "alltypes_legacy.h"
+
+const char SubMessage_substuff1_default[16] = "1";
+const int32_t SubMessage_substuff2_default = 2;
+const uint32_t SubMessage_substuff3_default = 3;
+const int32_t AllTypes_opt_int32_default = 4041;
+const int64_t AllTypes_opt_int64_default = 4042;
+const uint32_t AllTypes_opt_uint32_default = 4043;
+const uint64_t AllTypes_opt_uint64_default = 4044;
+const int32_t AllTypes_opt_sint32_default = 4045;
+const int64_t AllTypes_opt_sint64_default = 4046;
+const bool AllTypes_opt_bool_default = false;
+const uint32_t AllTypes_opt_fixed32_default = 4048;
+const int32_t AllTypes_opt_sfixed32_default = 4049;
+const float AllTypes_opt_float_default = 4050;
+const uint64_t AllTypes_opt_fixed64_default = 4051;
+const int64_t AllTypes_opt_sfixed64_default = 4052;
+const double AllTypes_opt_double_default = 4053;
+const char AllTypes_opt_string_default[16] = "4054";
+const AllTypes_opt_bytes_t AllTypes_opt_bytes_default = {4, {0x34,0x30,0x35,0x35}};
+const MyEnum AllTypes_opt_enum_default = MyEnum_Second;
+
+
+const pb_field_t SubMessage_fields[4] = {
+ PB_FIELD( 1, STRING , REQUIRED, STATIC, SubMessage, substuff1, substuff1, &SubMessage_substuff1_default),
+ PB_FIELD( 2, INT32 , REQUIRED, STATIC, SubMessage, substuff2, substuff1, &SubMessage_substuff2_default),
+ PB_FIELD( 3, FIXED32 , OPTIONAL, STATIC, SubMessage, substuff3, substuff2, &SubMessage_substuff3_default),
+ PB_LAST_FIELD
+};
+
+const pb_field_t AllTypes_fields[53] = {
+ PB_FIELD( 1, INT32 , REQUIRED, STATIC, AllTypes, req_int32, req_int32, 0),
+ PB_FIELD( 2, INT64 , REQUIRED, STATIC, AllTypes, req_int64, req_int32, 0),
+ PB_FIELD( 3, UINT32 , REQUIRED, STATIC, AllTypes, req_uint32, req_int64, 0),
+ PB_FIELD( 4, UINT64 , REQUIRED, STATIC, AllTypes, req_uint64, req_uint32, 0),
+ PB_FIELD( 5, SINT32 , REQUIRED, STATIC, AllTypes, req_sint32, req_uint64, 0),
+ PB_FIELD( 6, SINT64 , REQUIRED, STATIC, AllTypes, req_sint64, req_sint32, 0),
+ PB_FIELD( 7, BOOL , REQUIRED, STATIC, AllTypes, req_bool, req_sint64, 0),
+ PB_FIELD( 8, FIXED32 , REQUIRED, STATIC, AllTypes, req_fixed32, req_bool, 0),
+ PB_FIELD( 9, SFIXED32, REQUIRED, STATIC, AllTypes, req_sfixed32, req_fixed32, 0),
+ PB_FIELD( 10, FLOAT , REQUIRED, STATIC, AllTypes, req_float, req_sfixed32, 0),
+ PB_FIELD( 11, FIXED64 , REQUIRED, STATIC, AllTypes, req_fixed64, req_float, 0),
+ PB_FIELD( 12, SFIXED64, REQUIRED, STATIC, AllTypes, req_sfixed64, req_fixed64, 0),
+ PB_FIELD( 13, DOUBLE , REQUIRED, STATIC, AllTypes, req_double, req_sfixed64, 0),
+ PB_FIELD( 14, STRING , REQUIRED, STATIC, AllTypes, req_string, req_double, 0),
+ PB_FIELD( 15, BYTES , REQUIRED, STATIC, AllTypes, req_bytes, req_string, 0),
+ PB_FIELD( 16, MESSAGE , REQUIRED, STATIC, AllTypes, req_submsg, req_bytes, &SubMessage_fields),
+ PB_FIELD( 17, ENUM , REQUIRED, STATIC, AllTypes, req_enum, req_submsg, 0),
+ PB_FIELD( 21, INT32 , REPEATED, STATIC, AllTypes, rep_int32, req_enum, 0),
+ PB_FIELD( 22, INT64 , REPEATED, STATIC, AllTypes, rep_int64, rep_int32, 0),
+ PB_FIELD( 23, UINT32 , REPEATED, STATIC, AllTypes, rep_uint32, rep_int64, 0),
+ PB_FIELD( 24, UINT64 , REPEATED, STATIC, AllTypes, rep_uint64, rep_uint32, 0),
+ PB_FIELD( 25, SINT32 , REPEATED, STATIC, AllTypes, rep_sint32, rep_uint64, 0),
+ PB_FIELD( 26, SINT64 , REPEATED, STATIC, AllTypes, rep_sint64, rep_sint32, 0),
+ PB_FIELD( 27, BOOL , REPEATED, STATIC, AllTypes, rep_bool, rep_sint64, 0),
+ PB_FIELD( 28, FIXED32 , REPEATED, STATIC, AllTypes, rep_fixed32, rep_bool, 0),
+ PB_FIELD( 29, SFIXED32, REPEATED, STATIC, AllTypes, rep_sfixed32, rep_fixed32, 0),
+ PB_FIELD( 30, FLOAT , REPEATED, STATIC, AllTypes, rep_float, rep_sfixed32, 0),
+ PB_FIELD( 31, FIXED64 , REPEATED, STATIC, AllTypes, rep_fixed64, rep_float, 0),
+ PB_FIELD( 32, SFIXED64, REPEATED, STATIC, AllTypes, rep_sfixed64, rep_fixed64, 0),
+ PB_FIELD( 33, DOUBLE , REPEATED, STATIC, AllTypes, rep_double, rep_sfixed64, 0),
+ PB_FIELD( 34, STRING , REPEATED, STATIC, AllTypes, rep_string, rep_double, 0),
+ PB_FIELD( 35, BYTES , REPEATED, STATIC, AllTypes, rep_bytes, rep_string, 0),
+ PB_FIELD( 36, MESSAGE , REPEATED, STATIC, AllTypes, rep_submsg, rep_bytes, &SubMessage_fields),
+ PB_FIELD( 37, ENUM , REPEATED, STATIC, AllTypes, rep_enum, rep_submsg, 0),
+ PB_FIELD( 41, INT32 , OPTIONAL, STATIC, AllTypes, opt_int32, rep_enum, &AllTypes_opt_int32_default),
+ PB_FIELD( 42, INT64 , OPTIONAL, STATIC, AllTypes, opt_int64, opt_int32, &AllTypes_opt_int64_default),
+ PB_FIELD( 43, UINT32 , OPTIONAL, STATIC, AllTypes, opt_uint32, opt_int64, &AllTypes_opt_uint32_default),
+ PB_FIELD( 44, UINT64 , OPTIONAL, STATIC, AllTypes, opt_uint64, opt_uint32, &AllTypes_opt_uint64_default),
+ PB_FIELD( 45, SINT32 , OPTIONAL, STATIC, AllTypes, opt_sint32, opt_uint64, &AllTypes_opt_sint32_default),
+ PB_FIELD( 46, SINT64 , OPTIONAL, STATIC, AllTypes, opt_sint64, opt_sint32, &AllTypes_opt_sint64_default),
+ PB_FIELD( 47, BOOL , OPTIONAL, STATIC, AllTypes, opt_bool, opt_sint64, &AllTypes_opt_bool_default),
+ PB_FIELD( 48, FIXED32 , OPTIONAL, STATIC, AllTypes, opt_fixed32, opt_bool, &AllTypes_opt_fixed32_default),
+ PB_FIELD( 49, SFIXED32, OPTIONAL, STATIC, AllTypes, opt_sfixed32, opt_fixed32, &AllTypes_opt_sfixed32_default),
+ PB_FIELD( 50, FLOAT , OPTIONAL, STATIC, AllTypes, opt_float, opt_sfixed32, &AllTypes_opt_float_default),
+ PB_FIELD( 51, FIXED64 , OPTIONAL, STATIC, AllTypes, opt_fixed64, opt_float, &AllTypes_opt_fixed64_default),
+ PB_FIELD( 52, SFIXED64, OPTIONAL, STATIC, AllTypes, opt_sfixed64, opt_fixed64, &AllTypes_opt_sfixed64_default),
+ PB_FIELD( 53, DOUBLE , OPTIONAL, STATIC, AllTypes, opt_double, opt_sfixed64, &AllTypes_opt_double_default),
+ PB_FIELD( 54, STRING , OPTIONAL, STATIC, AllTypes, opt_string, opt_double, &AllTypes_opt_string_default),
+ PB_FIELD( 55, BYTES , OPTIONAL, STATIC, AllTypes, opt_bytes, opt_string, &AllTypes_opt_bytes_default),
+ PB_FIELD( 56, MESSAGE , OPTIONAL, STATIC, AllTypes, opt_submsg, opt_bytes, &SubMessage_fields),
+ PB_FIELD( 57, ENUM , OPTIONAL, STATIC, AllTypes, opt_enum, opt_submsg, &AllTypes_opt_enum_default),
+ PB_FIELD( 99, INT32 , REQUIRED, STATIC, AllTypes, end, opt_enum, 0),
+ PB_LAST_FIELD
+};
+
diff --git a/tests/backwards_compatibility/alltypes_legacy.h b/tests/backwards_compatibility/alltypes_legacy.h
new file mode 100644
index 0000000..037b347
--- /dev/null
+++ b/tests/backwards_compatibility/alltypes_legacy.h
@@ -0,0 +1,178 @@
+/* Automatically generated nanopb header */
+/* This is a file generated using nanopb-0.2.0-dev.
+ * It is used as a part of test suite in order to detect any
+ * incompatible changes made to the generator in future versions.
+ */
+
+#ifndef _PB_ALLTYPES_PB_H_
+#define _PB_ALLTYPES_PB_H_
+#include <pb.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Enum definitions */
+typedef enum _MyEnum {
+ MyEnum_Zero = 0,
+ MyEnum_First = 1,
+ MyEnum_Second = 2,
+ MyEnum_Truth = 42
+} MyEnum;
+
+/* Struct definitions */
+typedef struct _SubMessage {
+ char substuff1[16];
+ int32_t substuff2;
+ bool has_substuff3;
+ uint32_t substuff3;
+} SubMessage;
+
+typedef struct {
+ size_t size;
+ uint8_t bytes[16];
+} AllTypes_req_bytes_t;
+
+typedef struct {
+ size_t size;
+ uint8_t bytes[16];
+} AllTypes_rep_bytes_t;
+
+typedef struct {
+ size_t size;
+ uint8_t bytes[16];
+} AllTypes_opt_bytes_t;
+
+typedef struct _AllTypes {
+ int32_t req_int32;
+ int64_t req_int64;
+ uint32_t req_uint32;
+ uint64_t req_uint64;
+ int32_t req_sint32;
+ int64_t req_sint64;
+ bool req_bool;
+ uint32_t req_fixed32;
+ int32_t req_sfixed32;
+ float req_float;
+ uint64_t req_fixed64;
+ int64_t req_sfixed64;
+ double req_double;
+ char req_string[16];
+ AllTypes_req_bytes_t req_bytes;
+ SubMessage req_submsg;
+ MyEnum req_enum;
+ size_t rep_int32_count;
+ int32_t rep_int32[5];
+ size_t rep_int64_count;
+ int64_t rep_int64[5];
+ size_t rep_uint32_count;
+ uint32_t rep_uint32[5];
+ size_t rep_uint64_count;
+ uint64_t rep_uint64[5];
+ size_t rep_sint32_count;
+ int32_t rep_sint32[5];
+ size_t rep_sint64_count;
+ int64_t rep_sint64[5];
+ size_t rep_bool_count;
+ bool rep_bool[5];
+ size_t rep_fixed32_count;
+ uint32_t rep_fixed32[5];
+ size_t rep_sfixed32_count;
+ int32_t rep_sfixed32[5];
+ size_t rep_float_count;
+ float rep_float[5];
+ size_t rep_fixed64_count;
+ uint64_t rep_fixed64[5];
+ size_t rep_sfixed64_count;
+ int64_t rep_sfixed64[5];
+ size_t rep_double_count;
+ double rep_double[5];
+ size_t rep_string_count;
+ char rep_string[5][16];
+ size_t rep_bytes_count;
+ AllTypes_rep_bytes_t rep_bytes[5];
+ size_t rep_submsg_count;
+ SubMessage rep_submsg[5];
+ size_t rep_enum_count;
+ MyEnum rep_enum[5];
+ bool has_opt_int32;
+ int32_t opt_int32;
+ bool has_opt_int64;
+ int64_t opt_int64;
+ bool has_opt_uint32;
+ uint32_t opt_uint32;
+ bool has_opt_uint64;
+ uint64_t opt_uint64;
+ bool has_opt_sint32;
+ int32_t opt_sint32;
+ bool has_opt_sint64;
+ int64_t opt_sint64;
+ bool has_opt_bool;
+ bool opt_bool;
+ bool has_opt_fixed32;
+ uint32_t opt_fixed32;
+ bool has_opt_sfixed32;
+ int32_t opt_sfixed32;
+ bool has_opt_float;
+ float opt_float;
+ bool has_opt_fixed64;
+ uint64_t opt_fixed64;
+ bool has_opt_sfixed64;
+ int64_t opt_sfixed64;
+ bool has_opt_double;
+ double opt_double;
+ bool has_opt_string;
+ char opt_string[16];
+ bool has_opt_bytes;
+ AllTypes_opt_bytes_t opt_bytes;
+ bool has_opt_submsg;
+ SubMessage opt_submsg;
+ bool has_opt_enum;
+ MyEnum opt_enum;
+ int32_t end;
+} AllTypes;
+
+/* Default values for struct fields */
+extern const char SubMessage_substuff1_default[16];
+extern const int32_t SubMessage_substuff2_default;
+extern const uint32_t SubMessage_substuff3_default;
+extern const int32_t AllTypes_opt_int32_default;
+extern const int64_t AllTypes_opt_int64_default;
+extern const uint32_t AllTypes_opt_uint32_default;
+extern const uint64_t AllTypes_opt_uint64_default;
+extern const int32_t AllTypes_opt_sint32_default;
+extern const int64_t AllTypes_opt_sint64_default;
+extern const bool AllTypes_opt_bool_default;
+extern const uint32_t AllTypes_opt_fixed32_default;
+extern const int32_t AllTypes_opt_sfixed32_default;
+extern const float AllTypes_opt_float_default;
+extern const uint64_t AllTypes_opt_fixed64_default;
+extern const int64_t AllTypes_opt_sfixed64_default;
+extern const double AllTypes_opt_double_default;
+extern const char AllTypes_opt_string_default[16];
+extern const AllTypes_opt_bytes_t AllTypes_opt_bytes_default;
+extern const MyEnum AllTypes_opt_enum_default;
+
+/* Struct field encoding specification for nanopb */
+extern const pb_field_t SubMessage_fields[4];
+extern const pb_field_t AllTypes_fields[53];
+
+/* Check that field information fits in pb_field_t */
+#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)
+STATIC_ASSERT((pb_membersize(AllTypes, req_submsg) < 256 && pb_membersize(AllTypes, rep_submsg[0]) < 256 && pb_membersize(AllTypes, opt_submsg) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_SubMessage_AllTypes)
+#endif
+
+#if !defined(PB_FIELD_32BIT)
+STATIC_ASSERT((pb_membersize(AllTypes, req_submsg) < 65536 && pb_membersize(AllTypes, rep_submsg[0]) < 65536 && pb_membersize(AllTypes, opt_submsg) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_SubMessage_AllTypes)
+#endif
+
+/* On some platforms (such as AVR), double is really float.
+ * These are not directly supported by nanopb, but see example_avr_double.
+ */
+STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+#endif
diff --git a/tests/backwards_compatibility/decode_legacy.c b/tests/backwards_compatibility/decode_legacy.c
new file mode 100644
index 0000000..9dfe437
--- /dev/null
+++ b/tests/backwards_compatibility/decode_legacy.c
@@ -0,0 +1,202 @@
+/* Tests the decoding of all types.
+ * This is a backwards-compatibility test, using alltypes_legacy.h.
+ * It is similar to decode_alltypes, but duplicated in order to allow
+ * decode_alltypes to test any new features introduced later.
+ *
+ * Run e.g. ./encode_legacy | ./decode_legacy
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <pb_decode.h>
+#include "alltypes_legacy.h"
+#include "test_helpers.h"
+
+#define TEST(x) if (!(x)) { \
+ printf("Test " #x " failed.\n"); \
+ return false; \
+ }
+
+/* This function is called once from main(), it handles
+ the decoding and checks the fields. */
+bool check_alltypes(pb_istream_t *stream, int mode)
+{
+ AllTypes alltypes;
+
+ /* Fill with garbage to better detect initialization errors */
+ memset(&alltypes, 0xAA, sizeof(alltypes));
+
+ if (!pb_decode(stream, AllTypes_fields, &alltypes))
+ return false;
+
+ TEST(alltypes.req_int32 == -1001);
+ TEST(alltypes.req_int64 == -1002);
+ TEST(alltypes.req_uint32 == 1003);
+ TEST(alltypes.req_uint64 == 1004);
+ TEST(alltypes.req_sint32 == -1005);
+ TEST(alltypes.req_sint64 == -1006);
+ TEST(alltypes.req_bool == true);
+
+ TEST(alltypes.req_fixed32 == 1008);
+ TEST(alltypes.req_sfixed32 == -1009);
+ TEST(alltypes.req_float == 1010.0f);
+
+ TEST(alltypes.req_fixed64 == 1011);
+ TEST(alltypes.req_sfixed64 == -1012);
+ TEST(alltypes.req_double == 1013.0f);
+
+ TEST(strcmp(alltypes.req_string, "1014") == 0);
+ TEST(alltypes.req_bytes.size == 4);
+ TEST(memcmp(alltypes.req_bytes.bytes, "1015", 4) == 0);
+ TEST(strcmp(alltypes.req_submsg.substuff1, "1016") == 0);
+ TEST(alltypes.req_submsg.substuff2 == 1016);
+ TEST(alltypes.req_submsg.substuff3 == 3);
+ TEST(alltypes.req_enum == MyEnum_Truth);
+
+ TEST(alltypes.rep_int32_count == 5 && alltypes.rep_int32[4] == -2001 && alltypes.rep_int32[0] == 0);
+ TEST(alltypes.rep_int64_count == 5 && alltypes.rep_int64[4] == -2002 && alltypes.rep_int64[0] == 0);
+ TEST(alltypes.rep_uint32_count == 5 && alltypes.rep_uint32[4] == 2003 && alltypes.rep_uint32[0] == 0);
+ TEST(alltypes.rep_uint64_count == 5 && alltypes.rep_uint64[4] == 2004 && alltypes.rep_uint64[0] == 0);
+ TEST(alltypes.rep_sint32_count == 5 && alltypes.rep_sint32[4] == -2005 && alltypes.rep_sint32[0] == 0);
+ TEST(alltypes.rep_sint64_count == 5 && alltypes.rep_sint64[4] == -2006 && alltypes.rep_sint64[0] == 0);
+ TEST(alltypes.rep_bool_count == 5 && alltypes.rep_bool[4] == true && alltypes.rep_bool[0] == false);
+
+ TEST(alltypes.rep_fixed32_count == 5 && alltypes.rep_fixed32[4] == 2008 && alltypes.rep_fixed32[0] == 0);
+ TEST(alltypes.rep_sfixed32_count == 5 && alltypes.rep_sfixed32[4] == -2009 && alltypes.rep_sfixed32[0] == 0);
+ TEST(alltypes.rep_float_count == 5 && alltypes.rep_float[4] == 2010.0f && alltypes.rep_float[0] == 0.0f);
+
+ TEST(alltypes.rep_fixed64_count == 5 && alltypes.rep_fixed64[4] == 2011 && alltypes.rep_fixed64[0] == 0);
+ TEST(alltypes.rep_sfixed64_count == 5 && alltypes.rep_sfixed64[4] == -2012 && alltypes.rep_sfixed64[0] == 0);
+ TEST(alltypes.rep_double_count == 5 && alltypes.rep_double[4] == 2013.0 && alltypes.rep_double[0] == 0.0);
+
+ TEST(alltypes.rep_string_count == 5 && strcmp(alltypes.rep_string[4], "2014") == 0 && alltypes.rep_string[0][0] == '\0');
+ TEST(alltypes.rep_bytes_count == 5 && alltypes.rep_bytes[4].size == 4 && alltypes.rep_bytes[0].size == 0);
+ TEST(memcmp(alltypes.rep_bytes[4].bytes, "2015", 4) == 0);
+
+ TEST(alltypes.rep_submsg_count == 5);
+ TEST(strcmp(alltypes.rep_submsg[4].substuff1, "2016") == 0 && alltypes.rep_submsg[0].substuff1[0] == '\0');
+ TEST(alltypes.rep_submsg[4].substuff2 == 2016 && alltypes.rep_submsg[0].substuff2 == 0);
+ TEST(alltypes.rep_submsg[4].substuff3 == 2016 && alltypes.rep_submsg[0].substuff3 == 3);
+
+ TEST(alltypes.rep_enum_count == 5 && alltypes.rep_enum[4] == MyEnum_Truth && alltypes.rep_enum[0] == MyEnum_Zero);
+
+ if (mode == 0)
+ {
+ /* Expect default values */
+ TEST(alltypes.has_opt_int32 == false);
+ TEST(alltypes.opt_int32 == 4041);
+ TEST(alltypes.has_opt_int64 == false);
+ TEST(alltypes.opt_int64 == 4042);
+ TEST(alltypes.has_opt_uint32 == false);
+ TEST(alltypes.opt_uint32 == 4043);
+ TEST(alltypes.has_opt_uint64 == false);
+ TEST(alltypes.opt_uint64 == 4044);
+ TEST(alltypes.has_opt_sint32 == false);
+ TEST(alltypes.opt_sint32 == 4045);
+ TEST(alltypes.has_opt_sint64 == false);
+ TEST(alltypes.opt_sint64 == 4046);
+ TEST(alltypes.has_opt_bool == false);
+ TEST(alltypes.opt_bool == false);
+
+ TEST(alltypes.has_opt_fixed32 == false);
+ TEST(alltypes.opt_fixed32 == 4048);
+ TEST(alltypes.has_opt_sfixed32 == false);
+ TEST(alltypes.opt_sfixed32 == 4049);
+ TEST(alltypes.has_opt_float == false);
+ TEST(alltypes.opt_float == 4050.0f);
+
+ TEST(alltypes.has_opt_fixed64 == false);
+ TEST(alltypes.opt_fixed64 == 4051);
+ TEST(alltypes.has_opt_sfixed64 == false);
+ TEST(alltypes.opt_sfixed64 == 4052);
+ TEST(alltypes.has_opt_double == false);
+ TEST(alltypes.opt_double == 4053.0);
+
+ TEST(alltypes.has_opt_string == false);
+ TEST(strcmp(alltypes.opt_string, "4054") == 0);
+ TEST(alltypes.has_opt_bytes == false);
+ TEST(alltypes.opt_bytes.size == 4);
+ TEST(memcmp(alltypes.opt_bytes.bytes, "4055", 4) == 0);
+ TEST(alltypes.has_opt_submsg == false);
+ TEST(strcmp(alltypes.opt_submsg.substuff1, "1") == 0);
+ TEST(alltypes.opt_submsg.substuff2 == 2);
+ TEST(alltypes.opt_submsg.substuff3 == 3);
+ TEST(alltypes.has_opt_enum == false);
+ TEST(alltypes.opt_enum == MyEnum_Second);
+ }
+ else
+ {
+ /* Expect filled-in values */
+ TEST(alltypes.has_opt_int32 == true);
+ TEST(alltypes.opt_int32 == 3041);
+ TEST(alltypes.has_opt_int64 == true);
+ TEST(alltypes.opt_int64 == 3042);
+ TEST(alltypes.has_opt_uint32 == true);
+ TEST(alltypes.opt_uint32 == 3043);
+ TEST(alltypes.has_opt_uint64 == true);
+ TEST(alltypes.opt_uint64 == 3044);
+ TEST(alltypes.has_opt_sint32 == true);
+ TEST(alltypes.opt_sint32 == 3045);
+ TEST(alltypes.has_opt_sint64 == true);
+ TEST(alltypes.opt_sint64 == 3046);
+ TEST(alltypes.has_opt_bool == true);
+ TEST(alltypes.opt_bool == true);
+
+ TEST(alltypes.has_opt_fixed32 == true);
+ TEST(alltypes.opt_fixed32 == 3048);
+ TEST(alltypes.has_opt_sfixed32 == true);
+ TEST(alltypes.opt_sfixed32 == 3049);
+ TEST(alltypes.has_opt_float == true);
+ TEST(alltypes.opt_float == 3050.0f);
+
+ TEST(alltypes.has_opt_fixed64 == true);
+ TEST(alltypes.opt_fixed64 == 3051);
+ TEST(alltypes.has_opt_sfixed64 == true);
+ TEST(alltypes.opt_sfixed64 == 3052);
+ TEST(alltypes.has_opt_double == true);
+ TEST(alltypes.opt_double == 3053.0);
+
+ TEST(alltypes.has_opt_string == true);
+ TEST(strcmp(alltypes.opt_string, "3054") == 0);
+ TEST(alltypes.has_opt_bytes == true);
+ TEST(alltypes.opt_bytes.size == 4);
+ TEST(memcmp(alltypes.opt_bytes.bytes, "3055", 4) == 0);
+ TEST(alltypes.has_opt_submsg == true);
+ TEST(strcmp(alltypes.opt_submsg.substuff1, "3056") == 0);
+ TEST(alltypes.opt_submsg.substuff2 == 3056);
+ TEST(alltypes.opt_submsg.substuff3 == 3);
+ TEST(alltypes.has_opt_enum == true);
+ TEST(alltypes.opt_enum == MyEnum_Truth);
+ }
+
+ TEST(alltypes.end == 1099);
+
+ return true;
+}
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ size_t count;
+ pb_istream_t stream;
+
+ /* Whether to expect the optional values or the default values. */
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Read the data into buffer */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+
+ /* Construct a pb_istream_t for reading from the buffer */
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Decode and print out the stuff */
+ if (!check_alltypes(&stream, mode))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ } else {
+ return 0;
+ }
+}
diff --git a/tests/backwards_compatibility/encode_legacy.c b/tests/backwards_compatibility/encode_legacy.c
new file mode 100644
index 0000000..5c9d41b
--- /dev/null
+++ b/tests/backwards_compatibility/encode_legacy.c
@@ -0,0 +1,135 @@
+/* Attempts to test all the datatypes supported by ProtoBuf.
+ * This is a backwards-compatibility test, using alltypes_legacy.h.
+ * It is similar to encode_alltypes, but duplicated in order to allow
+ * encode_alltypes to test any new features introduced later.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "alltypes_legacy.h"
+#include "test_helpers.h"
+
+int main(int argc, char **argv)
+{
+ int mode = (argc > 1) ? atoi(argv[1]) : 0;
+
+ /* Initialize the structure with constants */
+ AllTypes alltypes = {0};
+
+ alltypes.req_int32 = -1001;
+ alltypes.req_int64 = -1002;
+ alltypes.req_uint32 = 1003;
+ alltypes.req_uint64 = 1004;
+ alltypes.req_sint32 = -1005;
+ alltypes.req_sint64 = -1006;
+ alltypes.req_bool = true;
+
+ alltypes.req_fixed32 = 1008;
+ alltypes.req_sfixed32 = -1009;
+ alltypes.req_float = 1010.0f;
+
+ alltypes.req_fixed64 = 1011;
+ alltypes.req_sfixed64 = -1012;
+ alltypes.req_double = 1013.0;
+
+ strcpy(alltypes.req_string, "1014");
+ alltypes.req_bytes.size = 4;
+ memcpy(alltypes.req_bytes.bytes, "1015", 4);
+ strcpy(alltypes.req_submsg.substuff1, "1016");
+ alltypes.req_submsg.substuff2 = 1016;
+ alltypes.req_enum = MyEnum_Truth;
+
+ alltypes.rep_int32_count = 5; alltypes.rep_int32[4] = -2001;
+ alltypes.rep_int64_count = 5; alltypes.rep_int64[4] = -2002;
+ alltypes.rep_uint32_count = 5; alltypes.rep_uint32[4] = 2003;
+ alltypes.rep_uint64_count = 5; alltypes.rep_uint64[4] = 2004;
+ alltypes.rep_sint32_count = 5; alltypes.rep_sint32[4] = -2005;
+ alltypes.rep_sint64_count = 5; alltypes.rep_sint64[4] = -2006;
+ alltypes.rep_bool_count = 5; alltypes.rep_bool[4] = true;
+
+ alltypes.rep_fixed32_count = 5; alltypes.rep_fixed32[4] = 2008;
+ alltypes.rep_sfixed32_count = 5; alltypes.rep_sfixed32[4] = -2009;
+ alltypes.rep_float_count = 5; alltypes.rep_float[4] = 2010.0f;
+
+ alltypes.rep_fixed64_count = 5; alltypes.rep_fixed64[4] = 2011;
+ alltypes.rep_sfixed64_count = 5; alltypes.rep_sfixed64[4] = -2012;
+ alltypes.rep_double_count = 5; alltypes.rep_double[4] = 2013.0;
+
+ alltypes.rep_string_count = 5; strcpy(alltypes.rep_string[4], "2014");
+ alltypes.rep_bytes_count = 5; alltypes.rep_bytes[4].size = 4;
+ memcpy(alltypes.rep_bytes[4].bytes, "2015", 4);
+
+ alltypes.rep_submsg_count = 5;
+ strcpy(alltypes.rep_submsg[4].substuff1, "2016");
+ alltypes.rep_submsg[4].substuff2 = 2016;
+ alltypes.rep_submsg[4].has_substuff3 = true;
+ alltypes.rep_submsg[4].substuff3 = 2016;
+
+ alltypes.rep_enum_count = 5; alltypes.rep_enum[4] = MyEnum_Truth;
+
+ if (mode != 0)
+ {
+ /* Fill in values for optional fields */
+ alltypes.has_opt_int32 = true;
+ alltypes.opt_int32 = 3041;
+ alltypes.has_opt_int64 = true;
+ alltypes.opt_int64 = 3042;
+ alltypes.has_opt_uint32 = true;
+ alltypes.opt_uint32 = 3043;
+ alltypes.has_opt_uint64 = true;
+ alltypes.opt_uint64 = 3044;
+ alltypes.has_opt_sint32 = true;
+ alltypes.opt_sint32 = 3045;
+ alltypes.has_opt_sint64 = true;
+ alltypes.opt_sint64 = 3046;
+ alltypes.has_opt_bool = true;
+ alltypes.opt_bool = true;
+
+ alltypes.has_opt_fixed32 = true;
+ alltypes.opt_fixed32 = 3048;
+ alltypes.has_opt_sfixed32 = true;
+ alltypes.opt_sfixed32 = 3049;
+ alltypes.has_opt_float = true;
+ alltypes.opt_float = 3050.0f;
+
+ alltypes.has_opt_fixed64 = true;
+ alltypes.opt_fixed64 = 3051;
+ alltypes.has_opt_sfixed64 = true;
+ alltypes.opt_sfixed64 = 3052;
+ alltypes.has_opt_double = true;
+ alltypes.opt_double = 3053.0;
+
+ alltypes.has_opt_string = true;
+ strcpy(alltypes.opt_string, "3054");
+ alltypes.has_opt_bytes = true;
+ alltypes.opt_bytes.size = 4;
+ memcpy(alltypes.opt_bytes.bytes, "3055", 4);
+ alltypes.has_opt_submsg = true;
+ strcpy(alltypes.opt_submsg.substuff1, "3056");
+ alltypes.opt_submsg.substuff2 = 3056;
+ alltypes.has_opt_enum = true;
+ alltypes.opt_enum = MyEnum_Truth;
+ }
+
+ alltypes.end = 1099;
+
+ {
+ uint8_t buffer[1024];
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, AllTypes_fields, &alltypes))
+ {
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed!\n");
+ return 1; /* Failure */
+ }
+ }
+}
diff --git a/tests/basic_buffer/SConscript b/tests/basic_buffer/SConscript
new file mode 100644
index 0000000..2546aaa
--- /dev/null
+++ b/tests/basic_buffer/SConscript
@@ -0,0 +1,12 @@
+# Build and run a basic round-trip test using memory buffer encoding.
+
+Import("env")
+
+enc = env.Program(["encode_buffer.c", "$COMMON/person.pb.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_buffer.c", "$COMMON/person.pb.c", "$COMMON/pb_decode.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_buffer.output"])
+env.Decode(["encode_buffer.output", "$COMMON/person.proto"], MESSAGE = "Person")
+env.Compare(["decode_buffer.output", "encode_buffer.decoded"])
+
diff --git a/tests/basic_buffer/decode_buffer.c b/tests/basic_buffer/decode_buffer.c
new file mode 100644
index 0000000..fae9e2f
--- /dev/null
+++ b/tests/basic_buffer/decode_buffer.c
@@ -0,0 +1,88 @@
+/* A very simple decoding test case, using person.proto.
+ * Produces output compatible with protoc --decode.
+ * Reads the encoded data from stdin and prints the values
+ * to stdout as text.
+ *
+ * Run e.g. ./test_encode1 | ./test_decode1
+ */
+
+#include <stdio.h>
+#include <pb_decode.h>
+#include "person.pb.h"
+#include "test_helpers.h"
+
+/* This function is called once from main(), it handles
+ the decoding and printing. */
+bool print_person(pb_istream_t *stream)
+{
+ int i;
+ Person person;
+
+ if (!pb_decode(stream, Person_fields, &person))
+ return false;
+
+ /* Now the decoding is done, rest is just to print stuff out. */
+
+ printf("name: \"%s\"\n", person.name);
+ printf("id: %ld\n", (long)person.id);
+
+ if (person.has_email)
+ printf("email: \"%s\"\n", person.email);
+
+ for (i = 0; i < person.phone_count; i++)
+ {
+ Person_PhoneNumber *phone = &person.phone[i];
+ printf("phone {\n");
+ printf(" number: \"%s\"\n", phone->number);
+
+ if (phone->has_type)
+ {
+ switch (phone->type)
+ {
+ case Person_PhoneType_WORK:
+ printf(" type: WORK\n");
+ break;
+
+ case Person_PhoneType_HOME:
+ printf(" type: HOME\n");
+ break;
+
+ case Person_PhoneType_MOBILE:
+ printf(" type: MOBILE\n");
+ break;
+ }
+ }
+ printf("}\n");
+ }
+
+ return true;
+}
+
+int main()
+{
+ uint8_t buffer[Person_size];
+ pb_istream_t stream;
+ size_t count;
+
+ /* Read the data into buffer */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+
+ if (!feof(stdin))
+ {
+ printf("Message does not fit in buffer\n");
+ return 1;
+ }
+
+ /* Construct a pb_istream_t for reading from the buffer */
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Decode and print out the stuff */
+ if (!print_person(&stream))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ } else {
+ return 0;
+ }
+}
diff --git a/tests/basic_buffer/encode_buffer.c b/tests/basic_buffer/encode_buffer.c
new file mode 100644
index 0000000..c412c14
--- /dev/null
+++ b/tests/basic_buffer/encode_buffer.c
@@ -0,0 +1,38 @@
+/* A very simple encoding test case using person.proto.
+ * Just puts constant data in the fields and encodes into
+ * buffer, which is then written to stdout.
+ */
+
+#include <stdio.h>
+#include <pb_encode.h>
+#include "person.pb.h"
+#include "test_helpers.h"
+
+int main()
+{
+ uint8_t buffer[Person_size];
+ pb_ostream_t stream;
+
+ /* Initialize the structure with constants */
+ Person person = {"Test Person 99", 99, true, "test@person.com",
+ 3, {{"555-12345678", true, Person_PhoneType_MOBILE},
+ {"99-2342", false, 0},
+ {"1234-5678", true, Person_PhoneType_WORK},
+ }};
+
+ stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, Person_fields, &person))
+ {
+ /* Write the result data to stdout */
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+}
diff --git a/tests/basic_stream/SConscript b/tests/basic_stream/SConscript
new file mode 100644
index 0000000..46db8c4
--- /dev/null
+++ b/tests/basic_stream/SConscript
@@ -0,0 +1,12 @@
+# Build and run a basic round-trip test using direct stream encoding.
+
+Import("env")
+
+enc = env.Program(["encode_stream.c", "$COMMON/person.pb.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_stream.c", "$COMMON/person.pb.c", "$COMMON/pb_decode.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_stream.output"])
+env.Decode(["encode_stream.output", "$COMMON/person.proto"], MESSAGE = "Person")
+env.Compare(["decode_stream.output", "encode_stream.decoded"])
+
diff --git a/tests/basic_stream/decode_stream.c b/tests/basic_stream/decode_stream.c
new file mode 100644
index 0000000..667bf3c
--- /dev/null
+++ b/tests/basic_stream/decode_stream.c
@@ -0,0 +1,84 @@
+/* Same as test_decode1 but reads from stdin directly.
+ */
+
+#include <stdio.h>
+#include <pb_decode.h>
+#include "person.pb.h"
+#include "test_helpers.h"
+
+/* This function is called once from main(), it handles
+ the decoding and printing.
+ Ugly copy-paste from test_decode1.c. */
+bool print_person(pb_istream_t *stream)
+{
+ int i;
+ Person person;
+
+ if (!pb_decode(stream, Person_fields, &person))
+ return false;
+
+ /* Now the decoding is done, rest is just to print stuff out. */
+
+ printf("name: \"%s\"\n", person.name);
+ printf("id: %ld\n", (long)person.id);
+
+ if (person.has_email)
+ printf("email: \"%s\"\n", person.email);
+
+ for (i = 0; i < person.phone_count; i++)
+ {
+ Person_PhoneNumber *phone = &person.phone[i];
+ printf("phone {\n");
+ printf(" number: \"%s\"\n", phone->number);
+
+ if (phone->has_type)
+ {
+ switch (phone->type)
+ {
+ case Person_PhoneType_WORK:
+ printf(" type: WORK\n");
+ break;
+
+ case Person_PhoneType_HOME:
+ printf(" type: HOME\n");
+ break;
+
+ case Person_PhoneType_MOBILE:
+ printf(" type: MOBILE\n");
+ break;
+ }
+ }
+ printf("}\n");
+ }
+
+ return true;
+}
+
+/* This binds the pb_istream_t to stdin */
+bool callback(pb_istream_t *stream, uint8_t *buf, size_t count)
+{
+ FILE *file = (FILE*)stream->state;
+ bool status;
+
+ status = (fread(buf, 1, count, file) == count);
+
+ if (feof(file))
+ stream->bytes_left = 0;
+
+ return status;
+}
+
+int main()
+{
+ pb_istream_t stream = {&callback, NULL, SIZE_MAX};
+ stream.state = stdin;
+ SET_BINARY_MODE(stdin);
+
+ if (!print_person(&stream))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ } else {
+ return 0;
+ }
+}
diff --git a/tests/basic_stream/encode_stream.c b/tests/basic_stream/encode_stream.c
new file mode 100644
index 0000000..7f571c4
--- /dev/null
+++ b/tests/basic_stream/encode_stream.c
@@ -0,0 +1,40 @@
+/* Same as test_encode1.c, except writes directly to stdout.
+ */
+
+#include <stdio.h>
+#include <pb_encode.h>
+#include "person.pb.h"
+#include "test_helpers.h"
+
+/* This binds the pb_ostream_t into the stdout stream */
+bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
+{
+ FILE *file = (FILE*) stream->state;
+ return fwrite(buf, 1, count, file) == count;
+}
+
+int main()
+{
+ /* Initialize the structure with constants */
+ Person person = {"Test Person 99", 99, true, "test@person.com",
+ 3, {{"555-12345678", true, Person_PhoneType_MOBILE},
+ {"99-2342", false, 0},
+ {"1234-5678", true, Person_PhoneType_WORK},
+ }};
+
+ /* Prepare the stream, output goes directly to stdout */
+ pb_ostream_t stream = {&streamcallback, NULL, SIZE_MAX, 0};
+ stream.state = stdout;
+ SET_BINARY_MODE(stdout);
+
+ /* Now encode it and check if we succeeded. */
+ if (pb_encode(&stream, Person_fields, &person))
+ {
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+}
diff --git a/tests/buffer_only/SConscript b/tests/buffer_only/SConscript
new file mode 100644
index 0000000..cddbb04
--- /dev/null
+++ b/tests/buffer_only/SConscript
@@ -0,0 +1,27 @@
+# Run the alltypes test case, but compile with PB_BUFFER_ONLY=1
+
+Import("env")
+
+# Take copy of the files for custom build.
+c = Copy("$TARGET", "$SOURCE")
+env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c)
+env.Command("alltypes.pb.c", "$BUILD/alltypes/alltypes.pb.c", c)
+env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c)
+env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c)
+
+# Define the compilation options
+opts = env.Clone()
+opts.Append(CPPDEFINES = {'PB_BUFFER_ONLY': 1})
+
+# Build new version of core
+strict = opts.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode_bufonly.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode_bufonly.o", "$NANOPB/pb_encode.c")
+
+# Now build and run the test normally.
+enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_bufonly.o"])
+dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_bufonly.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
diff --git a/tests/callbacks/SConscript b/tests/callbacks/SConscript
new file mode 100644
index 0000000..9ec8a43
--- /dev/null
+++ b/tests/callbacks/SConscript
@@ -0,0 +1,14 @@
+# Test the functionality of the callback fields.
+
+Import("env")
+
+env.NanopbProto("callbacks")
+enc = env.Program(["encode_callbacks.c", "callbacks.pb.c", "$COMMON/pb_encode.o"])
+dec = env.Program(["decode_callbacks.c", "callbacks.pb.c", "$COMMON/pb_decode.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_callbacks.output"])
+
+env.Decode(["encode_callbacks.output", "callbacks.proto"], MESSAGE = "TestMessage")
+env.Compare(["decode_callbacks.output", "encode_callbacks.decoded"])
+
diff --git a/tests/callbacks/callbacks.proto b/tests/callbacks/callbacks.proto
new file mode 100644
index 0000000..ccd1edd
--- /dev/null
+++ b/tests/callbacks/callbacks.proto
@@ -0,0 +1,16 @@
+message SubMessage {
+ optional string stringvalue = 1;
+ repeated int32 int32value = 2;
+ repeated fixed32 fixed32value = 3;
+ repeated fixed64 fixed64value = 4;
+}
+
+message TestMessage {
+ optional string stringvalue = 1;
+ repeated int32 int32value = 2;
+ repeated fixed32 fixed32value = 3;
+ repeated fixed64 fixed64value = 4;
+ optional SubMessage submsg = 5;
+ repeated string repeatedstring = 6;
+}
+
diff --git a/tests/callbacks/decode_callbacks.c b/tests/callbacks/decode_callbacks.c
new file mode 100644
index 0000000..45724d0
--- /dev/null
+++ b/tests/callbacks/decode_callbacks.c
@@ -0,0 +1,97 @@
+/* Decoding testcase for callback fields.
+ * Run e.g. ./test_encode_callbacks | ./test_decode_callbacks
+ */
+
+#include <stdio.h>
+#include <pb_decode.h>
+#include "callbacks.pb.h"
+#include "test_helpers.h"
+
+bool print_string(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint8_t buffer[1024] = {0};
+
+ /* We could read block-by-block to avoid the large buffer... */
+ if (stream->bytes_left > sizeof(buffer) - 1)
+ return false;
+
+ if (!pb_read(stream, buffer, stream->bytes_left))
+ return false;
+
+ /* Print the string, in format comparable with protoc --decode.
+ * Format comes from the arg defined in main().
+ */
+ printf((char*)*arg, buffer);
+ return true;
+}
+
+bool print_int32(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint64_t value;
+ if (!pb_decode_varint(stream, &value))
+ return false;
+
+ printf((char*)*arg, (long)value);
+ return true;
+}
+
+bool print_fixed32(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint32_t value;
+ if (!pb_decode_fixed32(stream, &value))
+ return false;
+
+ printf((char*)*arg, (long)value);
+ return true;
+}
+
+bool print_fixed64(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ uint64_t value;
+ if (!pb_decode_fixed64(stream, &value))
+ return false;
+
+ printf((char*)*arg, (long)value);
+ return true;
+}
+
+int main()
+{
+ uint8_t buffer[1024];
+ size_t length;
+ pb_istream_t stream;
+ /* Note: empty initializer list initializes the struct with all-0.
+ * This is recommended so that unused callbacks are set to NULL instead
+ * of crashing at runtime.
+ */
+ TestMessage testmessage = {{{NULL}}};
+
+ SET_BINARY_MODE(stdin);
+ length = fread(buffer, 1, 1024, stdin);
+ stream = pb_istream_from_buffer(buffer, length);
+
+ testmessage.submsg.stringvalue.funcs.decode = &print_string;
+ testmessage.submsg.stringvalue.arg = "submsg {\n stringvalue: \"%s\"\n";
+ testmessage.submsg.int32value.funcs.decode = &print_int32;
+ testmessage.submsg.int32value.arg = " int32value: %ld\n";
+ testmessage.submsg.fixed32value.funcs.decode = &print_fixed32;
+ testmessage.submsg.fixed32value.arg = " fixed32value: %ld\n";
+ testmessage.submsg.fixed64value.funcs.decode = &print_fixed64;
+ testmessage.submsg.fixed64value.arg = " fixed64value: %ld\n}\n";
+
+ testmessage.stringvalue.funcs.decode = &print_string;
+ testmessage.stringvalue.arg = "stringvalue: \"%s\"\n";
+ testmessage.int32value.funcs.decode = &print_int32;
+ testmessage.int32value.arg = "int32value: %ld\n";
+ testmessage.fixed32value.funcs.decode = &print_fixed32;
+ testmessage.fixed32value.arg = "fixed32value: %ld\n";
+ testmessage.fixed64value.funcs.decode = &print_fixed64;
+ testmessage.fixed64value.arg = "fixed64value: %ld\n";
+ testmessage.repeatedstring.funcs.decode = &print_string;
+ testmessage.repeatedstring.arg = "repeatedstring: \"%s\"\n";
+
+ if (!pb_decode(&stream, TestMessage_fields, &testmessage))
+ return 1;
+
+ return 0;
+}
diff --git a/tests/callbacks/encode_callbacks.c b/tests/callbacks/encode_callbacks.c
new file mode 100644
index 0000000..6cb67b1
--- /dev/null
+++ b/tests/callbacks/encode_callbacks.c
@@ -0,0 +1,92 @@
+/* Encoding testcase for callback fields */
+
+#include <stdio.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "callbacks.pb.h"
+#include "test_helpers.h"
+
+bool encode_string(pb_ostream_t *stream, const pb_field_t *field, void * const *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, void * const *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, void * const *arg)
+{
+ uint32_t value = 42;
+
+ if (!pb_encode_tag_for_field(stream, field))
+ return false;
+
+ return pb_encode_fixed32(stream, &value);
+}
+
+bool encode_fixed64(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ uint64_t value = 42;
+
+ if (!pb_encode_tag_for_field(stream, field))
+ return false;
+
+ return pb_encode_fixed64(stream, &value);
+}
+
+bool encode_repeatedstring(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ char *str[4] = {"Hello world!", "", "Test", "Test2"};
+ int i;
+
+ for (i = 0; i < 4; i++)
+ {
+ if (!pb_encode_tag_for_field(stream, field))
+ return false;
+
+ if (!pb_encode_string(stream, (uint8_t*)str[i], strlen(str[i])))
+ return false;
+ }
+ return true;
+}
+
+int main()
+{
+ uint8_t buffer[1024];
+ pb_ostream_t stream;
+ TestMessage testmessage = {{{NULL}}};
+
+ stream = pb_ostream_from_buffer(buffer, 1024);
+
+ 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;
+
+ testmessage.repeatedstring.funcs.encode = &encode_repeatedstring;
+
+ if (!pb_encode(&stream, TestMessage_fields, &testmessage))
+ return 1;
+
+ SET_BINARY_MODE(stdout);
+ if (fwrite(buffer, stream.bytes_written, 1, stdout) != 1)
+ return 2;
+
+ return 0;
+}
diff --git a/tests/common/SConscript b/tests/common/SConscript
new file mode 100644
index 0000000..144f149
--- /dev/null
+++ b/tests/common/SConscript
@@ -0,0 +1,17 @@
+# Build the common files needed by multiple test cases
+
+Import('env')
+
+# Protocol definitions for the encode/decode_unittests
+env.NanopbProto("unittestproto")
+
+# Protocol definitions for basic_buffer/stream tests
+env.NanopbProto("person")
+
+# Binaries of the pb_decode.c and pb_encode.c
+# These are built using more strict warning flags.
+strict = env.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode.o", "$NANOPB/pb_encode.c")
+
diff --git a/tests/common/person.proto b/tests/common/person.proto
new file mode 100644
index 0000000..dafcf93
--- /dev/null
+++ b/tests/common/person.proto
@@ -0,0 +1,20 @@
+import "nanopb.proto";
+
+message Person {
+ required string name = 1 [(nanopb).max_size = 40];
+ required int32 id = 2;
+ optional string email = 3 [(nanopb).max_size = 40];
+
+ enum PhoneType {
+ MOBILE = 0;
+ HOME = 1;
+ WORK = 2;
+ }
+
+ message PhoneNumber {
+ required string number = 1 [(nanopb).max_size = 40];
+ optional PhoneType type = 2 [default = HOME];
+ }
+
+ repeated PhoneNumber phone = 4 [(nanopb).max_count = 5];
+}
diff --git a/tests/common/test_helpers.h b/tests/common/test_helpers.h
new file mode 100644
index 0000000..f77760a
--- /dev/null
+++ b/tests/common/test_helpers.h
@@ -0,0 +1,17 @@
+/* Compatibility helpers for the test programs. */
+
+#ifndef _TEST_HELPERS_H_
+#define _TEST_HELPERS_H_
+
+#ifdef _WIN32
+#include <io.h>
+#include <fcntl.h>
+#define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
+
+#else
+#define SET_BINARY_MODE(file)
+
+#endif
+
+
+#endif
diff --git a/tests/common/unittestproto.proto b/tests/common/unittestproto.proto
new file mode 100644
index 0000000..eb3e7de
--- /dev/null
+++ b/tests/common/unittestproto.proto
@@ -0,0 +1,36 @@
+import 'nanopb.proto';
+
+message IntegerArray {
+ repeated int32 data = 1 [(nanopb).max_count = 10];
+}
+
+message FloatArray {
+ repeated float data = 1 [(nanopb).max_count = 10];
+}
+
+message StringMessage {
+ required string data = 1 [(nanopb).max_size = 10];
+}
+
+message BytesMessage {
+ required bytes data = 1 [(nanopb).max_size = 16];
+}
+
+message CallbackArray {
+ // We cheat a bit and use this message for testing other types, too.
+ // Nanopb does not care about the actual defined data type for callback
+ // fields.
+ repeated int32 data = 1;
+}
+
+message IntegerContainer {
+ required IntegerArray submsg = 1;
+}
+
+message CallbackContainer {
+ required CallbackArray submsg = 1;
+}
+
+message CallbackContainerContainer {
+ required CallbackContainer submsg = 1;
+}
diff --git a/tests/common/unittests.h b/tests/common/unittests.h
new file mode 100644
index 0000000..c2b470a
--- /dev/null
+++ b/tests/common/unittests.h
@@ -0,0 +1,14 @@
+#include <stdio.h>
+
+#define COMMENT(x) printf("\n----" x "----\n");
+#define STR(x) #x
+#define STR2(x) STR(x)
+#define TEST(x) \
+ if (!(x)) { \
+ fprintf(stderr, "\033[31;1mFAILED:\033[22;39m " __FILE__ ":" STR2(__LINE__) " " #x "\n"); \
+ status = 1; \
+ } else { \
+ printf("\033[32;1mOK:\033[22;39m " #x "\n"); \
+ }
+
+
diff --git a/tests/cxx_main_program/SConscript b/tests/cxx_main_program/SConscript
new file mode 100644
index 0000000..e78c6b3
--- /dev/null
+++ b/tests/cxx_main_program/SConscript
@@ -0,0 +1,24 @@
+# Run the alltypes test case, but compile it as C++ instead.
+# In fact, compile the entire nanopb using C++ compiler.
+
+Import("env")
+
+# This is needed to get INT32_MIN etc. macros defined
+env = env.Clone()
+env.Append(CPPDEFINES = ['__STDC_LIMIT_MACROS'])
+
+# Copy the files to .cxx extension in order to force C++ build.
+c = Copy("$TARGET", "$SOURCE")
+env.Command("pb_encode.cxx", "#../pb_encode.c", c)
+env.Command("pb_decode.cxx", "#../pb_decode.c", c)
+env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c)
+env.Command("alltypes.pb.cxx", "$BUILD/alltypes/alltypes.pb.c", c)
+env.Command("encode_alltypes.cxx", "$BUILD/alltypes/encode_alltypes.c", c)
+env.Command("decode_alltypes.cxx", "$BUILD/alltypes/decode_alltypes.c", c)
+
+# Now build and run the test normally.
+enc = env.Program(["encode_alltypes.cxx", "alltypes.pb.cxx", "pb_encode.cxx"])
+dec = env.Program(["decode_alltypes.cxx", "alltypes.pb.cxx", "pb_decode.cxx"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
diff --git a/tests/decode_unittests/SConscript b/tests/decode_unittests/SConscript
new file mode 100644
index 0000000..369b9dc
--- /dev/null
+++ b/tests/decode_unittests/SConscript
@@ -0,0 +1,4 @@
+Import('env')
+p = env.Program(["decode_unittests.c", "$COMMON/unittestproto.pb.c"])
+env.RunTest(p)
+
diff --git a/tests/decode_unittests/decode_unittests.c b/tests/decode_unittests/decode_unittests.c
new file mode 100644
index 0000000..1be0191
--- /dev/null
+++ b/tests/decode_unittests/decode_unittests.c
@@ -0,0 +1,306 @@
+/* This includes the whole .c file to get access to static functions. */
+#include "pb_decode.c"
+
+#include <stdio.h>
+#include <string.h>
+#include "unittests.h"
+#include "unittestproto.pb.h"
+
+#define S(x) pb_istream_from_buffer((uint8_t*)x, sizeof(x) - 1)
+
+bool stream_callback(pb_istream_t *stream, uint8_t *buf, size_t count)
+{
+ if (stream->state != NULL)
+ return false; /* Simulate error */
+
+ if (buf != NULL)
+ memset(buf, 'x', count);
+ return true;
+}
+
+/* Verifies that the stream passed to callback matches the byte array pointed to by arg. */
+bool callback_check(pb_istream_t *stream, const pb_field_t *field, void **arg)
+{
+ int i;
+ uint8_t byte;
+ pb_bytes_array_t *ref = (pb_bytes_array_t*) *arg;
+
+ for (i = 0; i < ref->size; i++)
+ {
+ if (!pb_read(stream, &byte, 1))
+ return false;
+
+ if (byte != ref->bytes[i])
+ return false;
+ }
+
+ return true;
+}
+
+int main()
+{
+ int status = 0;
+
+ {
+ uint8_t buffer1[] = "foobartest1234";
+ uint8_t buffer2[sizeof(buffer1)];
+ pb_istream_t stream = pb_istream_from_buffer(buffer1, sizeof(buffer1));
+
+ COMMENT("Test pb_read and pb_istream_t");
+ TEST(pb_read(&stream, buffer2, 6))
+ TEST(memcmp(buffer2, "foobar", 6) == 0)
+ TEST(stream.bytes_left == sizeof(buffer1) - 6)
+ TEST(pb_read(&stream, buffer2 + 6, stream.bytes_left))
+ TEST(memcmp(buffer1, buffer2, sizeof(buffer1)) == 0)
+ TEST(stream.bytes_left == 0)
+ TEST(!pb_read(&stream, buffer2, 1))
+ }
+
+ {
+ uint8_t buffer[20];
+ pb_istream_t stream = {&stream_callback, NULL, 20};
+
+ COMMENT("Test pb_read with custom callback");
+ TEST(pb_read(&stream, buffer, 5))
+ TEST(memcmp(buffer, "xxxxx", 5) == 0)
+ TEST(!pb_read(&stream, buffer, 50))
+ stream.state = (void*)1; /* Simulated error return from callback */
+ TEST(!pb_read(&stream, buffer, 5))
+ stream.state = NULL;
+ TEST(pb_read(&stream, buffer, 15))
+ }
+
+ {
+ pb_istream_t s;
+ uint64_t u;
+ int64_t i;
+
+ COMMENT("Test pb_decode_varint");
+ TEST((s = S("\x00"), pb_decode_varint(&s, &u) && u == 0));
+ TEST((s = S("\x01"), pb_decode_varint(&s, &u) && u == 1));
+ TEST((s = S("\xAC\x02"), pb_decode_varint(&s, &u) && u == 300));
+ TEST((s = S("\xFF\xFF\xFF\xFF\x0F"), pb_decode_varint(&s, &u) && u == UINT32_MAX));
+ TEST((s = S("\xFF\xFF\xFF\xFF\x0F"), pb_decode_varint(&s, (uint64_t*)&i) && i == UINT32_MAX));
+ TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"),
+ pb_decode_varint(&s, (uint64_t*)&i) && i == -1));
+ TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"),
+ pb_decode_varint(&s, &u) && u == UINT64_MAX));
+ }
+
+ {
+ pb_istream_t s;
+ COMMENT("Test pb_skip_varint");
+ TEST((s = S("\x00""foobar"), pb_skip_varint(&s) && s.bytes_left == 6))
+ TEST((s = S("\xAC\x02""foobar"), pb_skip_varint(&s) && s.bytes_left == 6))
+ TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01""foobar"),
+ pb_skip_varint(&s) && s.bytes_left == 6))
+ TEST((s = S("\xFF"), !pb_skip_varint(&s)))
+ }
+
+ {
+ pb_istream_t s;
+ COMMENT("Test pb_skip_string")
+ TEST((s = S("\x00""foobar"), pb_skip_string(&s) && s.bytes_left == 6))
+ TEST((s = S("\x04""testfoobar"), pb_skip_string(&s) && s.bytes_left == 6))
+ TEST((s = S("\x04"), !pb_skip_string(&s)))
+ TEST((s = S("\xFF"), !pb_skip_string(&s)))
+ }
+
+ {
+ pb_istream_t s = S("\x01\xFF\xFF\x03");
+ pb_field_t f = {1, PB_LTYPE_VARINT, 0, 0, 4, 0, 0};
+ uint32_t d;
+ COMMENT("Test pb_dec_varint using uint32_t")
+ TEST(pb_dec_varint(&s, &f, &d) && d == 1)
+
+ /* Verify that no more than data_size is written. */
+ d = 0;
+ f.data_size = 1;
+ TEST(pb_dec_varint(&s, &f, &d) && (d == 0xFF || d == 0xFF000000))
+ }
+
+ {
+ pb_istream_t s;
+ pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 4, 0, 0};
+ int32_t d;
+
+ COMMENT("Test pb_dec_svarint using int32_t")
+ TEST((s = S("\x01"), pb_dec_svarint(&s, &f, &d) && d == -1))
+ TEST((s = S("\x02"), pb_dec_svarint(&s, &f, &d) && d == 1))
+ TEST((s = S("\xfe\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d) && d == INT32_MAX))
+ TEST((s = S("\xff\xff\xff\xff\x0f"), pb_dec_svarint(&s, &f, &d) && d == INT32_MIN))
+ }
+
+ {
+ pb_istream_t s;
+ pb_field_t f = {1, PB_LTYPE_SVARINT, 0, 0, 8, 0, 0};
+ uint64_t d;
+
+ COMMENT("Test pb_dec_svarint using uint64_t")
+ TEST((s = S("\x01"), pb_dec_svarint(&s, &f, &d) && d == -1))
+ TEST((s = S("\x02"), pb_dec_svarint(&s, &f, &d) && d == 1))
+ TEST((s = S("\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), pb_dec_svarint(&s, &f, &d) && d == INT64_MAX))
+ TEST((s = S("\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"), pb_dec_svarint(&s, &f, &d) && d == INT64_MIN))
+ }
+
+ {
+ pb_istream_t s;
+ pb_field_t f = {1, PB_LTYPE_FIXED32, 0, 0, 4, 0, 0};
+ float d;
+
+ COMMENT("Test pb_dec_fixed32 using float (failures here may be caused by imperfect rounding)")
+ TEST((s = S("\x00\x00\x00\x00"), pb_dec_fixed32(&s, &f, &d) && d == 0.0f))
+ TEST((s = S("\x00\x00\xc6\x42"), pb_dec_fixed32(&s, &f, &d) && d == 99.0f))
+ TEST((s = S("\x4e\x61\x3c\xcb"), pb_dec_fixed32(&s, &f, &d) && d == -12345678.0f))
+ TEST((s = S("\x00"), !pb_dec_fixed32(&s, &f, &d) && d == -12345678.0f))
+ }
+
+ {
+ pb_istream_t s;
+ pb_field_t f = {1, PB_LTYPE_FIXED64, 0, 0, 8, 0, 0};
+ double d;
+
+ COMMENT("Test pb_dec_fixed64 using double (failures here may be caused by imperfect rounding)")
+ TEST((s = S("\x00\x00\x00\x00\x00\x00\x00\x00"), pb_dec_fixed64(&s, &f, &d) && d == 0.0))
+ TEST((s = S("\x00\x00\x00\x00\x00\xc0\x58\x40"), pb_dec_fixed64(&s, &f, &d) && d == 99.0))
+ TEST((s = S("\x00\x00\x00\xc0\x29\x8c\x67\xc1"), pb_dec_fixed64(&s, &f, &d) && d == -12345678.0f))
+ }
+
+ {
+ pb_istream_t s;
+ struct { size_t size; uint8_t bytes[5]; } d;
+ pb_field_t f = {1, PB_LTYPE_BYTES, 0, 0, sizeof(d), 0, 0};
+
+ COMMENT("Test pb_dec_bytes")
+ TEST((s = S("\x00"), pb_dec_bytes(&s, &f, &d) && d.size == 0))
+ TEST((s = S("\x01\xFF"), pb_dec_bytes(&s, &f, &d) && d.size == 1 && d.bytes[0] == 0xFF))
+ TEST((s = S("\x05xxxxx"), pb_dec_bytes(&s, &f, &d) && d.size == 5))
+ TEST((s = S("\x05xxxx"), !pb_dec_bytes(&s, &f, &d)))
+
+ /* Note: the size limit on bytes-fields is not strictly obeyed, as
+ * the compiler may add some padding to the struct. Using this padding
+ * is not a very good thing to do, but it is difficult to avoid when
+ * we use only a single uint8_t to store the size of the field.
+ * Therefore this tests against a 10-byte string, while otherwise even
+ * 6 bytes should error out.
+ */
+ TEST((s = S("\x10xxxxxxxxxx"), !pb_dec_bytes(&s, &f, &d)))
+ }
+
+ {
+ pb_istream_t s;
+ pb_field_t f = {1, PB_LTYPE_STRING, 0, 0, 5, 0, 0};
+ char d[5];
+
+ COMMENT("Test pb_dec_string")
+ TEST((s = S("\x00"), pb_dec_string(&s, &f, &d) && d[0] == '\0'))
+ TEST((s = S("\x04xyzz"), pb_dec_string(&s, &f, &d) && strcmp(d, "xyzz") == 0))
+ TEST((s = S("\x05xyzzy"), !pb_dec_string(&s, &f, &d)))
+ }
+
+ {
+ pb_istream_t s;
+ IntegerArray dest;
+
+ COMMENT("Testing pb_decode with repeated int32 field")
+ TEST((s = S(""), pb_decode(&s, IntegerArray_fields, &dest) && dest.data_count == 0))
+ TEST((s = S("\x08\x01\x08\x02"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 2 && dest.data[0] == 1 && dest.data[1] == 2))
+ s = S("\x08\x01\x08\x02\x08\x03\x08\x04\x08\x05\x08\x06\x08\x07\x08\x08\x08\x09\x08\x0A");
+ TEST(pb_decode(&s, IntegerArray_fields, &dest) && dest.data_count == 10 && dest.data[9] == 10)
+ s = S("\x08\x01\x08\x02\x08\x03\x08\x04\x08\x05\x08\x06\x08\x07\x08\x08\x08\x09\x08\x0A\x08\x0B");
+ TEST(!pb_decode(&s, IntegerArray_fields, &dest))
+ }
+
+ {
+ pb_istream_t s;
+ IntegerArray dest;
+
+ COMMENT("Testing pb_decode with packed int32 field")
+ TEST((s = S("\x0A\x00"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 0))
+ TEST((s = S("\x0A\x01\x01"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 1 && dest.data[0] == 1))
+ TEST((s = S("\x0A\x0A\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 10 && dest.data[0] == 1 && dest.data[9] == 10))
+ TEST((s = S("\x0A\x0B\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B"), !pb_decode(&s, IntegerArray_fields, &dest)))
+
+ /* Test invalid wire data */
+ TEST((s = S("\x0A\xFF"), !pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x0A\x01"), !pb_decode(&s, IntegerArray_fields, &dest)))
+ }
+
+ {
+ pb_istream_t s;
+ IntegerArray dest;
+
+ COMMENT("Testing pb_decode with unknown fields")
+ TEST((s = S("\x18\x0F\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 1 && dest.data[0] == 1))
+ TEST((s = S("\x19\x00\x00\x00\x00\x00\x00\x00\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 1 && dest.data[0] == 1))
+ TEST((s = S("\x1A\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 1 && dest.data[0] == 1))
+ TEST((s = S("\x1B\x08\x01"), !pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x1D\x00\x00\x00\x00\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest)
+ && dest.data_count == 1 && dest.data[0] == 1))
+ }
+
+ {
+ pb_istream_t s;
+ CallbackArray dest;
+ struct { size_t size; uint8_t bytes[10]; } ref;
+ dest.data.funcs.decode = &callback_check;
+ dest.data.arg = &ref;
+
+ COMMENT("Testing pb_decode with callbacks")
+ /* Single varint */
+ ref.size = 1; ref.bytes[0] = 0x55;
+ TEST((s = S("\x08\x55"), pb_decode(&s, CallbackArray_fields, &dest)))
+ /* Packed varint */
+ ref.size = 3; ref.bytes[0] = ref.bytes[1] = ref.bytes[2] = 0x55;
+ TEST((s = S("\x0A\x03\x55\x55\x55"), pb_decode(&s, CallbackArray_fields, &dest)))
+ /* Packed varint with loop */
+ ref.size = 1; ref.bytes[0] = 0x55;
+ TEST((s = S("\x0A\x03\x55\x55\x55"), pb_decode(&s, CallbackArray_fields, &dest)))
+ /* Single fixed32 */
+ ref.size = 4; ref.bytes[0] = ref.bytes[1] = ref.bytes[2] = ref.bytes[3] = 0xAA;
+ TEST((s = S("\x0D\xAA\xAA\xAA\xAA"), pb_decode(&s, CallbackArray_fields, &dest)))
+ /* Single fixed64 */
+ ref.size = 8; memset(ref.bytes, 0xAA, 8);
+ TEST((s = S("\x09\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA"), pb_decode(&s, CallbackArray_fields, &dest)))
+ /* Unsupported field type */
+ TEST((s = S("\x0B\x00"), !pb_decode(&s, CallbackArray_fields, &dest)))
+
+ /* Just make sure that our test function works */
+ ref.size = 1; ref.bytes[0] = 0x56;
+ TEST((s = S("\x08\x55"), !pb_decode(&s, CallbackArray_fields, &dest)))
+ }
+
+ {
+ pb_istream_t s;
+ IntegerArray dest;
+
+ COMMENT("Testing pb_decode message termination")
+ TEST((s = S(""), pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x00"), pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x08\x01"), pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x08\x01\x00"), pb_decode(&s, IntegerArray_fields, &dest)))
+ TEST((s = S("\x08"), !pb_decode(&s, IntegerArray_fields, &dest)))
+ }
+
+ {
+ pb_istream_t s;
+ IntegerContainer dest = {{0}};
+
+ COMMENT("Testing pb_decode_delimited")
+ TEST((s = S("\x09\x0A\x07\x0A\x05\x01\x02\x03\x04\x05"),
+ pb_decode_delimited(&s, IntegerContainer_fields, &dest)) &&
+ dest.submsg.data_count == 5)
+ }
+
+ if (status != 0)
+ fprintf(stdout, "\n\nSome tests FAILED!\n");
+
+ return status;
+}
diff --git a/tests/encode_unittests/SConscript b/tests/encode_unittests/SConscript
new file mode 100644
index 0000000..bf6d140
--- /dev/null
+++ b/tests/encode_unittests/SConscript
@@ -0,0 +1,5 @@
+# Build and run the stand-alone unit tests for the nanopb encoder part.
+
+Import('env')
+p = env.Program(["encode_unittests.c", "$COMMON/unittestproto.pb.c"])
+env.RunTest(p)
diff --git a/tests/encode_unittests/encode_unittests.c b/tests/encode_unittests/encode_unittests.c
new file mode 100644
index 0000000..06935f9
--- /dev/null
+++ b/tests/encode_unittests/encode_unittests.c
@@ -0,0 +1,337 @@
+/* This includes the whole .c file to get access to static functions. */
+#include "pb_encode.c"
+
+#include <stdio.h>
+#include <string.h>
+#include "unittests.h"
+#include "unittestproto.pb.h"
+
+bool streamcallback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
+{
+ /* Allow only 'x' to be written */
+ while (count--)
+ {
+ if (*buf++ != 'x')
+ return false;
+ }
+ return true;
+}
+
+bool fieldcallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ int value = 0x55;
+ if (!pb_encode_tag_for_field(stream, field))
+ return false;
+ return pb_encode_varint(stream, value);
+}
+
+bool crazyfieldcallback(pb_ostream_t *stream, const pb_field_t *field, void * const *arg)
+{
+ /* This callback writes different amount of data the second time. */
+ uint32_t *state = (uint32_t*)arg;
+ *state <<= 8;
+ if (!pb_encode_tag_for_field(stream, field))
+ return false;
+ return pb_encode_varint(stream, *state);
+}
+
+/* Check that expression x writes data y.
+ * Y is a string, which may contain null bytes. Null terminator is ignored.
+ */
+#define WRITES(x, y) \
+memset(buffer, 0xAA, sizeof(buffer)), \
+s = pb_ostream_from_buffer(buffer, sizeof(buffer)), \
+(x) && \
+memcmp(buffer, y, sizeof(y) - 1) == 0 && \
+buffer[sizeof(y) - 1] == 0xAA
+
+int main()
+{
+ int status = 0;
+
+ {
+ uint8_t buffer1[] = "foobartest1234";
+ uint8_t buffer2[sizeof(buffer1)];
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer2, sizeof(buffer1));
+
+ COMMENT("Test pb_write and pb_ostream_t");
+ TEST(pb_write(&stream, buffer1, sizeof(buffer1)));
+ TEST(memcmp(buffer1, buffer2, sizeof(buffer1)) == 0);
+ TEST(!pb_write(&stream, buffer1, 1));
+ TEST(stream.bytes_written == sizeof(buffer1));
+ }
+
+ {
+ uint8_t buffer1[] = "xxxxxxx";
+ pb_ostream_t stream = {&streamcallback, 0, SIZE_MAX, 0};
+
+ COMMENT("Test pb_write with custom callback");
+ TEST(pb_write(&stream, buffer1, 5));
+ buffer1[0] = 'a';
+ TEST(!pb_write(&stream, buffer1, 5));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+
+ COMMENT("Test pb_encode_varint")
+ TEST(WRITES(pb_encode_varint(&s, 0), "\0"));
+ TEST(WRITES(pb_encode_varint(&s, 1), "\1"));
+ TEST(WRITES(pb_encode_varint(&s, 0x7F), "\x7F"));
+ TEST(WRITES(pb_encode_varint(&s, 0x80), "\x80\x01"));
+ TEST(WRITES(pb_encode_varint(&s, UINT32_MAX), "\xFF\xFF\xFF\xFF\x0F"));
+ TEST(WRITES(pb_encode_varint(&s, UINT64_MAX), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+
+ COMMENT("Test pb_encode_tag")
+ TEST(WRITES(pb_encode_tag(&s, PB_WT_STRING, 5), "\x2A"));
+ TEST(WRITES(pb_encode_tag(&s, PB_WT_VARINT, 99), "\x98\x06"));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+ pb_field_t field = {10, PB_LTYPE_SVARINT};
+
+ COMMENT("Test pb_encode_tag_for_field")
+ TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x50"));
+
+ field.type = PB_LTYPE_FIXED64;
+ TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x51"));
+
+ field.type = PB_LTYPE_STRING;
+ TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x52"));
+
+ field.type = PB_LTYPE_FIXED32;
+ TEST(WRITES(pb_encode_tag_for_field(&s, &field), "\x55"));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+
+ COMMENT("Test pb_encode_string")
+ TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"abcd", 4), "\x04""abcd"));
+ TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"abcd\x00", 5), "\x05""abcd\x00"));
+ TEST(WRITES(pb_encode_string(&s, (const uint8_t*)"", 0), "\x00"));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+ uint8_t value = 1;
+ int32_t max = INT32_MAX;
+ int32_t min = INT32_MIN;
+ int64_t lmax = INT64_MAX;
+ int64_t lmin = INT64_MIN;
+ pb_field_t field = {1, PB_LTYPE_VARINT, 0, 0, sizeof(value)};
+
+ COMMENT("Test pb_enc_varint and pb_enc_svarint")
+ TEST(WRITES(pb_enc_varint(&s, &field, &value), "\x01"));
+
+ field.data_size = sizeof(max);
+ TEST(WRITES(pb_enc_svarint(&s, &field, &max), "\xfe\xff\xff\xff\x0f"));
+ TEST(WRITES(pb_enc_svarint(&s, &field, &min), "\xff\xff\xff\xff\x0f"));
+
+ field.data_size = sizeof(lmax);
+ TEST(WRITES(pb_enc_svarint(&s, &field, &lmax), "\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"));
+ TEST(WRITES(pb_enc_svarint(&s, &field, &lmin), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01"));
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+ float fvalue;
+ double dvalue;
+
+ COMMENT("Test pb_enc_fixed32 using float")
+ fvalue = 0.0f;
+ TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x00\x00\x00\x00"))
+ fvalue = 99.0f;
+ TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x00\x00\xc6\x42"))
+ fvalue = -12345678.0f;
+ TEST(WRITES(pb_enc_fixed32(&s, NULL, &fvalue), "\x4e\x61\x3c\xcb"))
+
+ COMMENT("Test pb_enc_fixed64 using double")
+ dvalue = 0.0;
+ TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\x00\x00\x00\x00\x00"))
+ dvalue = 99.0;
+ TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\x00\x00\xc0\x58\x40"))
+ dvalue = -12345678.0;
+ TEST(WRITES(pb_enc_fixed64(&s, NULL, &dvalue), "\x00\x00\x00\xc0\x29\x8c\x67\xc1"))
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+ struct { size_t size; uint8_t bytes[5]; } value = {5, {'x', 'y', 'z', 'z', 'y'}};
+
+ COMMENT("Test pb_enc_bytes")
+ TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x05xyzzy"))
+ value.size = 0;
+ TEST(WRITES(pb_enc_bytes(&s, &BytesMessage_fields[0], &value), "\x00"))
+ }
+
+ {
+ uint8_t buffer[30];
+ pb_ostream_t s;
+ char value[30] = "xyzzy";
+
+ COMMENT("Test pb_enc_string")
+ TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x05xyzzy"))
+ value[0] = '\0';
+ TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x00"))
+ memset(value, 'x', 30);
+ TEST(WRITES(pb_enc_string(&s, &StringMessage_fields[0], &value), "\x0Axxxxxxxxxx"))
+ }
+
+ {
+ uint8_t buffer[10];
+ pb_ostream_t s;
+ IntegerArray msg = {5, {1, 2, 3, 4, 5}};
+
+ COMMENT("Test pb_encode with int32 array")
+
+ TEST(WRITES(pb_encode(&s, IntegerArray_fields, &msg), "\x0A\x05\x01\x02\x03\x04\x05"))
+
+ msg.data_count = 0;
+ TEST(WRITES(pb_encode(&s, IntegerArray_fields, &msg), ""))
+
+ msg.data_count = 10;
+ TEST(!pb_encode(&s, IntegerArray_fields, &msg))
+ }
+
+ {
+ uint8_t buffer[10];
+ pb_ostream_t s;
+ FloatArray msg = {1, {99.0f}};
+
+ COMMENT("Test pb_encode with float array")
+
+ TEST(WRITES(pb_encode(&s, FloatArray_fields, &msg),
+ "\x0A\x04\x00\x00\xc6\x42"))
+
+ msg.data_count = 0;
+ TEST(WRITES(pb_encode(&s, FloatArray_fields, &msg), ""))
+
+ msg.data_count = 3;
+ TEST(!pb_encode(&s, FloatArray_fields, &msg))
+ }
+
+ {
+ uint8_t buffer[50];
+ pb_ostream_t s;
+ FloatArray msg = {1, {99.0f}};
+
+ COMMENT("Test array size limit in pb_encode")
+
+ s = pb_ostream_from_buffer(buffer, sizeof(buffer));
+ TEST((msg.data_count = 10) && pb_encode(&s, FloatArray_fields, &msg))
+
+ s = pb_ostream_from_buffer(buffer, sizeof(buffer));
+ TEST((msg.data_count = 11) && !pb_encode(&s, FloatArray_fields, &msg))
+ }
+
+ {
+ uint8_t buffer[10];
+ pb_ostream_t s;
+ CallbackArray msg;
+
+ msg.data.funcs.encode = &fieldcallback;
+
+ COMMENT("Test pb_encode with callback field.")
+ TEST(WRITES(pb_encode(&s, CallbackArray_fields, &msg), "\x08\x55"))
+ }
+
+ {
+ uint8_t buffer[10];
+ pb_ostream_t s;
+ IntegerContainer msg = {{5, {1,2,3,4,5}}};
+
+ COMMENT("Test pb_encode with packed array in a submessage.")
+ TEST(WRITES(pb_encode(&s, IntegerContainer_fields, &msg),
+ "\x0A\x07\x0A\x05\x01\x02\x03\x04\x05"))
+ }
+
+ {
+ uint8_t buffer[32];
+ pb_ostream_t s;
+ BytesMessage msg = {{3, "xyz"}};
+
+ COMMENT("Test pb_encode with bytes message.")
+ TEST(WRITES(pb_encode(&s, BytesMessage_fields, &msg),
+ "\x0A\x03xyz"))
+
+ msg.data.size = 17; /* More than maximum */
+ TEST(!pb_encode(&s, BytesMessage_fields, &msg))
+ }
+
+
+ {
+ uint8_t buffer[20];
+ pb_ostream_t s;
+ IntegerContainer msg = {{5, {1,2,3,4,5}}};
+
+ COMMENT("Test pb_encode_delimited.")
+ TEST(WRITES(pb_encode_delimited(&s, IntegerContainer_fields, &msg),
+ "\x09\x0A\x07\x0A\x05\x01\x02\x03\x04\x05"))
+ }
+
+ {
+ IntegerContainer msg = {{5, {1,2,3,4,5}}};
+ size_t size;
+
+ COMMENT("Test pb_get_encoded_size.")
+ TEST(pb_get_encoded_size(&size, IntegerContainer_fields, &msg) &&
+ size == 9);
+ }
+
+ {
+ uint8_t buffer[10];
+ pb_ostream_t s;
+ CallbackContainer msg;
+ CallbackContainerContainer msg2;
+ uint32_t state = 1;
+
+ msg.submsg.data.funcs.encode = &fieldcallback;
+ msg2.submsg.submsg.data.funcs.encode = &fieldcallback;
+
+ COMMENT("Test pb_encode with callback field in a submessage.")
+ TEST(WRITES(pb_encode(&s, CallbackContainer_fields, &msg), "\x0A\x02\x08\x55"))
+ TEST(WRITES(pb_encode(&s, CallbackContainerContainer_fields, &msg2),
+ "\x0A\x04\x0A\x02\x08\x55"))
+
+ /* Misbehaving callback: varying output between calls */
+ msg.submsg.data.funcs.encode = &crazyfieldcallback;
+ msg.submsg.data.arg = &state;
+ msg2.submsg.submsg.data.funcs.encode = &crazyfieldcallback;
+ msg2.submsg.submsg.data.arg = &state;
+
+ TEST(!pb_encode(&s, CallbackContainer_fields, &msg))
+ state = 1;
+ TEST(!pb_encode(&s, CallbackContainerContainer_fields, &msg2))
+ }
+
+ {
+ uint8_t buffer[StringMessage_size];
+ pb_ostream_t s;
+ StringMessage msg = {"0123456789"};
+
+ s = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ COMMENT("Test that StringMessage_size is correct")
+
+ TEST(pb_encode(&s, StringMessage_fields, &msg));
+ TEST(s.bytes_written == StringMessage_size);
+ }
+
+ if (status != 0)
+ fprintf(stdout, "\n\nSome tests FAILED!\n");
+
+ return status;
+}
diff --git a/tests/extensions/SConscript b/tests/extensions/SConscript
new file mode 100644
index 0000000..26fc5a3
--- /dev/null
+++ b/tests/extensions/SConscript
@@ -0,0 +1,16 @@
+# Test the support for extension fields.
+
+Import("env")
+
+# We use the files from the alltypes test case
+incpath = env.Clone()
+incpath.Append(PROTOCPATH = '$BUILD/alltypes')
+incpath.Append(CPPPATH = '$BUILD/alltypes')
+
+incpath.NanopbProto(["extensions", "extensions.options"])
+enc = incpath.Program(["encode_extensions.c", "extensions.pb.c", "$BUILD/alltypes/alltypes.pb$OBJSUFFIX", "$COMMON/pb_encode.o"])
+dec = incpath.Program(["decode_extensions.c", "extensions.pb.c", "$BUILD/alltypes/alltypes.pb$OBJSUFFIX", "$COMMON/pb_decode.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_extensions.output"])
+
diff --git a/tests/extensions/decode_extensions.c b/tests/extensions/decode_extensions.c
new file mode 100644
index 0000000..e437438
--- /dev/null
+++ b/tests/extensions/decode_extensions.c
@@ -0,0 +1,60 @@
+/* Test decoding of extension fields. */
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <pb_decode.h>
+#include "alltypes.pb.h"
+#include "extensions.pb.h"
+#include "test_helpers.h"
+
+#define TEST(x) if (!(x)) { \
+ printf("Test " #x " failed.\n"); \
+ return 2; \
+ }
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ size_t count;
+ pb_istream_t stream;
+
+ AllTypes alltypes = {0};
+ int32_t extensionfield1;
+ pb_extension_t ext1;
+ ExtensionMessage extensionfield2;
+ pb_extension_t ext2;
+
+ /* Read the message data */
+ SET_BINARY_MODE(stdin);
+ count = fread(buffer, 1, sizeof(buffer), stdin);
+ stream = pb_istream_from_buffer(buffer, count);
+
+ /* Add the extensions */
+ alltypes.extensions = &ext1;
+
+ ext1.type = &AllTypes_extensionfield1;
+ ext1.dest = &extensionfield1;
+ ext1.next = &ext2;
+
+ ext2.type = &ExtensionMessage_AllTypes_extensionfield2;
+ ext2.dest = &extensionfield2;
+ ext2.next = NULL;
+
+ /* Decode the message */
+ if (!pb_decode(&stream, AllTypes_fields, &alltypes))
+ {
+ printf("Parsing failed: %s\n", PB_GET_ERROR(&stream));
+ return 1;
+ }
+
+ /* Check that the extensions decoded properly */
+ TEST(ext1.found)
+ TEST(extensionfield1 == 12345)
+ TEST(ext2.found)
+ TEST(strcmp(extensionfield2.test1, "test") == 0)
+ TEST(extensionfield2.test2 == 54321)
+
+ return 0;
+}
+
diff --git a/tests/extensions/encode_extensions.c b/tests/extensions/encode_extensions.c
new file mode 100644
index 0000000..0074582
--- /dev/null
+++ b/tests/extensions/encode_extensions.c
@@ -0,0 +1,54 @@
+/* Tests extension fields.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <pb_encode.h>
+#include "alltypes.pb.h"
+#include "extensions.pb.h"
+#include "test_helpers.h"
+
+int main(int argc, char **argv)
+{
+ uint8_t buffer[1024];
+ pb_ostream_t stream;
+
+ AllTypes alltypes = {0};
+ int32_t extensionfield1 = 12345;
+ pb_extension_t ext1;
+ ExtensionMessage extensionfield2 = {"test", 54321};
+ pb_extension_t ext2;
+
+ /* Set up the extensions */
+ alltypes.extensions = &ext1;
+
+ ext1.type = &AllTypes_extensionfield1;
+ ext1.dest = &extensionfield1;
+ ext1.next = &ext2;
+
+ ext2.type = &ExtensionMessage_AllTypes_extensionfield2;
+ ext2.dest = &extensionfield2;
+ ext2.next = NULL;
+
+ /* Set up the output stream */
+ stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ /* Now encode the message and check if we succeeded. */
+ if (pb_encode(&stream, AllTypes_fields, &alltypes))
+ {
+ SET_BINARY_MODE(stdout);
+ fwrite(buffer, 1, stream.bytes_written, stdout);
+ return 0; /* Success */
+ }
+ else
+ {
+ fprintf(stderr, "Encoding failed: %s\n", PB_GET_ERROR(&stream));
+ return 1; /* Failure */
+ }
+
+ /* Check that the field tags are properly generated */
+ (void)AllTypes_extensionfield1_tag;
+ (void)ExtensionMessage_AllTypes_extensionfield2_tag;
+}
+
diff --git a/tests/extensions/extensions.options b/tests/extensions/extensions.options
new file mode 100644
index 0000000..a5cd61d
--- /dev/null
+++ b/tests/extensions/extensions.options
@@ -0,0 +1 @@
+* max_size:16
diff --git a/tests/extensions/extensions.proto b/tests/extensions/extensions.proto
new file mode 100644
index 0000000..da8432e
--- /dev/null
+++ b/tests/extensions/extensions.proto
@@ -0,0 +1,17 @@
+import 'alltypes.proto';
+
+extend AllTypes {
+ optional int32 AllTypes_extensionfield1 = 255 [default = 5];
+}
+
+message ExtensionMessage {
+ extend AllTypes {
+ optional ExtensionMessage AllTypes_extensionfield2 = 254;
+ required ExtensionMessage AllTypes_extensionfield3 = 253;
+ repeated ExtensionMessage AllTypes_extensionfield4 = 252;
+ }
+
+ required string test1 = 1;
+ required int32 test2 = 2;
+}
+
diff --git a/tests/extra_fields/SConscript b/tests/extra_fields/SConscript
new file mode 100644
index 0000000..75ac5c5
--- /dev/null
+++ b/tests/extra_fields/SConscript
@@ -0,0 +1,16 @@
+# Test that the decoder properly handles unknown fields in the input.
+
+Import("env")
+
+dec = env.GetBuildPath('$BUILD/basic_buffer/${PROGPREFIX}decode_buffer${PROGSUFFIX}')
+env.RunTest('person_with_extra_field.output', [dec, "person_with_extra_field.pb"])
+env.Compare(["person_with_extra_field.output", "person_with_extra_field.expected"])
+
+dec = env.GetBuildPath('$BUILD/basic_stream/${PROGPREFIX}decode_stream${PROGSUFFIX}')
+env.RunTest('person_with_extra_field_stream.output', [dec, "person_with_extra_field.pb"])
+env.Compare(["person_with_extra_field_stream.output", "person_with_extra_field.expected"])
+
+# This uses the backwards compatibility alltypes test, so that
+# alltypes_with_extra_fields.pb doesn't have to be remade so often.
+dec2 = env.GetBuildPath('$BUILD/backwards_compatibility/${PROGPREFIX}decode_legacy${PROGSUFFIX}')
+env.RunTest('alltypes_with_extra_fields.output', [dec2, 'alltypes_with_extra_fields.pb'])
diff --git a/tests/extra_fields/alltypes_with_extra_fields.pb b/tests/extra_fields/alltypes_with_extra_fields.pb
new file mode 100644
index 0000000..f9f5394
--- /dev/null
+++ b/tests/extra_fields/alltypes_with_extra_fields.pb
Binary files differ
diff --git a/tests/extra_fields/person_with_extra_field.expected b/tests/extra_fields/person_with_extra_field.expected
new file mode 100644
index 0000000..da9c32d
--- /dev/null
+++ b/tests/extra_fields/person_with_extra_field.expected
@@ -0,0 +1,14 @@
+name: "Test Person 99"
+id: 99
+email: "test@person.com"
+phone {
+ number: "555-12345678"
+ type: MOBILE
+}
+phone {
+ number: "99-2342"
+}
+phone {
+ number: "1234-5678"
+ type: WORK
+}
diff --git a/tests/extra_fields/person_with_extra_field.pb b/tests/extra_fields/person_with_extra_field.pb
new file mode 100644
index 0000000..ffb303d
--- /dev/null
+++ b/tests/extra_fields/person_with_extra_field.pb
Binary files differ
diff --git a/tests/field_size_16/SConscript b/tests/field_size_16/SConscript
new file mode 100644
index 0000000..8fee004
--- /dev/null
+++ b/tests/field_size_16/SConscript
@@ -0,0 +1,28 @@
+# Run the alltypes test case, but compile with PB_FIELD_16BIT=1.
+# Also the .proto file has been modified to have high indexes.
+
+Import("env")
+
+# Take copy of the files for custom build.
+c = Copy("$TARGET", "$SOURCE")
+env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c)
+env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c)
+
+env.NanopbProto(["alltypes", "alltypes.options"])
+
+# Define the compilation options
+opts = env.Clone()
+opts.Append(CPPDEFINES = {'PB_FIELD_16BIT': 1})
+
+# Build new version of core
+strict = opts.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode_fields16.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode_fields16.o", "$NANOPB/pb_encode.c")
+
+# Now build and run the test normally.
+enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_fields16.o"])
+dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_fields16.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
diff --git a/tests/field_size_16/alltypes.options b/tests/field_size_16/alltypes.options
new file mode 100644
index 0000000..b31e3cf
--- /dev/null
+++ b/tests/field_size_16/alltypes.options
@@ -0,0 +1,3 @@
+* max_size:16
+* max_count:5
+
diff --git a/tests/field_size_16/alltypes.proto b/tests/field_size_16/alltypes.proto
new file mode 100644
index 0000000..7494853
--- /dev/null
+++ b/tests/field_size_16/alltypes.proto
@@ -0,0 +1,111 @@
+message SubMessage {
+ required string substuff1 = 1 [default = "1"];
+ required int32 substuff2 = 2 [default = 2];
+ optional fixed32 substuff3 = 65535 [default = 3];
+}
+
+message EmptyMessage {
+
+}
+
+enum HugeEnum {
+ Negative = -2147483647; /* protoc doesn't accept -2147483648 here */
+ Positive = 2147483647;
+}
+
+message Limits {
+ required int32 int32_min = 1;
+ required int32 int32_max = 2;
+ required uint32 uint32_min = 3;
+ required uint32 uint32_max = 4;
+ required int64 int64_min = 5;
+ required int64 int64_max = 6;
+ required uint64 uint64_min = 7;
+ required uint64 uint64_max = 8;
+ required HugeEnum enum_min = 9;
+ required HugeEnum enum_max = 10;
+}
+
+enum MyEnum {
+ Zero = 0;
+ First = 1;
+ Second = 2;
+ Truth = 42;
+}
+
+message AllTypes {
+ required int32 req_int32 = 1;
+ required int64 req_int64 = 2;
+ required uint32 req_uint32 = 3;
+ required uint64 req_uint64 = 4;
+ required sint32 req_sint32 = 5;
+ required sint64 req_sint64 = 6;
+ required bool req_bool = 7;
+
+ required fixed32 req_fixed32 = 8;
+ required sfixed32 req_sfixed32= 9;
+ required float req_float = 10;
+
+ required fixed64 req_fixed64 = 11;
+ required sfixed64 req_sfixed64= 12;
+ required double req_double = 13;
+
+ required string req_string = 14;
+ required bytes req_bytes = 15;
+ required SubMessage req_submsg = 16;
+ required MyEnum req_enum = 17;
+ required EmptyMessage req_emptymsg = 18;
+
+
+ repeated int32 rep_int32 = 21;
+ repeated int64 rep_int64 = 22;
+ repeated uint32 rep_uint32 = 23;
+ repeated uint64 rep_uint64 = 24;
+ repeated sint32 rep_sint32 = 25;
+ repeated sint64 rep_sint64 = 26;
+ repeated bool rep_bool = 27;
+
+ repeated fixed32 rep_fixed32 = 28;
+ repeated sfixed32 rep_sfixed32= 29;
+ repeated float rep_float = 30;
+
+ repeated fixed64 rep_fixed64 = 10031;
+ repeated sfixed64 rep_sfixed64= 10032;
+ repeated double rep_double = 10033;
+
+ repeated string rep_string = 10034;
+ repeated bytes rep_bytes = 10035;
+ repeated SubMessage rep_submsg = 10036;
+ repeated MyEnum rep_enum = 10037;
+ repeated EmptyMessage rep_emptymsg = 10038;
+
+ optional int32 opt_int32 = 10041 [default = 4041];
+ optional int64 opt_int64 = 10042 [default = 4042];
+ optional uint32 opt_uint32 = 10043 [default = 4043];
+ optional uint64 opt_uint64 = 10044 [default = 4044];
+ optional sint32 opt_sint32 = 10045 [default = 4045];
+ optional sint64 opt_sint64 = 10046 [default = 4046];
+ optional bool opt_bool = 10047 [default = false];
+
+ optional fixed32 opt_fixed32 = 10048 [default = 4048];
+ optional sfixed32 opt_sfixed32= 10049 [default = 4049];
+ optional float opt_float = 10050 [default = 4050];
+
+ optional fixed64 opt_fixed64 = 10051 [default = 4051];
+ optional sfixed64 opt_sfixed64= 10052 [default = 4052];
+ optional double opt_double = 10053 [default = 4053];
+
+ optional string opt_string = 10054 [default = "4054"];
+ optional bytes opt_bytes = 10055 [default = "4055"];
+ optional SubMessage opt_submsg = 10056;
+ optional MyEnum opt_enum = 10057 [default = Second];
+ optional EmptyMessage opt_emptymsg = 10058;
+
+ // Check that extreme integer values are handled correctly
+ required Limits req_limits = 98;
+
+ // Just to make sure that the size of the fields has been calculated
+ // properly, i.e. otherwise a bug in last field might not be detected.
+ required int32 end = 10099;
+}
+
diff --git a/tests/field_size_32/SConscript b/tests/field_size_32/SConscript
new file mode 100644
index 0000000..2a64c6c
--- /dev/null
+++ b/tests/field_size_32/SConscript
@@ -0,0 +1,28 @@
+# Run the alltypes test case, but compile with PB_FIELD_32BIT=1.
+# Also the .proto file has been modified to have high indexes.
+
+Import("env")
+
+# Take copy of the files for custom build.
+c = Copy("$TARGET", "$SOURCE")
+env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c)
+env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c)
+
+env.NanopbProto(["alltypes", "alltypes.options"])
+
+# Define the compilation options
+opts = env.Clone()
+opts.Append(CPPDEFINES = {'PB_FIELD_32BIT': 1})
+
+# Build new version of core
+strict = opts.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode_fields32.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode_fields32.o", "$NANOPB/pb_encode.c")
+
+# Now build and run the test normally.
+enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_fields32.o"])
+dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_fields32.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
diff --git a/tests/field_size_32/alltypes.options b/tests/field_size_32/alltypes.options
new file mode 100644
index 0000000..b31e3cf
--- /dev/null
+++ b/tests/field_size_32/alltypes.options
@@ -0,0 +1,3 @@
+* max_size:16
+* max_count:5
+
diff --git a/tests/field_size_32/alltypes.proto b/tests/field_size_32/alltypes.proto
new file mode 100644
index 0000000..17f17ee
--- /dev/null
+++ b/tests/field_size_32/alltypes.proto
@@ -0,0 +1,111 @@
+message SubMessage {
+ required string substuff1 = 1 [default = "1"];
+ required int32 substuff2 = 2 [default = 2];
+ optional fixed32 substuff3 = 12365535 [default = 3];
+}
+
+message EmptyMessage {
+
+}
+
+enum HugeEnum {
+ Negative = -2147483647; /* protoc doesn't accept -2147483648 here */
+ Positive = 2147483647;
+}
+
+message Limits {
+ required int32 int32_min = 1;
+ required int32 int32_max = 2;
+ required uint32 uint32_min = 3;
+ required uint32 uint32_max = 4;
+ required int64 int64_min = 5;
+ required int64 int64_max = 6;
+ required uint64 uint64_min = 7;
+ required uint64 uint64_max = 8;
+ required HugeEnum enum_min = 9;
+ required HugeEnum enum_max = 10;
+}
+
+enum MyEnum {
+ Zero = 0;
+ First = 1;
+ Second = 2;
+ Truth = 42;
+}
+
+message AllTypes {
+ required int32 req_int32 = 1;
+ required int64 req_int64 = 2;
+ required uint32 req_uint32 = 3;
+ required uint64 req_uint64 = 4;
+ required sint32 req_sint32 = 5;
+ required sint64 req_sint64 = 6;
+ required bool req_bool = 7;
+
+ required fixed32 req_fixed32 = 8;
+ required sfixed32 req_sfixed32= 9;
+ required float req_float = 10;
+
+ required fixed64 req_fixed64 = 11;
+ required sfixed64 req_sfixed64= 12;
+ required double req_double = 13;
+
+ required string req_string = 14;
+ required bytes req_bytes = 15;
+ required SubMessage req_submsg = 16;
+ required MyEnum req_enum = 17;
+ required EmptyMessage req_emptymsg = 18;
+
+
+ repeated int32 rep_int32 = 21;
+ repeated int64 rep_int64 = 22;
+ repeated uint32 rep_uint32 = 23;
+ repeated uint64 rep_uint64 = 24;
+ repeated sint32 rep_sint32 = 25;
+ repeated sint64 rep_sint64 = 26;
+ repeated bool rep_bool = 27;
+
+ repeated fixed32 rep_fixed32 = 28;
+ repeated sfixed32 rep_sfixed32= 29;
+ repeated float rep_float = 30;
+
+ repeated fixed64 rep_fixed64 = 10031;
+ repeated sfixed64 rep_sfixed64= 10032;
+ repeated double rep_double = 10033;
+
+ repeated string rep_string = 10034;
+ repeated bytes rep_bytes = 10035;
+ repeated SubMessage rep_submsg = 10036;
+ repeated MyEnum rep_enum = 10037;
+ repeated EmptyMessage rep_emptymsg = 10038;
+
+ optional int32 opt_int32 = 10041 [default = 4041];
+ optional int64 opt_int64 = 10042 [default = 4042];
+ optional uint32 opt_uint32 = 10043 [default = 4043];
+ optional uint64 opt_uint64 = 10044 [default = 4044];
+ optional sint32 opt_sint32 = 10045 [default = 4045];
+ optional sint64 opt_sint64 = 10046 [default = 4046];
+ optional bool opt_bool = 10047 [default = false];
+
+ optional fixed32 opt_fixed32 = 10048 [default = 4048];
+ optional sfixed32 opt_sfixed32= 10049 [default = 4049];
+ optional float opt_float = 10050 [default = 4050];
+
+ optional fixed64 opt_fixed64 = 10051 [default = 4051];
+ optional sfixed64 opt_sfixed64= 10052 [default = 4052];
+ optional double opt_double = 10053 [default = 4053];
+
+ optional string opt_string = 10054 [default = "4054"];
+ optional bytes opt_bytes = 10055 [default = "4055"];
+ optional SubMessage opt_submsg = 10056;
+ optional MyEnum opt_enum = 10057 [default = Second];
+ optional EmptyMessage opt_emptymsg = 10058;
+
+ // Check that extreme integer values are handled correctly
+ required Limits req_limits = 98;
+
+ // Just to make sure that the size of the fields has been calculated
+ // properly, i.e. otherwise a bug in last field might not be detected.
+ required int32 end = 13432099;
+}
+
diff --git a/tests/message_sizes/SConscript b/tests/message_sizes/SConscript
new file mode 100644
index 0000000..e7524e0
--- /dev/null
+++ b/tests/message_sizes/SConscript
@@ -0,0 +1,11 @@
+# Test the generation of message size #defines
+
+Import('env')
+
+incpath = env.Clone()
+incpath.Append(PROTOCPATH = '#message_sizes')
+
+incpath.NanopbProto("messages1")
+incpath.NanopbProto("messages2")
+
+incpath.Program(['dummy.c', 'messages1.pb.c', 'messages2.pb.c'])
diff --git a/tests/message_sizes/dummy.c b/tests/message_sizes/dummy.c
new file mode 100644
index 0000000..767ad46
--- /dev/null
+++ b/tests/message_sizes/dummy.c
@@ -0,0 +1,9 @@
+/* Just test that the file can be compiled successfully. */
+
+#include "messages2.pb.h"
+
+int main()
+{
+ return xmit_size;
+}
+
diff --git a/tests/message_sizes/messages1.proto b/tests/message_sizes/messages1.proto
new file mode 100644
index 0000000..48af55a
--- /dev/null
+++ b/tests/message_sizes/messages1.proto
@@ -0,0 +1,27 @@
+enum MessageStatus {
+ FAIL = 0;
+ OK = 1;
+};
+
+message MessageInfo {
+ required fixed32 msg_id = 1;
+ optional fixed32 interface_id = 2;
+}
+
+message MessageResponseInfo {
+ required fixed64 interface_id = 1;
+ required fixed32 seq = 2;
+ required fixed32 msg_id = 3;
+}
+
+message MessageHeader {
+ required MessageInfo info = 1;
+ optional MessageResponseInfo response_info = 2;
+ optional MessageResponse response = 3;
+}
+
+message MessageResponse {
+ required MessageStatus status = 1;
+ required fixed32 seq = 2;
+}
+
diff --git a/tests/message_sizes/messages2.proto b/tests/message_sizes/messages2.proto
new file mode 100644
index 0000000..19fc11e
--- /dev/null
+++ b/tests/message_sizes/messages2.proto
@@ -0,0 +1,8 @@
+import 'nanopb.proto';
+import 'messages1.proto';
+
+message xmit {
+ required MessageHeader header = 1;
+ required bytes data = 2 [(nanopb).max_size = 128];
+}
+
diff --git a/tests/missing_fields/SConscript b/tests/missing_fields/SConscript
new file mode 100644
index 0000000..9926efa
--- /dev/null
+++ b/tests/missing_fields/SConscript
@@ -0,0 +1,8 @@
+# Check that the decoder properly detects when required fields are missing.
+
+Import("env")
+
+env.NanopbProto("missing_fields")
+test = env.Program(["missing_fields.c", "missing_fields.pb.c", "$COMMON/pb_encode.o", "$COMMON/pb_decode.o"])
+env.RunTest(test)
+
diff --git a/tests/missing_fields/missing_fields.c b/tests/missing_fields/missing_fields.c
new file mode 100644
index 0000000..8aded82
--- /dev/null
+++ b/tests/missing_fields/missing_fields.c
@@ -0,0 +1,53 @@
+/* Checks that missing required fields are detected properly */
+
+#include <stdio.h>
+#include <pb_encode.h>
+#include <pb_decode.h>
+#include "missing_fields.pb.h"
+
+int main()
+{
+ uint8_t buffer[512];
+ size_t size;
+
+ /* Create a message with one missing field */
+ {
+ MissingField msg = {0};
+ pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+
+ if (!pb_encode(&stream, MissingField_fields, &msg))
+ {
+ printf("Encode failed.\n");
+ return 1;
+ }
+
+ size = stream.bytes_written;
+ }
+
+ /* Test that it decodes properly if we don't require that field */
+ {
+ MissingField msg = {0};
+ pb_istream_t stream = pb_istream_from_buffer(buffer, size);
+
+ if (!pb_decode(&stream, MissingField_fields, &msg))
+ {
+ printf("Decode failed: %s\n", PB_GET_ERROR(&stream));
+ return 2;
+ }
+ }
+
+ /* Test that it does *not* decode properly if we require the field */
+ {
+ AllFields msg = {0};
+ pb_istream_t stream = pb_istream_from_buffer(buffer, size);
+
+ if (pb_decode(&stream, AllFields_fields, &msg))
+ {
+ printf("Decode didn't detect missing field.\n");
+ return 3;
+ }
+ }
+
+ return 0; /* All ok */
+}
+
diff --git a/tests/missing_fields/missing_fields.proto b/tests/missing_fields/missing_fields.proto
new file mode 100644
index 0000000..cbb23ba
--- /dev/null
+++ b/tests/missing_fields/missing_fields.proto
@@ -0,0 +1,138 @@
+/* Test for one missing field among many */
+
+message AllFields
+{
+ required int32 field1 = 1;
+ required int32 field2 = 2;
+ required int32 field3 = 3;
+ required int32 field4 = 4;
+ required int32 field5 = 5;
+ required int32 field6 = 6;
+ required int32 field7 = 7;
+ required int32 field8 = 8;
+ required int32 field9 = 9;
+ required int32 field10 = 10;
+ required int32 field11 = 11;
+ required int32 field12 = 12;
+ required int32 field13 = 13;
+ required int32 field14 = 14;
+ required int32 field15 = 15;
+ required int32 field16 = 16;
+ required int32 field17 = 17;
+ required int32 field18 = 18;
+ required int32 field19 = 19;
+ required int32 field20 = 20;
+ required int32 field21 = 21;
+ required int32 field22 = 22;
+ required int32 field23 = 23;
+ required int32 field24 = 24;
+ required int32 field25 = 25;
+ required int32 field26 = 26;
+ required int32 field27 = 27;
+ required int32 field28 = 28;
+ required int32 field29 = 29;
+ required int32 field30 = 30;
+ required int32 field31 = 31;
+ required int32 field32 = 32;
+ required int32 field33 = 33;
+ required int32 field34 = 34;
+ required int32 field35 = 35;
+ required int32 field36 = 36;
+ required int32 field37 = 37;
+ required int32 field38 = 38;
+ required int32 field39 = 39;
+ required int32 field40 = 40;
+ required int32 field41 = 41;
+ required int32 field42 = 42;
+ required int32 field43 = 43;
+ required int32 field44 = 44;
+ required int32 field45 = 45;
+ required int32 field46 = 46;
+ required int32 field47 = 47;
+ required int32 field48 = 48;
+ required int32 field49 = 49;
+ required int32 field50 = 50;
+ required int32 field51 = 51;
+ required int32 field52 = 52;
+ required int32 field53 = 53;
+ required int32 field54 = 54;
+ required int32 field55 = 55;
+ required int32 field56 = 56;
+ required int32 field57 = 57;
+ required int32 field58 = 58;
+ required int32 field59 = 59;
+ required int32 field60 = 60;
+ required int32 field61 = 61;
+ required int32 field62 = 62;
+ required int32 field63 = 63;
+ required int32 field64 = 64;
+}
+
+message MissingField
+{
+ required int32 field1 = 1;
+ required int32 field2 = 2;
+ required int32 field3 = 3;
+ required int32 field4 = 4;
+ required int32 field5 = 5;
+ required int32 field6 = 6;
+ required int32 field7 = 7;
+ required int32 field8 = 8;
+ required int32 field9 = 9;
+ required int32 field10 = 10;
+ required int32 field11 = 11;
+ required int32 field12 = 12;
+ required int32 field13 = 13;
+ required int32 field14 = 14;
+ required int32 field15 = 15;
+ required int32 field16 = 16;
+ required int32 field17 = 17;
+ required int32 field18 = 18;
+ required int32 field19 = 19;
+ required int32 field20 = 20;
+ required int32 field21 = 21;
+ required int32 field22 = 22;
+ required int32 field23 = 23;
+ required int32 field24 = 24;
+ required int32 field25 = 25;
+ required int32 field26 = 26;
+ required int32 field27 = 27;
+ required int32 field28 = 28;
+ required int32 field29 = 29;
+ required int32 field30 = 30;
+ required int32 field31 = 31;
+ required int32 field32 = 32;
+ required int32 field33 = 33;
+ required int32 field34 = 34;
+ required int32 field35 = 35;
+ required int32 field36 = 36;
+ required int32 field37 = 37;
+ required int32 field38 = 38;
+ required int32 field39 = 39;
+ required int32 field40 = 40;
+ required int32 field41 = 41;
+ required int32 field42 = 42;
+ required int32 field43 = 43;
+ required int32 field44 = 44;
+ required int32 field45 = 45;
+ required int32 field46 = 46;
+ required int32 field47 = 47;
+ required int32 field48 = 48;
+ required int32 field49 = 49;
+ required int32 field50 = 50;
+ required int32 field51 = 51;
+ required int32 field52 = 52;
+ required int32 field53 = 53;
+ required int32 field54 = 54;
+ required int32 field55 = 55;
+ required int32 field56 = 56;
+ required int32 field57 = 57;
+ required int32 field58 = 58;
+ required int32 field59 = 59;
+ required int32 field60 = 60;
+ required int32 field61 = 61;
+ required int32 field62 = 62;
+/* required int32 field63 = 63; */
+ required int32 field64 = 64;
+}
+
diff --git a/tests/multiple_files/SConscript b/tests/multiple_files/SConscript
new file mode 100644
index 0000000..6b4f6b6
--- /dev/null
+++ b/tests/multiple_files/SConscript
@@ -0,0 +1,13 @@
+# Test that multiple .proto files don't cause name collisions.
+
+Import("env")
+
+incpath = env.Clone()
+incpath.Append(PROTOCPATH = '#multiple_files')
+
+incpath.NanopbProto("callbacks")
+incpath.NanopbProto("callbacks2")
+test = incpath.Program(["test_multiple_files.c", "callbacks.pb.c", "callbacks2.pb.c"])
+
+env.RunTest(test)
+
diff --git a/tests/multiple_files/callbacks.proto b/tests/multiple_files/callbacks.proto
new file mode 100644
index 0000000..ccd1edd
--- /dev/null
+++ b/tests/multiple_files/callbacks.proto
@@ -0,0 +1,16 @@
+message SubMessage {
+ optional string stringvalue = 1;
+ repeated int32 int32value = 2;
+ repeated fixed32 fixed32value = 3;
+ repeated fixed64 fixed64value = 4;
+}
+
+message TestMessage {
+ optional string stringvalue = 1;
+ repeated int32 int32value = 2;
+ repeated fixed32 fixed32value = 3;
+ repeated fixed64 fixed64value = 4;
+ optional SubMessage submsg = 5;
+ repeated string repeatedstring = 6;
+}
+
diff --git a/tests/multiple_files/callbacks2.proto b/tests/multiple_files/callbacks2.proto
new file mode 100644
index 0000000..9a55e15
--- /dev/null
+++ b/tests/multiple_files/callbacks2.proto
@@ -0,0 +1,9 @@
+// Test if including generated header file for this file + implicit include of
+// callbacks.pb.h still compiles. Used with test_compiles.c.
+import "callbacks.proto";
+
+message Callback2Message {
+ required TestMessage tstmsg = 1;
+ required SubMessage submsg = 2;
+}
+
diff --git a/tests/multiple_files/test_multiple_files.c b/tests/multiple_files/test_multiple_files.c
new file mode 100644
index 0000000..05722dc
--- /dev/null
+++ b/tests/multiple_files/test_multiple_files.c
@@ -0,0 +1,12 @@
+/*
+ * Tests if this still compiles when multiple .proto files are involved.
+ */
+
+#include <stdio.h>
+#include <pb_encode.h>
+#include "callbacks2.pb.h"
+
+int main()
+{
+ return 0;
+}
diff --git a/tests/no_errmsg/SConscript b/tests/no_errmsg/SConscript
new file mode 100644
index 0000000..ed46705
--- /dev/null
+++ b/tests/no_errmsg/SConscript
@@ -0,0 +1,27 @@
+# Run the alltypes test case, but compile with PB_NO_ERRMSG=1
+
+Import("env")
+
+# Take copy of the files for custom build.
+c = Copy("$TARGET", "$SOURCE")
+env.Command("alltypes.pb.h", "$BUILD/alltypes/alltypes.pb.h", c)
+env.Command("alltypes.pb.c", "$BUILD/alltypes/alltypes.pb.c", c)
+env.Command("encode_alltypes.c", "$BUILD/alltypes/encode_alltypes.c", c)
+env.Command("decode_alltypes.c", "$BUILD/alltypes/decode_alltypes.c", c)
+
+# Define the compilation options
+opts = env.Clone()
+opts.Append(CPPDEFINES = {'PB_NO_ERRMSG': 1})
+
+# Build new version of core
+strict = opts.Clone()
+strict.Append(CFLAGS = strict['CORECFLAGS'])
+strict.Object("pb_decode_noerr.o", "$NANOPB/pb_decode.c")
+strict.Object("pb_encode_noerr.o", "$NANOPB/pb_encode.c")
+
+# Now build and run the test normally.
+enc = opts.Program(["encode_alltypes.c", "alltypes.pb.c", "pb_encode_noerr.o"])
+dec = opts.Program(["decode_alltypes.c", "alltypes.pb.c", "pb_decode_noerr.o"])
+
+env.RunTest(enc)
+env.RunTest([dec, "encode_alltypes.output"])
diff --git a/tests/no_messages/SConscript b/tests/no_messages/SConscript
new file mode 100644
index 0000000..6492e2c
--- /dev/null
+++ b/tests/no_messages/SConscript
@@ -0,0 +1,7 @@
+# Test that a .proto file without any messages compiles fine.
+
+Import("env")
+
+env.NanopbProto("no_messages")
+env.Object('no_messages.pb.c')
+
diff --git a/tests/no_messages/no_messages.proto b/tests/no_messages/no_messages.proto
new file mode 100644
index 0000000..279216b
--- /dev/null
+++ b/tests/no_messages/no_messages.proto
@@ -0,0 +1,7 @@
+/* Test that a file without any messages works. */
+
+enum Test {
+ First = 1;
+}
+
+
diff --git a/tests/options/SConscript b/tests/options/SConscript
new file mode 100644
index 0000000..89a00fa
--- /dev/null
+++ b/tests/options/SConscript
@@ -0,0 +1,9 @@
+# Test that the generator options work as expected.
+
+Import("env")
+
+env.NanopbProto("options")
+env.Object('options.pb.c')
+
+env.Match(['options.pb.h', 'options.expected'])
+
diff --git a/tests/options/options.expected b/tests/options/options.expected
new file mode 100644
index 0000000..e6179a2
--- /dev/null
+++ b/tests/options/options.expected
@@ -0,0 +1,7 @@
+char filesize\[20\];
+char msgsize\[30\];
+char fieldsize\[40\];
+pb_callback_t int32_callback;
+\sEnumValue1 = 1
+Message5_EnumValue1
+} pb_packed my_packed_struct;
diff --git a/tests/options/options.proto b/tests/options/options.proto
new file mode 100644
index 0000000..b5badcf
--- /dev/null
+++ b/tests/options/options.proto
@@ -0,0 +1,73 @@
+/* Test nanopb option parsing.
+ * options.expected lists the patterns that are searched for in the output.
+ */
+
+import "nanopb.proto";
+
+// File level options
+option (nanopb_fileopt).max_size = 20;
+
+message Message1
+{
+ required string filesize = 1;
+}
+
+// Message level options
+message Message2
+{
+ option (nanopb_msgopt).max_size = 30;
+ required string msgsize = 1;
+}
+
+// Field level options
+message Message3
+{
+ required string fieldsize = 1 [(nanopb).max_size = 40];
+}
+
+// Forced callback field
+message Message4
+{
+ required int32 int32_callback = 1 [(nanopb).type = FT_CALLBACK];
+}
+
+// Short enum names
+enum Enum1
+{
+ option (nanopb_enumopt).long_names = false;
+ EnumValue1 = 1;
+ EnumValue2 = 2;
+}
+
+message EnumTest
+{
+ required Enum1 field = 1 [default = EnumValue2];
+}
+
+// Short enum names inside message
+message Message5
+{
+ enum Enum2
+ {
+ option (nanopb_enumopt).long_names = false;
+ EnumValue1 = 1;
+ }
+ required Enum2 field = 1 [default = EnumValue1];
+}
+
+// Packed structure
+message my_packed_struct
+{
+ option (nanopb_msgopt).packed_struct = true;
+ optional int32 myfield = 1;
+}
+
+// Message with ignored field
+// Note: doesn't really test if the field is missing in the output,
+// but atleast tests that the output compiles.
+message Message6
+{
+ required int32 field1 = 1;
+ optional int32 field2 = 2 [(nanopb).type = FT_IGNORE];
+}
+
diff --git a/tests/package_name/SConscript b/tests/package_name/SConscript
new file mode 100644
index 0000000..8f1b902
--- /dev/null
+++ b/tests/package_name/SConscript
@@ -0,0 +1,36 @@
+# Check that alltypes test case works also when the .proto file defines
+# a package name.
+
+Import("env")
+
+# Build a modified alltypes.proto
+def modify_proto(target, source, env):
+ '''Add a "package test.package;" directive to the beginning of the .proto file.'''
+ data = open(str(source[0]), 'r').read()
+ open(str(target[0]), 'w').write("package test.package;\n\n" + data)
+ return 0
+
+env.Command("alltypes.proto", "#alltypes/alltypes.proto", modify_proto)
+env.Command("alltypes.options", "#alltypes/alltypes.options", Copy("$TARGET", "$SOURCE"))
+env.NanopbProto(["alltypes", "alltypes.options"])
+
+# Build a modified encode_alltypes.c
+def modify_c(target, source, env):
+ '''Add package name to type names in .c file.'''
+
+ data = open(str(source[0]), 'r').read()
+
+ type_names = ['AllTypes', 'MyEnum', 'HugeEnum']
+ for name in type_names:
+ data = data.replace(name, 'test_package_' + name)
+
+ open(str(target[0]), 'w').write(data)
+ return 0
+env.Command("encode_alltypes.c", "#alltypes/encode_alltypes.c", modify_c)
+
+# Encode and compare results to original alltypes testcase
+enc = env.Program(["encode_alltypes.c", "alltypes.pb.c", "$COMMON/pb_encode.o"])
+refdec = "$BUILD/alltypes/decode_alltypes$PROGSUFFIX"
+env.RunTest(enc)
+env.Compare(["encode_alltypes.output", "$BUILD/alltypes/encode_alltypes.output"])
+
diff --git a/tests/site_scons/site_init.py b/tests/site_scons/site_init.py
new file mode 100644
index 0000000..5fb06d6
--- /dev/null
+++ b/tests/site_scons/site_init.py
@@ -0,0 +1,98 @@
+import subprocess
+import sys
+import re
+
+try:
+ # Make terminal colors work on windows
+ import colorama
+ colorama.init()
+except ImportError:
+ pass
+
+def add_nanopb_builders(env):
+ '''Add the necessary builder commands for nanopb tests.'''
+
+ # Build command that runs a test program and saves the output
+ def run_test(target, source, env):
+ if len(source) > 1:
+ infile = open(str(source[1]))
+ else:
+ infile = None
+
+ if env.has_key("COMMAND"):
+ args = [env["COMMAND"]]
+ else:
+ args = [str(source[0])]
+
+ if env.has_key('ARGS'):
+ args.extend(env['ARGS'])
+
+ print 'Command line: ' + str(args)
+ pipe = subprocess.Popen(args,
+ stdin = infile,
+ stdout = open(str(target[0]), 'w'),
+ stderr = sys.stderr)
+ result = pipe.wait()
+ if result == 0:
+ print '\033[32m[ OK ]\033[0m Ran ' + args[0]
+ else:
+ print '\033[31m[FAIL]\033[0m Program ' + args[0] + ' returned ' + str(result)
+ return result
+
+ run_test_builder = Builder(action = run_test,
+ suffix = '.output')
+ env.Append(BUILDERS = {'RunTest': run_test_builder})
+
+ # Build command that decodes a message using protoc
+ def decode_actions(source, target, env, for_signature):
+ esc = env['ESCAPE']
+ dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']])
+ return '$PROTOC $PROTOCFLAGS %s --decode=%s %s <%s >%s' % (
+ dirs, env['MESSAGE'], esc(str(source[1])), esc(str(source[0])), esc(str(target[0])))
+
+ decode_builder = Builder(generator = decode_actions,
+ suffix = '.decoded')
+ env.Append(BUILDERS = {'Decode': decode_builder})
+
+ # Build command that encodes a message using protoc
+ def encode_actions(source, target, env, for_signature):
+ esc = env['ESCAPE']
+ dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']])
+ return '$PROTOC $PROTOCFLAGS %s --encode=%s %s <%s >%s' % (
+ dirs, env['MESSAGE'], esc(str(source[1])), esc(str(source[0])), esc(str(target[0])))
+
+ encode_builder = Builder(generator = encode_actions,
+ suffix = '.encoded')
+ env.Append(BUILDERS = {'Encode': encode_builder})
+
+ # Build command that asserts that two files be equal
+ def compare_files(target, source, env):
+ data1 = open(str(source[0]), 'rb').read()
+ data2 = open(str(source[1]), 'rb').read()
+ if data1 == data2:
+ print '\033[32m[ OK ]\033[0m Files equal: ' + str(source[0]) + ' and ' + str(source[1])
+ return 0
+ else:
+ print '\033[31m[FAIL]\033[0m Files differ: ' + str(source[0]) + ' and ' + str(source[1])
+ return 1
+
+ compare_builder = Builder(action = compare_files,
+ suffix = '.equal')
+ env.Append(BUILDERS = {'Compare': compare_builder})
+
+ # Build command that checks that each pattern in source2 is found in source1.
+ def match_files(target, source, env):
+ data = open(str(source[0]), 'rU').read()
+ patterns = open(str(source[1]))
+ for pattern in patterns:
+ if pattern.strip() and not re.search(pattern.strip(), data, re.MULTILINE):
+ print '\033[31m[FAIL]\033[0m Pattern not found in ' + str(source[0]) + ': ' + pattern
+ return 1
+ else:
+ print '\033[32m[ OK ]\033[0m All patterns found in ' + str(source[0])
+ return 0
+
+ match_builder = Builder(action = match_files, suffix = '.matched')
+ env.Append(BUILDERS = {'Match': match_builder})
+
+
diff --git a/tests/site_scons/site_tools/nanopb.py b/tests/site_scons/site_tools/nanopb.py
new file mode 100644
index 0000000..b3e58fa
--- /dev/null
+++ b/tests/site_scons/site_tools/nanopb.py
@@ -0,0 +1,126 @@
+'''
+Scons Builder for nanopb .proto definitions.
+
+This tool will locate the nanopb generator and use it to generate .pb.c and
+.pb.h files from the .proto files.
+
+Basic example
+-------------
+# Build myproto.pb.c and myproto.pb.h from myproto.proto
+myproto = env.NanopbProto("myproto")
+
+# Link nanopb core to the program
+env.Append(CPPPATH = "$NANOB")
+myprog = env.Program(["myprog.c", myproto, "$NANOPB/pb_encode.c", "$NANOPB/pb_decode.c"])
+
+Configuration options
+---------------------
+Normally, this script is used in the test environment of nanopb and it locates
+the nanopb generator by a relative path. If this script is used in another
+application, the path to nanopb root directory has to be defined:
+
+env.SetDefault(NANOPB = "path/to/nanopb")
+
+Additionally, the path to protoc and the options to give to protoc can be
+defined manually:
+
+env.SetDefault(PROTOC = "path/to/protoc")
+env.SetDefault(PROTOCFLAGS = "--plugin=protoc-gen-nanopb=path/to/protoc-gen-nanopb")
+'''
+
+import SCons.Action
+import SCons.Builder
+import SCons.Util
+import os.path
+
+class NanopbWarning(SCons.Warnings.Warning):
+ pass
+SCons.Warnings.enableWarningClass(NanopbWarning)
+
+def _detect_nanopb(env):
+ '''Find the path to nanopb root directory.'''
+ if env.has_key('NANOPB'):
+ # Use nanopb dir given by user
+ return env['NANOPB']
+
+ p = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
+ if os.path.isdir(p) and os.path.isfile(os.path.join(p, 'pb.h')):
+ # Assume we are running under tests/site_scons/site_tools
+ return p
+
+ raise SCons.Errors.StopError(NanopbWarning,
+ "Could not find the nanopb root directory")
+
+def _detect_protoc(env):
+ '''Find the path to the protoc compiler.'''
+ if env.has_key('PROTOC'):
+ # Use protoc defined by user
+ return env['PROTOC']
+
+ n = _detect_nanopb(env)
+ p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX'])
+ if os.path.exists(p1):
+ # Use protoc bundled with binary package
+ return env['ESCAPE'](p1)
+
+ p = env.WhereIs('protoc')
+ if p:
+ # Use protoc from path
+ return env['ESCAPE'](p)
+
+ raise SCons.Errors.StopError(NanopbWarning,
+ "Could not find the protoc compiler")
+
+def _detect_protocflags(env):
+ '''Find the options to use for protoc.'''
+ if env.has_key('PROTOCFLAGS'):
+ return env['PROTOCFLAGS']
+
+ p = _detect_protoc(env)
+ n = _detect_nanopb(env)
+ p1 = os.path.join(n, 'generator-bin', 'protoc' + env['PROGSUFFIX'])
+ if p == env['ESCAPE'](p1):
+ # Using the bundled protoc, no options needed
+ return ''
+
+ e = env['ESCAPE']
+ if env['PLATFORM'] == 'win32':
+ return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb.bat'))
+ else:
+ return e('--plugin=protoc-gen-nanopb=' + os.path.join(n, 'generator', 'protoc-gen-nanopb'))
+
+def _nanopb_proto_actions(source, target, env, for_signature):
+ esc = env['ESCAPE']
+ dirs = ' '.join(['-I' + esc(env.GetBuildPath(d)) for d in env['PROTOCPATH']])
+ return '$PROTOC $PROTOCFLAGS %s --nanopb_out=. %s' % (dirs, esc(str(source[0])))
+
+def _nanopb_proto_emitter(target, source, env):
+ basename = os.path.splitext(str(source[0]))[0]
+ target.append(basename + '.pb.h')
+
+ if os.path.exists(basename + '.options'):
+ source.append(basename + '.options')
+
+ return target, source
+
+_nanopb_proto_builder = SCons.Builder.Builder(
+ generator = _nanopb_proto_actions,
+ suffix = '.pb.c',
+ src_suffix = '.proto',
+ emitter = _nanopb_proto_emitter)
+
+def generate(env):
+ '''Add Builder for nanopb protos.'''
+
+ env['NANOPB'] = _detect_nanopb(env)
+ env['PROTOC'] = _detect_protoc(env)
+ env['PROTOCFLAGS'] = _detect_protocflags(env)
+
+ env.SetDefault(PROTOCPATH = ['.', os.path.join(env['NANOPB'], 'generator', 'proto')])
+
+ env.SetDefault(NANOPB_PROTO_CMD = '$PROTOC $PROTOC_OPTS --nanopb_out=. $SOURCE')
+ env['BUILDERS']['NanopbProto'] = _nanopb_proto_builder
+
+def exists(env):
+ return _detect_protoc(env) and _detect_protoc_opts(env)
+
diff --git a/tests/special_characters/SConscript b/tests/special_characters/SConscript
new file mode 100644
index 0000000..2309cf2
--- /dev/null
+++ b/tests/special_characters/SConscript
@@ -0,0 +1,6 @@
+# Test that special characters in .proto filenames work.
+
+Import('env')
+
+env.NanopbProto("funny-proto+name has.characters.proto")
+env.Object("funny-proto+name has.characters.pb.c")
diff --git a/tests/special_characters/funny-proto+name has.characters.proto b/tests/special_characters/funny-proto+name has.characters.proto
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/tests/special_characters/funny-proto+name has.characters.proto
diff --git a/tests/splint/SConscript b/tests/splint/SConscript
new file mode 100644
index 0000000..c1432dd
--- /dev/null
+++ b/tests/splint/SConscript
@@ -0,0 +1,13 @@
+# Check the nanopb core using splint
+
+Import('env')
+
+p = env.WhereIs('splint')
+
+if p:
+ env.Command('pb_decode.splint', '$NANOPB/pb_decode.c',
+ 'splint -f splint/splint.rc $SOURCE 2> $TARGET')
+
+ env.Command('pb_encode.splint', '$NANOPB/pb_encode.c',
+ 'splint -f splint/splint.rc $SOURCE 2> $TARGET')
+
diff --git a/tests/splint/splint.rc b/tests/splint/splint.rc
new file mode 100644
index 0000000..421f567
--- /dev/null
+++ b/tests/splint/splint.rc
@@ -0,0 +1,37 @@
++checks
++partial
++matchanyintegral
++strictlib
+-isoreserved # to be fixed in 0.3
+-nullassign
+-predboolint
+-predboolptr
++ptrnegate
+-switchloopbreak
++ignoresigns
+-infloopsuncon
+-type
+
+# splint's memory checks don't quite work without annotations
+-mustfreeonly
+-compmempass
+-nullret
+-observertrans
+-statictrans
+-compdestroy
+-nullpass
+-nullstate
+-compdef
+-usereleased
+-temptrans
+-dependenttrans
+-kepttrans
+-branchstate
+-immediatetrans
+
+# These tests give false positives, compiler typically has
+# better warnings for these.
+-noret
+-noeffect
+-usedef
+