Uploaded image for project: 'C Driver'
  1. C Driver
  2. CDRIVER-811

Clearer Design & document on Invalid bson_t Object

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: 1.1.10
    • Component/s: Docs, libbson
    • None

      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).

            Assignee:
            jesse@mongodb.com A. Jesse Jiryu Davis
            Reporter:
            mapx Peng Xie
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: