import { describe, expect, it } from 'vitest' import { charLabel, ENCODINGS, formatAs, FORMATS, parseAs, parseWords, signed, type ConvertOptions } from '../app/lib/convert' const o: ConvertOptions = { enc: 'utf8', word: 8, endian: 'big' } const conv = (input: string, from: (typeof FORMATS)[number], to: (typeof FORMATS)[number], opts: Partial = {}) => { const b = parseAs(input, from, { ...o, ...opts }) if (!b.ok) throw new Error(b.error) const out = formatAs(b.value, to, { ...o, ...opts }) if (!out.ok) throw new Error(out.error) return out.value } describe('converter', () => { it('text to hex, binary, decimal, octal and Base64, and back', () => { expect(conv('Hi!', 'text', 'hex')).toBe('48 69 21') expect(conv('Hi!', 'text', 'bin')).toBe('01001000 01101001 00100001') expect(conv('Hi!', 'text', 'dec')).toBe('72 105 33') expect(conv('Hi!', 'text', 'oct')).toBe('110 151 41') expect(conv('Hi!', 'text', 'base64')).toBe('SGkh') for (const f of FORMATS) expect(conv(conv('Hällo €', 'text', f), f, 'text')).toBe('Hällo €') }) it('every encoding round-trips what it can encode', () => { for (const enc of ENCODINGS) { const s = enc === 'ascii' ? 'Hello' : enc === 'latin1' ? 'Grüße' : 'Grüße 😀' expect(conv(conv(s, 'text', 'hex', { enc }), 'hex', 'text', { enc })).toBe(s) } expect(conv('Hé', 'text', 'hex', { enc: 'utf16le' })).toBe('48 00 E9 00') expect(conv('😀', 'text', 'hex', { enc: 'utf32be' })).toBe('00 01 F6 00') expect(parseAs('é', 'text', { ...o, enc: 'ascii' }).ok).toBe(false) }) it('hex and binary accept prefixes, separators and long runs', () => { expect(conv('0x48,0x69 $21', 'hex', 'text')).toBe('Hi!') expect(conv('486921', 'hex', 'dec')).toBe('72 105 33') expect(conv('0b0100_1000', 'bin', 'hex')).toBe('48') expect(parseWords('ABC', 'hex', 8).ok).toBe(false) expect(parseWords('256', 'dec', 8).ok).toBe(false) expect(parseWords('zz', 'hex', 8).ok).toBe(false) }) it('words of 16 and 32 bits, in either byte order', () => { expect(conv('1234', 'hex', 'hex', { word: 16 })).toBe('1234') expect(conv('1234', 'hex', 'dec', { word: 16 })).toBe('4660') const le = parseAs('1234', 'hex', { ...o, word: 16, endian: 'little' }) expect(le.ok && [...le.value]).toEqual([0x34, 0x12]) expect(conv('DEADBEEF', 'hex', 'dec', { word: 32 })).toBe('3735928559') expect(conv('Hi!', 'text', 'hex', { word: 16 })).toBe('4869 2100') expect(signed(0xff, 8)).toBe(-1) expect(signed(0x7f, 8)).toBe(127) }) it('control characters have names', () => { expect(charLabel(10)).toBe('LF') expect(charLabel(65)).toBe('A') expect(charLabel(1)).toBe('^01') }) })