Byte order belongs at the call site, not in a library default
A wire format fixes its byte order. The host it runs on has one of its own, and the two agree only by accident. When a binary parsing library lets the order go unstated (a u16() with no argument, a packed struct, a memcpy into a uint32_t), the host answers a question that only the format's specification is allowed to answer, and the code is correct on the machine it was written on. Make the order a required argument of every multi-byte read and write and that answer moves into the call site, which is the only place a reviewer can hold it next to the spec.
I have been shipping payments and crypto systems since 2018: card rails and account-to-account flows, custodial wallet services for BTC and ETH, an on-chain payment system, e-signature document workflows. Underneath all of it sits the same shape, a record that arrives as bytes (a tag, a version, a length, a body), and the orders are not uniform. Some formats are big-endian end to end, some are little, and a few are one in the envelope and the other inside it. What survived contact with all of them was one habit, and it has nothing to do with naming conventions. I refuse to let the question be answered anywhere except at the read or the write itself.
That is the rule I built bytespan around, and it has a consequence I did not anticipate: it makes the reader and the writer asymmetric, for good reasons.
A default byte order is not a default, it is a guess#
There are two things a library can do when the caller says nothing.
It can pick network order and call it the default. Now every little-endian format is a trap, because the correct call is the one that looks unusual, and whoever writes a new call site has to know that the surrounding format is the exception.
Or it can lay down the host's representation, memcpy the integer and read it back the same way. That one is worse, because it is invisible. On the little-endian hosts that everything is built on, it round-trips perfectly. The test suite is green. And that green has a structural cause: a round-trip test cannot find a byte order bug. An encoder and a decoder that are wrong in the same direction agree with each other exactly. What finds the bug is a fixture of literal bytes copied out of the specification, plus a call site that states which order those bytes are supposed to be in.
So the enum has two values and no third meaning:
enum class endian { little, big };and nothing that moves a multi-byte integer has a default for it. The reader requires it on u16, u32, u64, length_prefixed_u16 and length_prefixed_u32. The writer requires it on the same five, plus close, which back-patches a reserved length field. A header parse then reads like the paragraph of the spec it came from:
bytespan::reader r{input};
const auto type = r.u8();
const auto version = r.u16(bytespan::endian::big);
const auto payload = r.length_prefixed_u16(bytespan::endian::big);
if (!r.ok()) return std::nullopt; // one check for the whole headerA reviewer with the specification open can check those three lines without knowing one thing about the library's internals. That is the whole point of the required argument, and it is worth more than the keystrokes it costs.
u8 is the exception, and it is the exception that shows what the rule is for. It takes no order and passes endian::big internally, because one byte has no order. A parameter there would be noise, implying a choice exists where none does. The argument is required exactly where something is actually being chosen.
Reading: shifts, so the host is never consulted#
The reader's private read template does the bounds check first, take(sizeof(T)), then assembles the value out of data_ one byte at a time. Byte i gets shifted by 8 * (sizeof(T) - 1 - i) for endian::big and by 8 * i for little, and the pieces are combined into the result. No memcpy, no swap, no std::endian::native anywhere in the path.
Three things follow, in ascending order of how much I care about them.
It reads like the spec. "Byte zero is the high byte" is a sentence from a document, and 8 * (sizeof(T) - 1 - i) is that sentence written down. There is no indirection through a swap, so nothing has to be mentally unwound when you are checking it.
The host's byte order never enters the code. Not as a branch, not as an if constexpr, not as a configuration. A big-endian target is not a second combination to test, because no code behaves differently on one. Anything conditioned on the platform is a path that CI, running on one platform, cannot exercise.
And the same loop stays valid during constant evaluation, where a memcpy through an object representation is not. That makes a different category of test available. A decoder built on memcpy can only ever be exercised at runtime, on whatever host ran the job. A decoder built on shifts can decode a literal fixture while the compiler is still running, which is the strongest version of the "bytes from the spec" test, because the failure lands at build time on every platform, long before any single host could hit it at runtime.
The cost is a byte-at-a-time loop where a wide load and one byteswap instruction would do. For a record header of a handful of fields sitting behind network or disk I/O, that has never been the thing worth optimizing in anything I have put into production. If it ever is, the measurement comes first and this paragraph gets rewritten.
Writing: one swap, in one function everything passes through#
The writing side cannot be host-agnostic in the same way, and pretending otherwise would be worse than admitting it. The value is an integer in a register, and the cheap, correct way to put it in a buffer is to copy its representation, which is in the host's order. So exactly one function asks what the host is:
template <typename T>
void store(std::size_t at, T value, endian order) noexcept {
if constexpr (sizeof(T) > 1) {
const bool host_is_little = std::endian::native == std::endian::little;
const bool want_little = order == endian::little;
if (host_is_little != want_little) value = detail::swap_bytes(value);
}
std::memcpy(out_.data() + at, &value, sizeof(T));
}Note what the condition is not. Not "swap on little-endian hosts", not "swap for big-endian output". It is two independent booleans compared against each other, and the swap happens when the host's answer and the caller's answer disagree. That symmetry is why one function covers both values of the enum on both kinds of host without a second branch, and why no case is left over to get wrong. The if constexpr (sizeof(T) > 1) is there because a single byte has nothing to reorder, the same fact that spares u8 its parameter.
detail::swap_bytes reverses the bytes with a loop of shifts and carries a static_assert that the type is unsigned. It is handwritten because std::byteswap is C++23 and this header stays at C++20; the assert keeps it off signed types, where shifting is not a thing to be clever about.
The part that actually matters is the funnel. put goes through store, and so does close:
if (narrow) {
store(slot.offset, static_cast<std::uint16_t>(body), order);
} else {
store(slot.offset, static_cast<std::uint32_t>(body), order);
}Back-patched lengths are where a byte order bug lives longest. A length field reserved by open_u16 and filled in later, after the body is written, is a second encoder in all but name, a different code path writing an integer at an offset it kept in a local. If it has its own memcpy, it has its own opportunity to be wrong, and it will be wrong in a way that does not look like a swapped integer. It looks like a message whose nesting does not add up, which is a much longer afternoon...
Routing close through store means a count that covers a block is encoded by the identical code as a plain u16, and each close still names its order where you can see it:
const auto block = w.open_u16(); // nullopt, writer poisoned, if it does not fit
w.u8(0x0A);
const auto body = w.open_u16();
w.bytes(payload);
w.close(*body, bytespan::endian::big); // innermost first
w.close(*block, bytespan::endian::big);And because it is one encoder, the test can assert the literal bytes themselves: {0x00, 0x06, 0x0A, 0x00, 0x03, 0xAA, 0xBB, 0xCC}, the outer count of six and the inner count of three, high byte first, checkable by eye.
The argument is what makes both orders testable in one process#
There is a second, duller payoff. Since the order is a value, a test can take both of them:
for (const endian order : {endian::big, endian::little}) {
std::array<std::byte, 16> buffer{};
writer w{buffer};
CHECK(w.length_prefixed_u16(payload, order));
CHECK(w.length_prefixed_u32(payload, order));
// ... read it back with the same order and compare
}With a default, the non-default path is reachable only by changing a build flag or the host, which in practice probably means it is not reachable in CI at all. A loop over the enum is nothing clever, just the test that becomes possible once the parameter exists. It still only proves the two sides agree, which is why the literal-byte fixtures have to exist alongside it. Agreement is cheap. Conformance is the thing being claimed.
What I would do differently#
I have shipped systems where the byte order was carried by a comment above a packed struct, and systems where it was carried by a thin wrapper with a name like the socket macros. Both work until someone adds a field. The comment cannot be checked by a compiler and drifts the first time the format grows a section with a different order; the wrapper is fine, but it hides the decision one call deeper than the review happens.
The real lesson is about ordering: the parameter has to be required from the first commit. If a default exists for even one release, every call site that omits it becomes unreviewable after the fact, because you can no longer tell "deliberately host order, and the format says so" from "nobody thought about it". Removing the default later does not recover that information, it just tells you where to go and ask.
The one ergonomic concession I keep being tempted by is a reader that binds the order once per format, so the argument disappears from the call sites. I have not done it, and I do not think I will. The saving is a few words per line. The loss is the only place where the code and the specification can be compared side by side.