Skip to content

Commit

Permalink
Make sure we can write to a file
Browse files Browse the repository at this point in the history
  • Loading branch information
liuzicheng1987 committed Jan 17, 2024
1 parent 6f16f50 commit dee18b4
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 16 deletions.
2 changes: 1 addition & 1 deletion include/rfl/bson/load.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#define RFL_BSON_LOAD_HPP_

#include "../Result.hpp"
#include "../io/load_string.hpp"
#include "../io/load_bytes.hpp"
#include "read.hpp"

namespace rfl {
Expand Down
2 changes: 1 addition & 1 deletion include/rfl/bson/save.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
#include <string>

#include "../Result.hpp"
#include "../io/save_string.hpp"
#include "../io/save_bytes.hpp"
#include "write.hpp"

namespace rfl {
Expand Down
30 changes: 16 additions & 14 deletions include/rfl/bson/write.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,50 @@
#include <ostream>
#include <sstream>
#include <string>
#include <utility>

#include "../parsing/Parent.hpp"
#include "Parser.hpp"

namespace rfl {
namespace bson {

/// Returns BSON bytes.
/// Returns BSON bytes. Careful: It is the responsibility of the caller to call
/// bson_free on the returned pointer.
template <class T>
std::vector<char> write(const T& _obj) {
std::pair<uint8_t*, size_t> to_buffer(const T& _obj) noexcept {
using ParentType = parsing::Parent<Writer>;
bson_t* doc;
bson_t* doc = nullptr;
uint8_t* buf = nullptr;
size_t buflen = 0;

bson_writer_t* bson_writer =
bson_writer_new(&buf, &buflen, 0, bson_realloc_ctx, NULL);

bson_writer_begin(bson_writer, &doc);

const auto rfl_writer = Writer(doc);

Parser<T>::write(rfl_writer, _obj, typename ParentType::Root{});

bson_writer_end(bson_writer);

const auto len = bson_writer_get_length(bson_writer);

bson_writer_destroy(bson_writer);
return std::make_pair(buf, len);
}

/// Returns BSON bytes.
template <class T>
std::vector<char> write(const T& _obj) noexcept {
auto [buf, len] = to_buffer(_obj);
const auto result = std::vector<char>(reinterpret_cast<char*>(buf),
reinterpret_cast<char*>(buf) + len);

bson_free(buf);

return result;
}

/// Writes a BSON into an ostream.
template <class T>
std::ostream& write(const T& _obj, std::ostream& _stream) {
// TODO
std::ostream& write(const T& _obj, std::ostream& _stream) noexcept {
auto [buf, len] = to_buffer(_obj);
_stream.write(reinterpret_cast<const char*>(buf), len);
bson_free(buf);
return _stream;
}

} // namespace bson
Expand Down

0 comments on commit dee18b4

Please sign in to comment.