Skip to content

Instantly share code, notes, and snippets.

@lynxerzhang
Created May 25, 2017 08:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lynxerzhang/bd74064bcd5108f967a1799647d6cedf to your computer and use it in GitHub Desktop.
Save lynxerzhang/bd74064bcd5108f967a1799647d6cedf to your computer and use it in GitHub Desktop.
encapsulate js ArrayBuffer class and DataView class
//在构造函数中创建了一个DataView对象和一个position变量追踪当前指针指向哪个字节。
class ByteArray extends ArrayBuffer
{
constructor(...args) {
super(...args);
this.dataView = new DataView(this);
this.position = 0;
}
get length(){
return this.byteLength;
}
get bytesAvailable(){
let diff = this.byteLength - this.position;
if(diff < 0){
diff = 0;
}
return diff;
}
writeInt8(value){
this.dataView.setInt8(this.position, value);
this.position += 1;
}
writeUint8(value){
this.dataView.setUint8(this.position, value);
this.position += 1;
}
writeInt16(value){
this.dataView.setInt16(this.position, value);
this.position += 2;
}
writeUint16(value){
this.dataView.setUint16(this.position, value);
this.position += 2;
}
writeInt32(value){
this.dataView.setInt32(this.position, value);
this.position += 4;
}
writeUint32(value){
this.dataView.setUint32(this.position, value);
this.position += 4;
}
writeFloat32(value){
this.dataView.setFloat32(this.position, value);
this.position += 4;
}
writeFloat64(value){
this.dataView.setFloat64(this.position, value);
this.position += 8;
}
readInt8(){
let result = this.dataView.getInt8(this.position);
this.position += 1;
return result;
}
readUint8(){
let result = this.dataView.getUint8(this.position);
this.position += 1;
return result;
}
readInt16(){
let result = this.dataView.getInt16(this.position);
this.position += 2;
return result;
}
readUint16(){
let result = this.dataView.getUint16(this.position);
this.position += 2;
return result;
}
readInt32(){
let result = this.dataView.getInt32(this.position);
this.position += 4;
return result;
}
readUint32(){
let result = this.dataView.getUint32(this.position);
this.position += 4;
return result;
}
readFloat32(){
let result = this.dataView.getFloat32(this.position);
this.position += 4;
return result;
}
readFloat64(){
let result = this.dataView.getFloat64(this.position);
this.position += 8;
return result;
}
}
//example
var ds = new ByteArray(32);
console.log("length is:", ds.length, "position is:", ds.position, "bytesAvaliable is:", ds.bytesAvailable); //32, 0, 32
ds.writeInt32(10); //作为32位的整数写入(4个字节)
ds.writeInt16(12); //作为16位的整数写入(2个字节)
console.log("length is:", ds.length, "position is:", ds.position, "bytesAvaliable is:", ds.bytesAvailable); //32, 6, 26
ds.position = 0;
console.log(ds.readInt32()); //10
console.log(ds.readInt16()); //12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment