Loading...
Searching...
No Matches
Validation

How to use BSON document validation interfaces.

# Basic Usage

void example() {
{
std::uint8_t bytes[1]{}; // Invalid.
EXPECT(!bsoncxx::validate(bytes, sizeof(bytes)));
std::size_t offset;
EXPECT(!bsoncxx::validate(bytes, sizeof(bytes), bsoncxx::validator{}, &offset));
// Set to `0` for an invalid BSON document.
EXPECT(offset == 0u);
}
bsoncxx::document::value owner = bsoncxx::from_json(R"({"x": 1})");
std::uint8_t const* data = owner.data();
std::size_t const length = owner.length();
{
auto doc_opt = bsoncxx::validate(data, length);
EXPECT(doc_opt);
bsoncxx::document::view doc = *doc_opt;
EXPECT(doc.data() == data);
EXPECT(doc.length() == length);
EXPECT(doc == owner.view());
}
{
bsoncxx::validator options;
std::size_t offset = 123u;
EXPECT(bsoncxx::validate(data, length) == bsoncxx::validate(data, length, options, &offset));
// Set to 0 when valid.
EXPECT(offset == 0u);
}
}

# With Validator

// {
// "x": "a\0b",
// "a.b": 1,
// "v": {
// "$numberInt": "123"
// }
// }
void example(std::uint8_t const* bytes, std::size_t length) {
// Default options.
{
bsoncxx::validator options;
std::size_t offset;
EXPECT(bsoncxx::validate(bytes, length, options, &offset));
}
// Validate UTF-8 strings.
{
bsoncxx::validator options;
std::size_t offset;
options.check_utf8(true);
EXPECT(!bsoncxx::validate(bytes, length, options, &offset));
// Offset of `"x": "\0"` relative to start of the document.
EXPECT(offset == 4u);
options.check_utf8_allow_null(true);
EXPECT(bsoncxx::validate(bytes, length, options, &offset));
}
// Validate dot keys.
{
bsoncxx::validator options;
std::size_t offset;
options.check_dot_keys(true);
EXPECT(!bsoncxx::validate(bytes, length, options, &offset));
// Offset of `"a.b": 1` relative to start of the document.
EXPECT(offset == 15u);
}
// Validate dollar keys.
{
bsoncxx::validator options;
std::size_t offset;
options.check_dollar_keys(true);
EXPECT(!bsoncxx::validate(bytes, length, options, &offset));
// Offset of `"$numberInt": "123"` relative to start of the document.
EXPECT(offset == 31u);
}
}