MongoDB C++ Driver mongocxx-3.11.0
Loading...
Searching...
No Matches
Validation

Table of Contents

How to use BSON document validation interfaces.

Basic Usage

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

With Validator

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