|
| 1 | +import { describe, expect, it } from "vitest"; |
| 2 | +import { toBytes } from "./to-bytes.js"; |
| 3 | + |
| 4 | +// Test suite for toBytes function |
| 5 | +describe("toBytes", () => { |
| 6 | + it("should convert a small number to a 1-byte buffer", () => { |
| 7 | + expect(toBytes(42, 1)).toEqual(Buffer.from([42])); |
| 8 | + }); |
| 9 | + |
| 10 | + it("should convert a small number to a multi-byte buffer with padding", () => { |
| 11 | + expect(toBytes(42, 4)).toEqual(Buffer.from([42, 0, 0, 0])); |
| 12 | + }); |
| 13 | + |
| 14 | + it("should handle multi-byte numbers correctly", () => { |
| 15 | + expect(toBytes(4660, 4)).toEqual(Buffer.from([0x34, 0x12, 0, 0])); |
| 16 | + expect(toBytes(0x12345678, 4)).toEqual(Buffer.from([0x78, 0x56, 0x34, 0x12])); |
| 17 | + }); |
| 18 | + |
| 19 | + it("should handle maximum safe integer correctly", () => { |
| 20 | + expect(toBytes(Number.MAX_SAFE_INTEGER, 8)).toEqual(Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00])); |
| 21 | + }); |
| 22 | + |
| 23 | + it("should handle zero correctly", () => { |
| 24 | + expect(toBytes(0, 4)).toEqual(Buffer.from([0, 0, 0, 0])); |
| 25 | + }); |
| 26 | + |
| 27 | + it("should return a zero-filled buffer for zero with a larger length", () => { |
| 28 | + expect(toBytes(0, 8)).toEqual(Buffer.alloc(8)); |
| 29 | + }); |
| 30 | + |
| 31 | + it("should throw a RangeError for negative lengths", () => { |
| 32 | + expect(() => toBytes(123, -1)).toThrow(RangeError); |
| 33 | + }); |
| 34 | + |
| 35 | + it("should throw a RangeError for zero length", () => { |
| 36 | + expect(() => toBytes(123, 0)).toThrow(RangeError); |
| 37 | + }); |
| 38 | + |
| 39 | + it("should throw a RangeError for negative values", () => { |
| 40 | + expect(() => toBytes(-123, 4)).toThrow(RangeError); |
| 41 | + }); |
| 42 | + |
| 43 | + it("should throw a RangeError for non-safe integers", () => { |
| 44 | + expect(() => toBytes(Number.MAX_SAFE_INTEGER + 1, 8)).toThrow(RangeError); |
| 45 | + }); |
| 46 | + |
| 47 | + it("should handle maximum value fitting in the given length", () => { |
| 48 | + expect(toBytes(255, 1)).toEqual(Buffer.from([0xff])); |
| 49 | + expect(toBytes(65535, 2)).toEqual(Buffer.from([0xff, 0xff])); |
| 50 | + expect(toBytes(4294967295, 4)).toEqual(Buffer.from([0xff, 0xff, 0xff, 0xff])); |
| 51 | + expect(toBytes(Number.MAX_SAFE_INTEGER, 8)).toEqual(Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x1f, 0x00])); |
| 52 | + }); |
| 53 | + |
| 54 | + it("should throw a RangeError if the value exceeds the buffer length", () => { |
| 55 | + expect(() => toBytes(256, 1)).toThrow(RangeError); |
| 56 | + expect(() => toBytes(65536, 2)).toThrow(RangeError); |
| 57 | + expect(() => toBytes(4294967296, 4)).toThrow(RangeError); |
| 58 | + expect(() => toBytes(Number.MAX_SAFE_INTEGER + 1, 8)).toThrow(RangeError); |
| 59 | + }); |
| 60 | +}); |
0 commit comments