buffer.test.ts 1.7 KB

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