"use strict"; const generateID = require("../../generate-id"); const BLOB_INTERNAL = Buffer.from([ 0 ]); const BLOB_EXTERNAL = Buffer.from([ 1 ]); module.exports = { encode: function (value, _asIndexKey) { if (value.length < 256) { return { value: [ BLOB_INTERNAL, Buffer.from([ value.length ]), value ], auxiliaryBlob: undefined }; } else { let blobID = generateID(); return { value: [ BLOB_EXTERNAL, blobID ], auxiliaryBlob: { key: blobID, value: value } }; } }, decode: function (buffer, offset) { let blobType = buffer.readUInt8(offset); if (blobType === 0) { // Internal blob let blobLength = buffer.readUInt8(offset + 1); let blobPosition = offset + 2; let bytes = buffer.slice(blobPosition, blobPosition + blobLength); return { bytesRead: 2 + blobLength, value: bytes, auxiliaryBlob: undefined }; } else if (blobType === 1) { // External blob let idPosition = offset + 1; return { bytesRead: 13, // a blob ID is always 12 bytes value: undefined, auxiliaryBlob: { key: buffer.slice(idPosition, idPosition + 12), transform: (blob) => blob } }; } else { throw new Error(`Invalid blob type: ${blobType}`); } } };