[CDRIVER-233] how to generate bson with unfinished data and append some more element here? Created: 11/Aug/13  Updated: 03/May/17  Resolved: 09/Nov/13

Status: Closed
Project: C Driver
Component/s: None
Affects Version/s: 0.8.1
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: smallrui Assignee: Gary Murakami
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

win7 32



 Description   

I code it like this below, but no one can work.
========================================================
bson b2[1];

char * buffer;
int size;

size = bson_size(b);
buffer = (char *)malloc(size);
memcpy(buffer, bson_data(b), size);

//bson_init_unfinished_data(b2, buffer, size, 0); // no effect
//bson_init_unfinished_data(b2, buffer, size, 1); // with crash
//bson_init_finished_data_with_copy(b2, bson_data(b)); // no effect
bson_append_int(b2, "age", 18);

bson_finish( b2 );
bson_print( b2 );

======================================================

best regard and thanks.



 Comments   
Comment by Christian Hergert [ 09/Nov/13 ]

Hi,

You can do this with libbson, which can be found at https://github.com/mongodb/libbson

Here is a small example. You can compile it with:

gcc -Wall -g -o test test.c $(pkg-config --cflags --libs libbson-1.0)

#include <assert.h>
#include <bson.h>
 
int
main (int argc,
      char *argv[])
{
   bson_t b;
   bson_t sub;
   char *str;
 
   bson_init(&b);
 
   bson_append_document_begin(&b, "foo", -1, &sub);
   bson_append_int32(&sub, "a", -1, 123);
   bson_append_int32(&sub, "b", -1, 456);
   bson_append_document_end(&b, &sub);
 
   str = bson_as_json(&b, NULL);
   printf("%s\n", str);
   assert(!strcmp(str, "{ \"foo\" : { \"a\" : 123, \"b\" : 456 } }"));
   bson_free(str);
 
   bson_destroy(&b);
 
   return 0;
}

Generated at Wed Feb 07 21:08:50 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.