-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Open
Description
Feature Description
I need to convert between ArrayBuffer and String. I haven't found an efficient conversion method yet
I have to use encodeURI and decodeURI:
function str2buf (str) {
if (typeof str !== 'string') return EMPTY_BUF
const arr = []
const a = encodeURI(str)
for (let i = 0; i < a.length;) {
if (a[i] === '%') {
arr.push(Number.parseInt(a.slice(i+1, i+3), 16))
i += 3
} else {
arr.push(a.charCodeAt(i))
i++
}
}
const buf = Uint8Array.from(arr)
return buf.buffer
}
function buf2str(buf) {
if (!buf) return ''
if (Object.prototype.toString.apply(buf) === '[object ArrayBuffer]') buf = new Uint8Array(buf)
if (Object.prototype.toString.apply(buf) !== '[object Uint8Array]') return ''
const length = buf.byteLength
const arr = []
for (let i = 0; i < length;) {
// ascii
if (buf[i] < 0x7f) {
arr.push(String.fromCharCode(buf[i]))
i++
} else {
const cc = []
for (;i > length || (buf[i] > 0x7f);) {
cc.push('%')
cc.push((buf[i]).toString(16).padStart(2, '0'))
i += 1
}
arr.push(decodeURI(cc.join('')))
}
}
return arr.join('')
}
Suggested Solution (optional)
No response
Already existing or connected issues / PRs (optional)
No response
fullheart and wendyn-projects