1BSON_STREAMING_BSON(3) libbson BSON_STREAMING_BSON(3)
2
3
4
6 bson_streaming_bson - Streaming BSON
7
8 bson_reader_t provides a streaming reader which can be initialized with
9 a filedescriptor or memory region. bson_writer_t provides a streaming
10 writer which can be initialized with a memory region. (Streaming BSON
11 to a file descriptor is not yet supported.)
12
14 bson_reader_t provides a convenient API to read sequential BSON docu‐
15 ments from a file-descriptor or memory buffer. The bson_reader_read()
16 function will read forward in the underlying stream and return a bson_t
17 that can be inspected and iterated upon.
18
19 #include <stdio.h>
20 #include <bson/bson.h>
21
22 int
23 main (int argc, char *argv[])
24 {
25 bson_reader_t *reader;
26 const bson_t *doc;
27 bson_error_t error;
28 bool eof;
29
30 reader = bson_reader_new_from_file ("mycollection.bson", &error);
31
32 if (!reader) {
33 fprintf (stderr, "Failed to open file.\n");
34 return 1;
35 }
36
37 while ((doc = bson_reader_read (reader, &eof))) {
38 char *str = bson_as_canonical_extended_json (doc, NULL);
39 printf ("%s\n", str);
40 bson_free (str);
41 }
42
43 if (!eof) {
44 fprintf (stderr,
45 "corrupted bson document found at %u\n",
46 (unsigned) bson_reader_tell (reader));
47 }
48
49 bson_reader_destroy (reader);
50
51 return 0;
52 }
53
54 See bson_reader_new_from_fd(), bson_reader_new_from_file(), and
55 bson_reader_new_from_data() for more information.
56
58 bson_writer_t provides a convenient API to write a sequence of BSON
59 documents to a memory buffer that can grow with realloc(). The
60 bson_writer_begin() and bson_writer_end() functions will manage the un‐
61 derlying buffer while building the sequence of documents.
62
63 This could also be useful if you want to write to a network packet
64 while serializing the documents from a higher level language, (but do
65 so just after the packets header).
66
67 #include <stdio.h>
68 #include <bson/bson.h>
69 #include <assert.h>
70
71 int
72 main (int argc, char *argv[])
73 {
74 bson_writer_t *writer;
75 bson_t *doc;
76 uint8_t *buf = NULL;
77 size_t buflen = 0;
78 bool r;
79 int i;
80
81 writer = bson_writer_new (&buf, &buflen, 0, bson_realloc_ctx, NULL);
82
83 for (i = 0; i < 10000; i++) {
84 r = bson_writer_begin (writer, &doc);
85 assert (r);
86
87 r = BSON_APPEND_INT32 (doc, "i", i);
88 assert (r);
89
90 bson_writer_end (writer);
91 }
92
93 bson_free (buf);
94
95 return 0;
96 }
97
98 See bson_writer_new() for more information.
99
101 MongoDB, Inc
102
104 2017-present, MongoDB, Inc
105
106
107
108
1091.23.1 Oct 20, 2022 BSON_STREAMING_BSON(3)