2021-08-02 11:31:59 -04:00
|
|
|
"use strict";
|
2017-07-19 17:56:24 -04:00
|
|
|
module.exports = getJsonBufferPadded;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert the JSON object to a padded buffer.
|
|
|
|
*
|
|
|
|
* Pad the JSON with extra whitespace to fit the next 4-byte boundary. This ensures proper alignment
|
|
|
|
* for the section that follows.
|
|
|
|
*
|
|
|
|
* @param {Object} [json] The JSON object.
|
|
|
|
* @returns {Buffer} The padded JSON buffer.
|
|
|
|
*
|
|
|
|
* @private
|
|
|
|
*/
|
|
|
|
function getJsonBufferPadded(json) {
|
2021-08-02 11:31:59 -04:00
|
|
|
let string = JSON.stringify(json);
|
2017-07-19 17:56:24 -04:00
|
|
|
|
2021-08-02 11:31:59 -04:00
|
|
|
const boundary = 4;
|
|
|
|
const byteLength = Buffer.byteLength(string);
|
|
|
|
const remainder = byteLength % boundary;
|
|
|
|
const padding = remainder === 0 ? 0 : boundary - remainder;
|
|
|
|
let whitespace = "";
|
|
|
|
for (let i = 0; i < padding; ++i) {
|
|
|
|
whitespace += " ";
|
|
|
|
}
|
|
|
|
string += whitespace;
|
2017-07-19 17:56:24 -04:00
|
|
|
|
2021-08-02 11:31:59 -04:00
|
|
|
return Buffer.from(string);
|
2017-07-19 17:56:24 -04:00
|
|
|
}
|