Created
May 5, 2018 20:22
-
-
Save hinzundcode/c7b2a4b464337c57ac064fe176953e88 to your computer and use it in GitHub Desktop.
read and write strings from arraybuffers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function strlen(buffer, byteOffset, byteLength) { | |
let array = new Uint8Array(buffer, byteOffset, byteLength); | |
for (let i = 0; i < array.length; i++) { | |
if (array[i] == 0) | |
return i; | |
} | |
throw new Error("invalid string: not ending with null byte"); | |
} | |
class StringView { | |
constructor(buffer, byteOffset = 0, byteLength = null) { | |
this.buffer = buffer; | |
this.byteOffset = byteOffset; | |
this.byteLength = byteLength === null ? buffer.byteLength : byteLength; | |
} | |
getString(byteOffset = 0, encoding = "utf-8") { | |
let length = strlen(this.buffer, this.byteOffset+byteOffset, this.byteLength-byteOffset); | |
let bytes = new DataView(this.buffer, this.byteOffset+byteOffset, length); | |
return new TextDecoder(encoding).decode(bytes); | |
} | |
setString(value, byteOffset = 0, encoding = "utf-8") { | |
if (encoding != "utf-8") throw new Error("only utf-8 is supported at the moment"); | |
let array = new Uint8Array(this.buffer, this.byteOffset, this.byteLength); | |
let bytes = new TextEncoder().encode(value); | |
let nullpos = byteOffset+bytes.byteLength; | |
if (nullpos >= array.length) | |
throw new RangeError("String too long"); | |
array.set(bytes, byteOffset); | |
array[nullpos] = 0; | |
return bytes.byteLength+1; | |
} | |
} | |
let buffer = new ArrayBuffer(20); | |
let array = new Uint8Array(buffer); | |
let view = new StringView(buffer); | |
let bytesWritten = view.setString("Hello World"); | |
view.setString("Foo Bar", bytesWritten); | |
console.log(array); | |
console.log(view.getString()); | |
console.log(view.getString(bytesWritten)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment