[CDRIVER-811] Clearer Design & document on Invalid bson_t Object Created: 26/Aug/15  Updated: 03/May/17  Resolved: 28/Aug/15

Status: Closed
Project: C Driver
Component/s: docs, libbson
Affects Version/s: 1.1.10
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: Peng Xie Assignee: A. Jesse Jiryu Davis
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Related
related to CDRIVER-812 Memory Leak When Using bson_reinit() Closed

 Description   

I was stumped by a bug until the following demo revealed clues:

test.cc

#include <cassert>
#include <cstring>
 
#include <mongoc.h>
 
void log_bson(const bson_t *bson) {
  char *json = bson_as_json(bson, NULL);
  puts(json ? json : "[bson_as_json_error]");
  if (json) bson_free(json);
}
 
int main() {
  bool status;
  bson_t bson = BSON_INITIALIZER;
  bson_t child = BSON_INITIALIZER;
  status = bson_append_document_begin(&bson, "$set", 4, &child);
  assert(status);
  status = bson_append_bool(&child, "foo", 3, true);
  assert(status);
  status = bson_append_document_end(&bson, &child);
  assert(status);
  log_bson(&bson);
  bson_reinit(&child); // <- this line destroy bson object
  //child = BSON_INITIALIZER; <- this seems no hurt, in C++ 11 mode
  log_bson(&bson);
}

The first log_bson(&bson) works fine. But after bson_reinit(&child), bson is destroyed.

The document of bson_append_document_end() says:
"child is invalid after calling this function."

There's a side effect if a user tried to make child valid again in a wrong way (if there is a correct way to do that.)

Yet there are more "invalid" status if bson_append_xxx fail.

It would be nice if there is some document to tell the users how to deal with an invalid bson_t object, or provide some function to save these objects (and us).



 Comments   
Comment by A. Jesse Jiryu Davis [ 28/Aug/15 ]

Glad to hear it.

Comment by Peng Xie [ 28/Aug/15 ]

Yes, indeed.

I got further knowledge and am no longer confused by reading your replies below CDRIVER-812.

Thanks!

Comment by A. Jesse Jiryu Davis [ 27/Aug/15 ]

Does simply calling "bson_init(&child)" instead of "bson_reinit(&child)" accomplish what you want?

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