A regression was introduced in commit
c1abbb11f ("OPTIM: log/tools:
switch from function pointer design to dual mode HEX/BIN design for
CBOR encoding").
Indeed, it was assumed that for x86_64 systems that the byte order
for uint64_t was already correct and that the value could be written
as-is. This is totally wrong, because x86_64 is little endian while
CBOR is big endian. Because of this mistake, values greater than 24
were written in reverse/incorrect order when using
cbor_encode_uint64_prefix_bin().
To fix the issue, instead of completely ditching the fast-path,
let's leverage htons, htonl and my_htonll for 2, 4 and 8 bytes
value respectively (since the value length is known under the
function), as they are less expensive than writing the value 1
byte at a time.
Many thanks to Dragan Dosen and Martin Mirchev for having reported the
issue.
No backport needed.
return NULL;
#if defined(__x86_64__)
- /* we can actually assume the bits are already in proper order
- * so let's directly write them as-is on the wire to save CPU
- * time.
+ /* x86_64 is little endian while CBOR expects big endian, so
+ * let's invert bit order, hopefully we can leverage hton{s,l},
+ * given the number of bytes in <value>, to revert all the bytes
+ * from <value> at once which is less costly than writing 1 byte
+ * at a time.
*/
+ switch (nb_bytes) {
+ case 2:
+ value = htons(value);
+ break;
+ case 4:
+ value = htonl(value);
+ break;
+ case 8:
+ value = my_htonll(value);
+ break;
+ default:
+ /* nothing to do */
+ break;
+ }
memcpy(start, &value, nb_bytes);
start += nb_bytes;
#else