MongoDB C++ Driver mongocxx-4.0.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.
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);
}
const std::uint8_t* data = owner.data();
const std::size_t 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());
}
{
std::size_t offset = 123u;
EXPECT(bsoncxx::validate(data, length) ==
bsoncxx::validate(data, length, options, &offset));
// Not set when valid.
EXPECT(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;
EXPECT(bsoncxx::validate(bytes, length, options, &offset));
}
// Validate UTF-8 strings.
{
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.
{
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.
{
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 sub-document. (CDRIVER-5710)
EXPECT(offset == 4u);
}
}