const Mode = require('./mode') // 微信部分真机运行时没有 TextEncoder。二维码 BYTE 段只需要 UTF-8 字节, // 在此实现最小兼容编码器,且与 TextEncoder 对无效代理对的处理一致。 function encodeUtf8 (value) { const bytes = [] for (let index = 0; index < value.length; index += 1) { let codePoint = value.charCodeAt(index) if (codePoint >= 0xd800 && codePoint <= 0xdbff) { const next = value.charCodeAt(index + 1) if (next >= 0xdc00 && next <= 0xdfff) { codePoint = 0x10000 + ((codePoint - 0xd800) << 10) + (next - 0xdc00) index += 1 } else { codePoint = 0xfffd } } else if (codePoint >= 0xdc00 && codePoint <= 0xdfff) { codePoint = 0xfffd } if (codePoint <= 0x7f) { bytes.push(codePoint) } else if (codePoint <= 0x7ff) { bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)) } else if (codePoint <= 0xffff) { bytes.push(0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f)) } else { bytes.push(0xf0 | (codePoint >> 18), 0x80 | ((codePoint >> 12) & 0x3f), 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f)) } } return new Uint8Array(bytes) } function ByteData (data) { this.mode = Mode.BYTE if (typeof (data) === 'string') { this.data = encodeUtf8(data) } else { this.data = new Uint8Array(data) } } ByteData.getBitsLength = function getBitsLength (length) { return length * 8 } ByteData.prototype.getLength = function getLength () { return this.data.length } ByteData.prototype.getBitsLength = function getBitsLength () { return ByteData.getBitsLength(this.data.length) } ByteData.prototype.write = function (bitBuffer) { for (let i = 0, l = this.data.length; i < l; i++) { bitBuffer.put(this.data[i], 8) } } module.exports = ByteData