convert.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { toArrayBuffer } from "../bytes/index.js";
  2. import { base64, base64url, binary, hex, utf8, utf16 } from "../encoding/index.js";
  3. import { defaultConverterRegistry } from "./defaults.js";
  4. function encode(name, data, ...args) {
  5. return defaultConverterRegistry.encode(name, data, ...args);
  6. }
  7. function decode(name, text, ...args) {
  8. return defaultConverterRegistry.decode(name, text, ...args);
  9. }
  10. function tryDecode(name, text, ...args) {
  11. return defaultConverterRegistry.tryDecode(name, text, ...args);
  12. }
  13. function normalize(name, text, ...args) {
  14. return defaultConverterRegistry.normalize(name, text, ...args);
  15. }
  16. function parse(name, text, ...args) {
  17. return defaultConverterRegistry.parse(name, text, ...args);
  18. }
  19. function format(name, data, value) {
  20. return defaultConverterRegistry.format(name, data, value);
  21. }
  22. function transcode(text, options) {
  23. return defaultConverterRegistry.transcode(text, options);
  24. }
  25. function detect(text, options) {
  26. return defaultConverterRegistry.detect(text, options);
  27. }
  28. function normalizeEncodingName(encoding) {
  29. return encoding.toLowerCase();
  30. }
  31. export const convert = {
  32. encode,
  33. decode,
  34. tryDecode,
  35. normalize,
  36. parse,
  37. format,
  38. transcode,
  39. detect,
  40. to(format, data, ...args) {
  41. return encode(format, data, ...args);
  42. },
  43. from(format, text, ...args) {
  44. return decode(format, text, ...args);
  45. },
  46. toString(data, encoding = "utf8") {
  47. return encode(encoding, data);
  48. },
  49. fromString(text, encoding = "utf8") {
  50. if (normalizeEncodingName(encoding) === "hex") {
  51. return toArrayBuffer(hex.decode(text, { allowOddLength: true }));
  52. }
  53. return toArrayBuffer(decode(encoding, text));
  54. },
  55. toBase64: base64.encode,
  56. fromBase64: (text) => toArrayBuffer(base64.decode(text)),
  57. toBase64Url: base64url.encode,
  58. fromBase64Url: (text) => toArrayBuffer(base64url.decode(text)),
  59. toHex: hex.encode,
  60. fromHex: (text) => toArrayBuffer(hex.decode(text, { allowOddLength: true })),
  61. toBinary: binary.encode,
  62. fromBinary: (text) => toArrayBuffer(binary.decode(text)),
  63. toUtf8String: utf8.decode,
  64. fromUtf8String: (text) => toArrayBuffer(utf8.encode(text)),
  65. toUtf16String: (data, littleEndian = false) => utf16.decode(data, { littleEndian }),
  66. fromUtf16String: (text, littleEndian = false) => toArrayBuffer(utf16.encode(text, { littleEndian })),
  67. isHex: hex.is,
  68. isBase64: base64.is,
  69. isBase64Url: base64url.is,
  70. formatString: base64.normalize,
  71. };