mirror of
https://github.com/oven-sh/bun
synced 2026-02-09 18:38:55 +00:00
enhance Buffer.from to support (de)serialization roundtrip (#14201)
Co-authored-by: Jarred Sumner <jarred@jarredsumner.com>
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user