logigate/app/lib/convert.ts

204 lines
9.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The converter tool: text, hex, binary, decimal, octal and Base64 into one
// another. Everything goes through bytes: text by its encoding, numbers as
// words of 8, 16 or 32 bits (several bytes each in big- or little-endian).
export const FORMATS = ['text', 'hex', 'bin', 'dec', 'oct', 'base64'] as const
export type Format = (typeof FORMATS)[number]
export const FORMAT_NAMES: Record<Format, string> = { text: 'Text', hex: 'Hex', bin: 'Binary', dec: 'Decimal', oct: 'Octal', base64: 'Base64' }
export const ENCODINGS = ['utf8', 'ascii', 'latin1', 'utf16le', 'utf16be', 'utf32be'] as const
export type Encoding = (typeof ENCODINGS)[number]
export const ENCODING_NAMES: Record<Encoding, string> = {
utf8: 'UTF-8',
ascii: 'ASCII (7 bits)',
latin1: 'Latin-1 (ISO 8859-1)',
utf16le: 'UTF-16 little-endian',
utf16be: 'UTF-16 big-endian',
utf32be: 'UTF-32 big-endian',
}
export type WordBits = 8 | 16 | 32
export interface ConvertOptions {
enc: Encoding
word: WordBits
endian: 'big' | 'little'
}
export type Result<T> = { ok: true; value: T; note?: string } | { ok: false; error: string }
// ── Text ⇄ bytes ─────────────────────────────────────────────────────
export function encodeText(s: string, enc: Encoding): Result<Uint8Array> {
const out: number[] = []
const cps = [...s].map(c => c.codePointAt(0)!)
switch (enc) {
case 'utf8':
return { ok: true, value: new TextEncoder().encode(s) }
case 'ascii':
case 'latin1': {
const max = enc === 'ascii' ? 0x7f : 0xff
const bad = cps.findIndex(c => c > max)
if (bad >= 0) return { ok: false, error: `"${String.fromCodePoint(cps[bad]!)}" (character ${bad + 1}) has no code in ${ENCODING_NAMES[enc]}` }
return { ok: true, value: Uint8Array.from(cps) }
}
case 'utf16le':
case 'utf16be':
for (let i = 0; i < s.length; i++) {
const u = s.charCodeAt(i)
if (enc === 'utf16le') out.push(u & 0xff, u >> 8)
else out.push(u >> 8, u & 0xff)
}
return { ok: true, value: Uint8Array.from(out) }
case 'utf32be':
for (const c of cps) out.push((c >>> 24) & 0xff, (c >>> 16) & 0xff, (c >>> 8) & 0xff, c & 0xff)
return { ok: true, value: Uint8Array.from(out) }
}
}
export function decodeText(b: Uint8Array, enc: Encoding): Result<string> {
switch (enc) {
case 'utf8': {
const text = new TextDecoder('utf-8').decode(b)
return { ok: true, value: text, ...(text.includes('<27>') ? { note: 'Some bytes are not valid UTF-8 (shown as <20>)' } : {}) }
}
case 'ascii':
case 'latin1': {
const bad = enc === 'ascii' && b.some(x => x > 0x7f)
let text = ''
for (const x of b) text += enc === 'ascii' && x > 0x7f ? '<27>' : String.fromCharCode(x)
return { ok: true, value: text, ...(bad ? { note: 'Bytes above 7F are not ASCII (shown as <20>)' } : {}) }
}
case 'utf16le':
case 'utf16be': {
let text = ''
for (let i = 0; i + 1 < b.length; i += 2) text += String.fromCharCode(enc === 'utf16le' ? b[i]! | (b[i + 1]! << 8) : (b[i]! << 8) | b[i + 1]!)
return { ok: true, value: text, ...(b.length % 2 ? { note: 'The last byte is half a character' } : {}) }
}
case 'utf32be': {
let text = ''
let bad = false
for (let i = 0; i + 3 < b.length; i += 4) {
const c = ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0
if (c > 0x10ffff || (c >= 0xd800 && c <= 0xdfff)) {
bad = true
text += '<27>'
} else text += String.fromCodePoint(c)
}
return { ok: true, value: text, ...(bad || b.length % 4 ? { note: 'Some bytes are not whole UTF-32 characters' } : {}) }
}
}
}
// ── Words ⇄ bytes ────────────────────────────────────────────────────
/** Bytes as words; a last word short of bytes is filled with zeros. */
export function toWords(b: Uint8Array, o: Pick<ConvertOptions, 'word' | 'endian'>): number[] {
const n = o.word / 8
const out: number[] = []
for (let i = 0; i < b.length; i += n) {
let v = 0
for (let k = 0; k < n; k++) {
const byte = b[i + k] ?? 0
v += byte * 2 ** (8 * (o.endian === 'big' ? n - 1 - k : k))
}
out.push(v)
}
return out
}
export function fromWords(words: number[], o: Pick<ConvertOptions, 'word' | 'endian'>): Uint8Array {
const n = o.word / 8
const out = new Uint8Array(words.length * n)
words.forEach((v, i) => {
for (let k = 0; k < n; k++) {
const byte = Math.floor(v / 2 ** (8 * k)) & 0xff
out[i * n + (o.endian === 'big' ? n - 1 - k : k)] = byte
}
})
return out
}
// ── Number formats ───────────────────────────────────────────────────
const RADIX: Record<'hex' | 'bin' | 'dec' | 'oct', number> = { hex: 16, bin: 2, dec: 10, oct: 8 }
const DIGITS: Record<'hex' | 'bin' | 'dec' | 'oct', RegExp> = { hex: /^[0-9a-f]+$/i, bin: /^[01]+$/, dec: /^\d+$/, oct: /^[0-7]+$/ }
/** Digits one word takes in a format with a fixed width (hex and binary). */
const wordDigits = (fmt: 'hex' | 'bin', word: WordBits) => (fmt === 'hex' ? word / 4 : word)
/** Words written in a number format: separated by spaces, commas or new lines; 0x, 0b, 0o prefixes are fine. A long hex or binary run is several words. */
export function parseWords(input: string, fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): Result<number[]> {
const out: number[] = []
const max = 2 ** word
for (const raw of input.split(/[\s,;]+/).filter(Boolean)) {
const t = raw.replace(fmt === 'hex' ? /^(0x|\$|#)|h$/gi : fmt === 'bin' ? /^0b|b$/gi : fmt === 'oct' ? /^0o/i : /^$/, '').replace(/_/g, '')
if (!DIGITS[fmt].test(t)) return { ok: false, error: `"${raw}" is not ${fmt === 'hex' ? 'hex' : fmt === 'bin' ? 'binary' : fmt === 'dec' ? 'a decimal number' : 'octal'}` }
if ((fmt === 'hex' || fmt === 'bin') && t.length > wordDigits(fmt, word)) {
const d = wordDigits(fmt, word)
if (t.length % d) return { ok: false, error: `"${raw}" is ${t.length} digits: not a whole number of ${word}-bit words (${d} digits each)` }
for (let i = 0; i < t.length; i += d) out.push(parseInt(t.slice(i, i + d), RADIX[fmt]))
continue
}
const v = parseInt(t, RADIX[fmt])
if (v >= max) return { ok: false, error: `"${raw}" does not fit in ${word} bits (up to ${max - 1})` }
out.push(v)
}
return { ok: true, value: out }
}
export function formatWords(words: number[], fmt: 'hex' | 'bin' | 'dec' | 'oct', word: WordBits): string {
return words
.map(v => {
const s = v.toString(RADIX[fmt])
return fmt === 'hex' ? s.toUpperCase().padStart(word / 4, '0') : fmt === 'bin' ? s.padStart(word, '0') : s
})
.join(' ')
}
// ── Base64 ───────────────────────────────────────────────────────────
export function toBase64(b: Uint8Array): string {
let s = ''
for (const x of b) s += String.fromCharCode(x)
return btoa(s)
}
export function fromBase64(input: string): Result<Uint8Array> {
const t = input.replace(/\s+/g, '').replace(/-/g, '+').replace(/_/g, '/')
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(t)) return { ok: false, error: 'Not Base64 (A–Z, a–z, 0–9, +, / and = at the end)' }
try {
const s = atob(t.padEnd(Math.ceil(t.length / 4) * 4, '='))
return { ok: true, value: Uint8Array.from(s, c => c.charCodeAt(0)) }
} catch {
return { ok: false, error: 'Not Base64' }
}
}
// ── Any format ⇄ bytes ───────────────────────────────────────────────
export function parseAs(input: string, fmt: Format, o: ConvertOptions): Result<Uint8Array> {
if (fmt === 'text') return encodeText(input, o.enc)
if (fmt === 'base64') return fromBase64(input)
const w = parseWords(input, fmt, o.word)
return w.ok ? { ok: true, value: fromWords(w.value, o) } : w
}
export function formatAs(b: Uint8Array, fmt: Format, o: ConvertOptions): Result<string> {
if (fmt === 'text') return decodeText(b, o.enc)
if (fmt === 'base64') return { ok: true, value: toBase64(b) }
const note = b.length % (o.word / 8) ? `The last word is filled up with zero bytes` : undefined
return { ok: true, value: formatWords(toWords(b, o), fmt, o.word), ...(note ? { note } : {}) }
}
/** A word as a signed number (two's complement). */
export const signed = (v: number, word: WordBits) => (v >= 2 ** (word - 1) ? v - 2 ** word : v)
/** How a byte or character shows in a table: control characters by name. */
export function charLabel(code: number): string {
const NAMES: Record<number, string> = { 0: 'NUL', 7: 'BEL', 8: 'BS', 9: 'TAB', 10: 'LF', 13: 'CR', 27: 'ESC', 32: 'space', 127: 'DEL' }
if (NAMES[code]) return NAMES[code]!
if (code < 32 || (code >= 0x80 && code < 0xa0)) return `^${code.toString(16).toUpperCase().padStart(2, '0')}`
if (code >= 0xd800 && code <= 0xdfff) return '·'
return code <= 0x10ffff ? String.fromCodePoint(code) : '·'
}