import { describe, expect, test } from "bun:test"; describe("Structured Clone Fast Path", () => { test("structuredClone should work with empty object", () => { const object = {}; const cloned = structuredClone(object); expect(cloned).toStrictEqual({}); }); test("structuredClone should work with empty string", () => { const string = ""; const cloned = structuredClone(string); expect(cloned).toStrictEqual(""); }); const deOptimizations = [ { get accessor() { return 1; }, }, Object.create(Object.prototype, { data: { value: 1, writable: false, configurable: false, }, }), Object.create(Object.prototype, { data: { value: 1, writable: true, configurable: false, }, }), Object.create(Object.prototype, { data: { get: () => 1, configurable: true, }, }), Object.create(Object.prototype, { data: { set: () => {}, enumerable: true, configurable: true, }, }), ]; for (const deOptimization of deOptimizations) { test("structuredCloneDeOptimization", () => { structuredClone(deOptimization); }); } test("structuredClone should use a constant amount of memory for string inputs", () => { const clones: Array = []; // Create a 512KB string to test fast path const largeString = Buffer.alloc(512 * 1024, "a").toString(); for (let i = 0; i < 100; i++) { clones.push(structuredClone(largeString)); } Bun.gc(true); const rss = process.memoryUsage.rss(); for (let i = 0; i < 10000; i++) { clones.push(structuredClone(largeString)); } Bun.gc(true); const rss2 = process.memoryUsage.rss(); const delta = rss2 - rss; expect(delta).toBeLessThan(1024 * 1024 * 8); expect(clones.length).toBe(10000 + 100); }); test("structuredClone should use a constant amount of memory for simple object inputs", () => { // Create a 512KB string to test fast path const largeValue = { property: Buffer.alloc(512 * 1024, "a").toString() }; for (let i = 0; i < 100; i++) { structuredClone(largeValue); } Bun.gc(true); const rss = process.memoryUsage.rss(); for (let i = 0; i < 10000; i++) { structuredClone(largeValue); } Bun.gc(true); const rss2 = process.memoryUsage.rss(); const delta = rss2 - rss; expect(delta).toBeLessThan(1024 * 1024); }); test("structuredClone on object with simple properties can exceed JSFinalObject::maxInlineCapacity", () => { let largeValue = {}; for (let i = 0; i < 100; i++) { largeValue["property" + i] = i; } for (let i = 0; i < 100; i++) { expect(structuredClone(largeValue)).toStrictEqual(largeValue); } Bun.gc(true); for (let i = 0; i < 100; i++) { expect(structuredClone(largeValue)).toStrictEqual(largeValue); } }); });