Skip to content

Commit dee18b4

Browse files
Make sure we can write to a file
1 parent 6f16f50 commit dee18b4

File tree

3 files changed

+18
-16
lines changed

3 files changed

+18
-16
lines changed

include/rfl/bson/load.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
#define RFL_BSON_LOAD_HPP_
33

44
#include "../Result.hpp"
5-
#include "../io/load_string.hpp"
5+
#include "../io/load_bytes.hpp"
66
#include "read.hpp"
77

88
namespace rfl {

include/rfl/bson/save.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
#include <string>
77

88
#include "../Result.hpp"
9-
#include "../io/save_string.hpp"
9+
#include "../io/save_bytes.hpp"
1010
#include "write.hpp"
1111

1212
namespace rfl {

include/rfl/bson/write.hpp

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,48 +6,50 @@
66
#include <ostream>
77
#include <sstream>
88
#include <string>
9+
#include <utility>
910

1011
#include "../parsing/Parent.hpp"
1112
#include "Parser.hpp"
1213

1314
namespace rfl {
1415
namespace bson {
1516

16-
/// Returns BSON bytes.
17+
/// Returns BSON bytes. Careful: It is the responsibility of the caller to call
18+
/// bson_free on the returned pointer.
1719
template <class T>
18-
std::vector<char> write(const T& _obj) {
20+
std::pair<uint8_t*, size_t> to_buffer(const T& _obj) noexcept {
1921
using ParentType = parsing::Parent<Writer>;
20-
bson_t* doc;
22+
bson_t* doc = nullptr;
2123
uint8_t* buf = nullptr;
2224
size_t buflen = 0;
23-
2425
bson_writer_t* bson_writer =
2526
bson_writer_new(&buf, &buflen, 0, bson_realloc_ctx, NULL);
26-
2727
bson_writer_begin(bson_writer, &doc);
28-
2928
const auto rfl_writer = Writer(doc);
30-
3129
Parser<T>::write(rfl_writer, _obj, typename ParentType::Root{});
32-
3330
bson_writer_end(bson_writer);
34-
3531
const auto len = bson_writer_get_length(bson_writer);
36-
3732
bson_writer_destroy(bson_writer);
33+
return std::make_pair(buf, len);
34+
}
3835

36+
/// Returns BSON bytes.
37+
template <class T>
38+
std::vector<char> write(const T& _obj) noexcept {
39+
auto [buf, len] = to_buffer(_obj);
3940
const auto result = std::vector<char>(reinterpret_cast<char*>(buf),
4041
reinterpret_cast<char*>(buf) + len);
41-
4242
bson_free(buf);
43-
4443
return result;
4544
}
4645

4746
/// Writes a BSON into an ostream.
4847
template <class T>
49-
std::ostream& write(const T& _obj, std::ostream& _stream) {
50-
// TODO
48+
std::ostream& write(const T& _obj, std::ostream& _stream) noexcept {
49+
auto [buf, len] = to_buffer(_obj);
50+
_stream.write(reinterpret_cast<const char*>(buf), len);
51+
bson_free(buf);
52+
return _stream;
5153
}
5254

5355
} // namespace bson

0 commit comments

Comments
 (0)