Zero-copy DER INTEGER: point at the positive, compute the negative
A DER INTEGER carries no width. A certificate serial number can be wider than any integer type your platform has, and it is written as two's complement, so the digits of a negative value are not in the document at all. A reader that allocates nothing cannot hand you "the number" uniformly: for one sign the bytes are already sitting there to point at, and for the other they have to be produced somewhere. The asymmetry lives in the format itself, so the API has one honest shape available and that is the one it takes.
I write this from the reading side. In payments and crypto work since 2018 I have spent more time parsing other people's encodings than designing my own, and the integers that matter (serial numbers, key material, ASN.1-wrapped amounts) are routinely wider than a register and not under my control. derstrict is where I keep that reasoning as code: a header-only DER reader that owns no memory and refuses everything DER already forbids.
The one encoding, and the two bytes that break it#
BER lets you spell the same value several ways; DER picks exactly one. For integers, the one is the shortest two's complement representation. That rule is short enough to state as two refusals:
- A leading
0x00is a sign byte only in front of a byte whose top bit is set. Anywhere else it is padding. - A leading
0xFFis sign extension only in front of a byte whose top bit is clear. Anywhere else it carries information.
0x00 0x01 and 0x01 are both 1. 0xFF 0x80 and 0x80 are both -128. Accept the longer spelling of either and one number now has two encodings: as the README puts it, a reader that accepts both spellings accepts two documents where DER defines one. That is the mechanism behind a whole genre of certificate bugs. The cryptography in them is fine. What breaks is two parsers disagreeing about what a document says, because one of them quietly normalised.
So the check runs before any value comes back to you. integer() reads the element through expect(tag::integer) and then runs minimal() on its content. minimal() fails with error::empty_integer for zero content bytes, accepts any single byte, and rejects the two spellings above under their own names:
// tests/test_integer.cpp: integer_of() wraps content bytes in an INTEGER,
// over() opens a parser across a buffer.
const refusal cases[] = {
{integer_of({}), error::empty_integer},
{integer_of({0x00, 0x01}), error::padded_integer},
{integer_of({0x00, 0x7F}), error::padded_integer},
{integer_of({0x00, 0x00, 0x80}), error::padded_integer},
{integer_of({0xFF, 0x80}), error::sign_extended_integer},
{integer_of({0xFF, 0xFF}), error::sign_extended_integer},
{integer_of({0xFF, 0xFF, 0x01}), error::sign_extended_integer},
};
for (const auto& c : cases) {
auto p = over(c.document);
CHECK(!p.integer().has_value());
CHECK(p.failure() == c.expected);
}And the near misses get accepted, because there the byte is doing work:
const auto sign_byte = integer_of({0x00, 0x80}); // +128, the zero is the sign
auto p = over(sign_byte);
CHECK(p.integer().has_value());
const auto extended = integer_of({0xFF, 0x7F}); // -129, the 0xFF is the value
auto q = over(extended);
CHECK(q.integer().has_value());The alternative, strip the padding and carry on, is the thing I will not do. A signature covers the bytes on the wire. A reader that repairs a document is checking a document nobody wrote and nobody signed, so the thing it verified and the thing it read are no longer the same object. Refuse, not repair.
The refusal is also what makes the rest of this possible. Once no second encoding can get past the front door, the content bytes are a canonical number, and a canonical number can be described by a pointer and a length instead of being rebuilt.
A non-negative magnitude is already in the document#
integer() returns a big_integer: a pointer and a size into your buffer, with nothing copied. negative() tests the top bit of the first byte. is_zero() is true only for the single byte 0x00. And for a non-negative value, magnitude() returns the bytes where they lie, stepping past a leading 0x00 sign byte:
// tests/test_derstrict.cpp
const auto data = bytes({0x02, 0x09, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF});
auto p = over(data);
const auto number = p.integer();
CHECK(number.has_value());
CHECK(!number->negative());
CHECK(number->magnitude_size() == 8u);
CHECK(number->magnitude() == data.data() + 3); // past the sign byte, not a copy of it
CHECK(p.at_end());That data.data() + 3 is the whole design in one assertion. The nine content bytes are a sign byte and eight magnitude bytes, so the view hands back a pointer three bytes into the document (identifier, length, sign byte) and a width of eight. No allocation, no std::vector, no fixed-size scratch array hiding a width limit. If you want to hash the serial number, compare it, or pass it to a bignum library, you get the bytes you would have copied anyway.
Zero is the degenerate case and stays consistent: is_zero() is true, negative() is false, and magnitude_size() is 0u. A number with no magnitude bytes is exactly what zero is.
A negative magnitude is nowhere in the document#
For a negative value the document holds the two's complement, not the magnitude. The bytes of 255 appear nowhere in the encoding of -255. So magnitude() returns null for a negative value: there is nothing to point at, and faking a pointer would mean allocating a buffer the library has no business owning.
What the view can still answer for free is how wide the magnitude will be, and that width is not the width of the encoding. Negation loses the top byte exactly when that byte is 0xFF and no carry out of the lower bytes reaches it. Negate 0xFF 0x01 and you get 0x00 0xFF, so the top byte vanishes and -255 is one byte wide. Negate 0xFF 0x00 and you get 0x01 0x00, the carry lands in the top byte, and -256 stays two. magnitude_size() encodes that rule: a negative value drops its top byte only when that byte is 0xFF and some lower byte is not zero.
You then supply the buffer, and magnitude_into() negates into it:
// tests/test_integer.cpp
const negated cases[] = {
{integer_of({0xFF}), bytes({0x01})}, // -1
{integer_of({0x80}), bytes({0x80})}, // -128
{integer_of({0xFF, 0x01}), bytes({0xFF})}, // -255, one byte wide
{integer_of({0xFF, 0x00}), bytes({0x01, 0x00})}, // -256, and still two
{integer_of({0xFF, 0x7F}), bytes({0x81})}, // -129
{integer_of({0x80, 0x00}), bytes({0x80, 0x00})}, // -32768
};
for (const auto& c : cases) {
auto p = over(c.document);
const auto number = p.integer();
CHECK(number->negative());
CHECK(number->magnitude() == nullptr);
CHECK(number->magnitude_size() == c.magnitude.size());
std::vector<std::uint8_t> written(c.magnitude.size(), 0xCC);
CHECK(number->magnitude_into(written.data(), written.size()));
CHECK(written == c.magnitude);
}A too-small buffer is refused whole rather than filled part of the way, which matters because a partially written magnitude is a wrong number that looks like a right one:
const auto data = integer_of({0xFF, 0x00}); // -256, two magnitude bytes
auto p = over(data);
const auto number = p.integer();
std::uint8_t out[2] = {0xCC, 0xCC};
CHECK(!number->magnitude_into(out, 1));
CHECK(out[0] == 0xCC);
CHECK(out[1] == 0xCC);
CHECK(number->magnitude_into(out, sizeof(out)));
CHECK(out[0] == 0x01);
CHECK(out[1] == 0x00);So the cost of owning no memory is a two-step call on the negative path: ask the width, then supply the buffer. I took that trade deliberately. The sign asymmetry exists in the format, and an API that hides it has to allocate, or cap the width, or copy every positive value to make the two paths look alike. Copying every serial number to spare the rare negative integer a second call is the wrong way round...
Where a plain integer type still fits#
Most callers do not want a view, they want a number. unsigned_integer() is built on the same checked view and adds two refusals of its own: error::negative_integer for a negative value, and error::length_too_large when the magnitude is wider than a std::uint64_t:
const auto widest = integer_of({0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF});
auto p = over(widest);
CHECK(p.unsigned_integer() == 0xFFFFFFFFFFFFFFFFull);
const auto wider = integer_of({0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00});
auto s = over(wider);
CHECK(!s.unsigned_integer().has_value());
CHECK(s.failure() == error::length_too_large);
const auto below_zero = integer_of({0xFF});
auto t = over(below_zero);
CHECK(!t.unsigned_integer().has_value());
CHECK(t.failure() == error::negative_integer);Note what length_too_large is and is not. The nine-byte value whose first byte is a sign byte reads fine, because its magnitude is eight bytes. The nine-byte value whose first byte is 0x01 is a perfectly well-formed DER integer that this result type cannot hold, a limit of the destination rather than a defect in the document. That is why the view exists alongside it. A reader should not have to call a number malformed because it does not fit.
What I would do differently#
One thing I would revisit is that magnitude() returning null now answers two questions at once: the value is negative, or it is zero and has no magnitude bytes. Both are legitimate, both are documented, and the correct order of checks is sign first, then width. But a null return that means two things is the kind of detail a caller gets wrong once, and I would probably rather have the type make the order impossible to invert than rely on you remembering it.
What I would keep without hesitation is the ordering of the whole thing: refuse the second encoding first, and only then describe the value. Every zero-copy property above depends on the content bytes being canonical. A reader that normalises first and views afterwards is handing out a pointer to bytes it has already decided to reinterpret, and that is the exact position from which two parsers disagree about what a document said.