#5481·poco

MongoDB: read every BSON element type through Element::read with a byte budget

Author: matejkCreated Sep 14, 2026Updated Sep 14, 2026
Labelsenhancement

PR #5478 bounds every length read from a server reply against the bytes left in the enclosing document. After that PR, BSONReader holds the bounded helpers (readCString, readString, readBinary, readFixed with an Int32& available budget), and both Document::readValue and the public BSONReader::read<T> specializations use them. One duplication remains: Document::readValue dispatches on the type byte with its own switch, because the virtual Element::read(BinaryReader&) has no way to receive the byte budget, so the library no longer calls Element::read at all.

Proposal for 2.0, where the ABI may change:

  • Give the private virtual Element::read the budget, for example read(BSONReader& reader, Int32& available) (it is private with friend class Document, so no user code calls it).
  • Document::readImpl goes back to creating the element for the type byte and calling element->read(...) for every type; readValue's switch and the fixedElement helper go away, and each BSONReader::read<T> specialization becomes the single implementation of its type.
  • Re-measure BSON_MAX_DEPTH afterwards: the recursion for nested documents then passes through ConcreteElement<Document::Ptr>::read and BSONReader::read<Document::Ptr>, about two small frames more per level (the current limit of 512 was measured with direct recursion on a 512 KiB thread stack).

Costs: a virtual signature change (every element header), and the change must not be cherry-picked to 1.15.