encoder.js 716 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. function con(n) {
  2. return 0x80 | (n & 0x3f);
  3. }
  4. export function encode(str) {
  5. const arr = str.split("").map((x) => x.charCodeAt(0));
  6. return _encode(arr);
  7. }
  8. function _encode(arr) {
  9. if (arr.length === 0) {
  10. return [];
  11. }
  12. const [n, ...ns] = arr;
  13. if (n < 0) {
  14. throw new Error("utf8");
  15. }
  16. if (n < 0x80) {
  17. return [n, ..._encode(ns)];
  18. }
  19. if (n < 0x800) {
  20. return [0xc0 | (n >>> 6), con(n), ..._encode(ns)];
  21. }
  22. if (n < 0x10000) {
  23. return [0xe0 | (n >>> 12), con(n >>> 6), con(n), ..._encode(ns)];
  24. }
  25. if (n < 0x110000) {
  26. return [
  27. 0xf0 | (n >>> 18),
  28. con(n >>> 12),
  29. con(n >>> 6),
  30. con(n),
  31. ..._encode(ns),
  32. ];
  33. }
  34. throw new Error("utf8");
  35. }