Uint8Array再新建的時候就固定大小了,一個模塊需要一直存入流,另一個模塊需要一直讀取流。這樣的模型發現沒有,就自己寫了一個,如下:
function ByteArray(){
this.list=[];
this.byteOffset=0;
this.length=0;
}
var p=ByteArray.prototype;
p.push=function(unit8Arr){
this.list.push(unit8Arr);
this.length+=unit8Arr.length;
}
p.readBytes=function(len){
if(len>0){
let rbuf=new Uint8Array(len);
let rbuf_ind=0;
while(rbuf_ind<len){
if(this.list.length>0){
let tmpbuf=this.list.shift();
let tmplen=tmpbuf.length;
let last_len=len-rbuf_ind;
if(tmplen>=last_len){
//足夠了
let tmpbuf2 = tmpbuf.subarray(0, last_len);
rbuf.set(tmpbuf2,rbuf_ind);
rbuf_ind+=tmpbuf2.length;
if(last_len<tmplen){
let newUint8Array = tmpbuf.subarray(last_len, tmplen);
this.list.unshift(newUint8Array);
}
break;
}else{
rbuf.set(tmpbuf,rbuf_ind);
rbuf_ind+=tmplen;
}
}else{
rbuf=rbuf.subarray(0, rbuf_ind);
break;
}
}
this.length-=rbuf.length;
return rbuf;
}
return null;
}
module.exports=ByteArray;
使用方式:
var byte=new ByteArray();
byte.push(new Uint8Array([1,2,4,5]));
byte.push(new Uint8Array([5,3,4,5]));
byte.readBytes(2);
byte.readBytes(2);
還有個方法就是模仿go 字符串的拼接寫法。先給一個緩存空間如1024,滿了以后再增加1.5倍空間。