Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 11 additions & 17 deletions src/os/persistence/PersistenceLayer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,25 @@ export class PersistenceLayer {
*/
save(data: any, key: string): Buffer {
const payload = JSON.stringify(data);
const payloadBuf = Buffer.from(payload, 'utf8');

// Bolt Optimization: Allocate unsafe buffer for exact combined size to avoid Buffer.concat and intermediate payload allocations
const outBuf = Buffer.allocUnsafe(38 + payloadBuf.length);

// Copy pre-allocated header and payload
outBuf.set(HEADER_BUF, 0);
outBuf.set(payloadBuf, 38);

// Compute and write HMAC signature directly
const hmac = crypto.createHmac('sha256',. key);
hmac.update(payloadBuf);
const signature = hmac.digest();
outBuf.set(signature, 6);

const payloadByteLength = Buffer.byteLength(payload, 'utf8');

// Bolt Optimization: Allocate pre-sized buffer to eliminate Buffer.concat and intermediate allocations
const out = Buffer.allocUnsafe(HEADER_LENGTH + SIGNATURE_LENGTH + payloadByteLength);

// Zero-copy set of pre-allocated header
out.set(HEADER_MAGIC, 0);
// Zero-copy set of hmac signature
out.set(signature, HEADER_LENGTH);

// Direct UTF-8 write of the payload to avoid intermediate Buffer allocation
out.write(payload, HEADER_LENGTH + SIGNATURE_LENGTH, payloadByteLength, 'utf8');

// Compute HMAC signature directly from string payload without intermediate buffer
const hmac = crypto.createHmac('sha256', key);
hmac.update(payload);
const signature = hmac.digest();

// Zero-copy set of hmac signature
out.set(signature, HEADER_LENGTH);

return out;
}

Expand Down