TEST(PBCTest, TestGeneratedCode) { Foo__Person person; foo__person__init(&person); Foo__Person *person2; unsigned char simple_pad[8]; size_t size, size2; unsigned char *packed; ProtobufCBufferSimple bs = PROTOBUF_C_BUFFER_SIMPLE_INIT (NULL, simple_pad); person.name = (char *)"dave b"; person.id = 42; size = foo__person__get_packed_size (NULL, &person); packed = (unsigned char*)malloc(size); ASSERT_TRUE(packed); size2 = foo__person__pack (NULL, &person, packed); EXPECT_EQ(size, size2); foo__person__pack_to_buffer (&person, &bs.base); EXPECT_EQ(bs.len, size); EXPECT_FALSE(memcmp (bs.data, packed, size)); PROTOBUF_C_BUFFER_SIMPLE_CLEAR (&bs); person2 = foo__person__unpack (NULL, size, packed); ASSERT_TRUE(person2); EXPECT_EQ(person2->id, 42); EXPECT_STREQ(person2->name, "dave b"); foo__person__free_unpacked (NULL, person2); free (packed); }
static void load_database (const char *filename) { FILE *fp = fopen (filename, "r"); char buf[2048]; unsigned n_people = 0; unsigned people_alloced = 32; unsigned line_no; Foo__Person *people = xmalloc (sizeof (Foo__Person) * people_alloced); if (fp == NULL) die ("error opening %s: %s", filename, strerror (errno)); line_no = 0; while (fgets (buf, sizeof (buf), fp) != NULL) { line_no++; if (buf[0] == '#') continue; if (is_whitespace (buf)) continue; chomp_trailing_whitespace (buf); if (isspace (buf[0])) { Foo__Person *person; char *start = buf + 1; if (n_people == 0) die ("error on %s, line %u: line began with a space, but no person's name preceded it", filename, line_no); person = people + (n_people - 1); while (*start && isspace (*start)) start++; if (starts_with (start, "id ")) person->id = atoi (peek_next_token (start)); else if (starts_with (start, "email ")) person->email = xstrdup (peek_next_token (start)); else if (starts_with (start, "mobile ") || starts_with (start, "home ") || starts_with (start, "work ")) { Foo__Person__PhoneNumber *pn = xmalloc (sizeof (Foo__Person__PhoneNumber)); Foo__Person__PhoneNumber tmp = FOO__PERSON__PHONE_NUMBER__INIT; tmp.has_type = 1; tmp.type = start[0] == 'm' ? FOO__PERSON__PHONE_TYPE__MOBILE : start[0] == 'h' ? FOO__PERSON__PHONE_TYPE__HOME : FOO__PERSON__PHONE_TYPE__WORK; tmp.number = xstrdup (peek_next_token (start)); person->phone = xrealloc (person->phone, sizeof (Foo__Person__PhoneNumber*) * (person->n_phone+1)); *pn = tmp; person->phone[person->n_phone++] = pn; } else die ("error on %s, line %u: unrecognized field starting with %s", filename, line_no, start); } else { Foo__Person *person; if (n_people == people_alloced) { people_alloced *= 2; people = xrealloc (people, people_alloced * sizeof (Foo__Person)); } person = people + n_people++; foo__person__init (person); person->name = xstrdup (buf); } } if (n_people == 0) die ("empty database: insufficiently interesting to procede"); qsort (people, n_people, sizeof (Foo__Person), compare_persons_by_name); database = people; database_size = n_people; fclose (fp); }