UNPKG

@gulujs/toml

Version:

TOML parser and serializer

40 lines (39 loc) 1.43 kB
import { InvalidValueError } from '../errors/index.js'; export const MAX_SAFE_INTEGER_STRING_MAP = Object.freeze({ 10: Number.MAX_SAFE_INTEGER.toString(), 16: Number.MAX_SAFE_INTEGER.toString(16), 8: Number.MAX_SAFE_INTEGER.toString(8), 2: Number.MAX_SAFE_INTEGER.toString(2) }); export const INTEGER_PREFIX_MAP = Object.freeze({ 10: '', 16: '0x', 8: '0o', 2: '0b' }); export class IntegerConverter { convertStringToJsValue(str, options) { if (str.length < MAX_SAFE_INTEGER_STRING_MAP[options.radix].length || (str.length === MAX_SAFE_INTEGER_STRING_MAP[options.radix].length && str <= MAX_SAFE_INTEGER_STRING_MAP[options.radix])) { return parseInt(`${options.sign}${str}`, options.radix); } if (options.radix === 10) { return BigInt(`${options.sign}${str}`); } else { return BigInt(`${INTEGER_PREFIX_MAP[options.radix]}${str}`); } } isJsValue(value) { return Number.isInteger(value) || typeof value === 'bigint'; } convertJsValueToString(value, options) { if (options.radix !== 10) { if (value < 0) { throw new InvalidValueError('Negative number should only be allowed in decimal representation'); } } return `${INTEGER_PREFIX_MAP[options.radix]}${value.toString(options.radix)}`; } }