1
0

value-text.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. const {
  2. normalizeTextValue
  3. } = require('../../utils/base-utils.js')
  4. const {
  5. trimTrailingNullBytes
  6. } = require('../../utils/binary-utils.js')
  7. const {
  8. MAX_TEXT_BYTE_LENGTH
  9. } = require('./constants.js')
  10. const {
  11. getDataType
  12. } = require('./value-types.js')
  13. function encodeAsciiBytes(text, byteLimit = 32) {
  14. const bytes = []
  15. const stringValue = normalizeTextValue(text)
  16. for (let index = 0; index < stringValue.length; index += 1) {
  17. const code = stringValue.charCodeAt(index)
  18. if (code > 0x7F) {
  19. throw new Error('ASCII 文本只能包含 0x00 - 0x7F 字符')
  20. }
  21. bytes.push(code)
  22. if (bytes.length > byteLimit) break
  23. }
  24. if (bytes.length > byteLimit) {
  25. throw new Error(`长文本最长 ${byteLimit} 字节`)
  26. }
  27. return bytes
  28. }
  29. function encodeUtf8Bytes(text, byteLimit = 32) {
  30. const bytes = []
  31. const encoded = encodeURIComponent(normalizeTextValue(text))
  32. for (let index = 0; index < encoded.length; index += 1) {
  33. const char = encoded[index]
  34. if (char === '%') {
  35. const byte = parseInt(encoded.slice(index + 1, index + 3), 16)
  36. if (!Number.isFinite(byte)) break
  37. bytes.push(byte & 0xFF)
  38. index += 2
  39. } else {
  40. bytes.push(char.charCodeAt(0) & 0xFF)
  41. }
  42. if (bytes.length > byteLimit) break
  43. }
  44. if (bytes.length > byteLimit) {
  45. throw new Error(`长文本最长 ${byteLimit} 字节`)
  46. }
  47. return bytes
  48. }
  49. function decodeAsciiBytes(bytes = []) {
  50. return String.fromCharCode.apply(null, trimTrailingNullBytes(bytes).map((byte) => byte & 0xFF))
  51. }
  52. function decodeUtf8Bytes(bytes = []) {
  53. const trimmed = trimTrailingNullBytes(bytes)
  54. if (!trimmed.length) return ''
  55. let encoded = ''
  56. trimmed.forEach((byte) => {
  57. encoded += `%${(byte & 0xFF).toString(16).padStart(2, '0').toUpperCase()}`
  58. })
  59. try {
  60. return decodeURIComponent(encoded)
  61. } catch (error) {
  62. return decodeAsciiBytes(trimmed)
  63. }
  64. }
  65. function encodeTextBytes(text, dataType, byteLimit = MAX_TEXT_BYTE_LENGTH) {
  66. const normalizedType = getDataType(dataType).key
  67. if (normalizedType === 'ascii') return encodeAsciiBytes(text, byteLimit)
  68. return encodeUtf8Bytes(text, byteLimit)
  69. }
  70. function decodeTextBytes(bytes, dataType) {
  71. const normalizedType = getDataType(dataType).key
  72. return normalizedType === 'ascii'
  73. ? decodeAsciiBytes(bytes)
  74. : decodeUtf8Bytes(bytes)
  75. }
  76. module.exports = {
  77. decodeAsciiBytes,
  78. decodeTextBytes,
  79. decodeUtf8Bytes,
  80. encodeAsciiBytes,
  81. encodeTextBytes,
  82. encodeUtf8Bytes
  83. }