buffer.test.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { describe, it, expect } from "vitest";
  2. import { VSBuffer } from "../src/buffer.js";
  3. describe("VSBuffer", () => {
  4. it("alloc should create a zero-filled buffer", () => {
  5. const buf = VSBuffer.alloc(4);
  6. expect(buf.byteLength).toBe(4);
  7. expect(buf.buffer.every((b) => b === 0)).toBe(true);
  8. });
  9. it("wrap should wrap existing Uint8Array", () => {
  10. const raw = new Uint8Array([1, 2, 3]);
  11. const buf = VSBuffer.wrap(raw);
  12. expect(buf.byteLength).toBe(3);
  13. expect(buf.buffer).toBe(raw);
  14. });
  15. it("fromString / toString roundtrip", () => {
  16. const text = "hello 你好 🌍";
  17. const buf = VSBuffer.fromString(text);
  18. expect(buf.toString()).toBe(text);
  19. });
  20. it("concat should merge multiple buffers", () => {
  21. const a = VSBuffer.fromString("ab");
  22. const b = VSBuffer.fromString("cd");
  23. const result = VSBuffer.concat([a, b]);
  24. expect(result.toString()).toBe("abcd");
  25. expect(result.byteLength).toBe(a.byteLength + b.byteLength);
  26. });
  27. it("slice should return a sub-buffer", () => {
  28. const buf = VSBuffer.fromString("hello");
  29. const sub = buf.slice(1, 3);
  30. expect(sub.toString()).toBe("el");
  31. });
  32. it("set should copy data at offset", () => {
  33. const buf = VSBuffer.alloc(4);
  34. const src = VSBuffer.wrap(new Uint8Array([0xaa, 0xbb]));
  35. buf.set(src, 1);
  36. expect(buf.readUInt8(0)).toBe(0);
  37. expect(buf.readUInt8(1)).toBe(0xaa);
  38. expect(buf.readUInt8(2)).toBe(0xbb);
  39. expect(buf.readUInt8(3)).toBe(0);
  40. });
  41. it("readUInt32BE / writeUInt32BE roundtrip", () => {
  42. const buf = VSBuffer.alloc(8);
  43. buf.writeUInt32BE(0x12345678, 0);
  44. buf.writeUInt32BE(0xdeadbeef, 4);
  45. expect(buf.readUInt32BE(0)).toBe(0x12345678);
  46. expect(buf.readUInt32BE(4)).toBe(0xdeadbeef);
  47. });
  48. it("readUInt32BE should handle max value", () => {
  49. const buf = VSBuffer.alloc(4);
  50. buf.writeUInt32BE(0xffffffff, 0);
  51. expect(buf.readUInt32BE(0)).toBe(0xffffffff);
  52. });
  53. });