美文网首页
js下Uint8Array合并读取的方式

js下Uint8Array合并读取的方式

作者: go含羞草 | 来源:发表于2018-07-29 10:57 被阅读0次

    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倍空间。

    相关文章

      网友评论

          本文标题:js下Uint8Array合并读取的方式

          本文链接:https://www.haomeiwen.com/subject/rgjzmftx.html