Skip to content

Commit

Permalink
enhance Buffer.from to support (de)serialization roundtrip (#14201)
Browse files Browse the repository at this point in the history
Co-authored-by: Jarred Sumner <[email protected]>
  • Loading branch information
nektro and Jarred-Sumner authored Oct 11, 2024
1 parent 170fafb commit 25fcbed
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/js/builtins/JSBufferConstructor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,12 @@ export function from(items) {
}
}
}
if (typeof items === "object") {
const data = items.data;
if (items.type === "Buffer" && Array.isArray(data)) {
return new $Buffer(data);
}
}

var arrayLike = $toObject(
items,
Expand Down
24 changes: 24 additions & 0 deletions test/js/node/buffer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2921,3 +2921,27 @@ export function fillRepeating(dstBuffer, start, end) {
sLen <<= 1; // double length for next segment
}
}

describe("serialization", () => {
it("json", () => {
expect(JSON.stringify(Buffer.alloc(0))).toBe('{"type":"Buffer","data":[]}');
expect(JSON.stringify(Buffer.from([1, 2, 3, 4]))).toBe('{"type":"Buffer","data":[1,2,3,4]}');
});

it("and deserialization", () => {
const buf = Buffer.from("test");
const json = JSON.stringify(buf);
const obj = JSON.parse(json);
const copy = Buffer.from(obj);
expect(copy).toEqual(buf);
});

it("custom", () => {
const buffer = Buffer.from("test");
const string = JSON.stringify(buffer);
expect(string).toBe('{"type":"Buffer","data":[116,101,115,116]}');

const receiver = (key, value) => (value && value.type === "Buffer" ? Buffer.from(value.data) : value);
expect(JSON.parse(string, receiver)).toEqual(buffer);
});
});

0 comments on commit 25fcbed

Please sign in to comment.