Skip to content

Commit

Permalink
perf(syrup): Pass diagnostic path data as an array rather than a string
Browse files Browse the repository at this point in the history
In the absence of errors, the associated string concatenation doesn't even take place.
  • Loading branch information
gibson042 committed Jan 30, 2024
1 parent 8ead45d commit 5ef0882
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions packages/syrup/src/encode.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ function encodeString(buffer, value) {
/**
* @param {Buffer} buffer
* @param {Record<string, any>} record
* @param {string} path
* @param {Array<string | number>} path
*/
function encodeRecord(buffer, record, path) {
const restart = buffer.length;
Expand Down Expand Up @@ -132,7 +132,7 @@ function encodeRecord(buffer, record, path) {
encodeString(buffer, key);
// Recursion, it's a thing!
// eslint-disable-next-line no-use-before-define
encodeAny(buffer, value, `${path}/${key}`);
encodeAny(buffer, value, path, key);
}

cursor = grow(buffer, 1);
Expand All @@ -142,7 +142,7 @@ function encodeRecord(buffer, record, path) {
/**
* @param {Buffer} buffer
* @param {Array<any>} array
* @param {string} path
* @param {Array<string | number>} path
*/
function encodeArray(buffer, array, path) {
let cursor = grow(buffer, 2 + array.length);
Expand All @@ -153,7 +153,7 @@ function encodeArray(buffer, array, path) {
for (const value of array) {
// Recursion, it's a thing!
// eslint-disable-next-line no-use-before-define
encodeAny(buffer, value, `${path}/${index}`);
encodeAny(buffer, value, path, index);
index += 1;
}

Expand All @@ -164,9 +164,10 @@ function encodeArray(buffer, array, path) {
/**
* @param {Buffer} buffer
* @param {any} value
* @param {string} path
* @param {Array<string | number>} path
* @param {string | number} pathSuffix
*/
function encodeAny(buffer, value, path) {
function encodeAny(buffer, value, path, pathSuffix) {
if (typeof value === 'string') {
encodeString(buffer, value);
return;
Expand Down Expand Up @@ -202,12 +203,16 @@ function encodeAny(buffer, value, path) {
}

if (Array.isArray(value)) {
path.push(pathSuffix);
encodeArray(buffer, value, path);
path.pop();
return;
}

if (Object(value) === value) {
path.push(pathSuffix);
encodeRecord(buffer, value, path);
path.pop();
return;
}

Expand All @@ -223,7 +228,8 @@ function encodeAny(buffer, value, path) {
return;
}

throw TypeError(`Cannot encode value ${value} at ${path}`);
path.push(pathSuffix);
throw TypeError(`Cannot encode value ${value} at ${path.join('/')}`);
}

/**
Expand All @@ -239,6 +245,6 @@ export function encodeSyrup(value, options = {}) {
const data = new DataView(bytes.buffer);
const length = 0;
const buffer = { bytes, data, length };
encodeAny(buffer, value, '/');
encodeAny(buffer, value, [], '/');
return buffer.bytes.subarray(0, buffer.length);
}

0 comments on commit 5ef0882

Please sign in to comment.