Skip to content

ByteBuffer.wrap should accept an array #10

@pocesar

Description

@pocesar

Is there any reason why ByteBuffer.wrap can't use a plain array? If it can already use a string, why couldn't use an array?

I'm saying this because I've created a new prototype function called readBytes that looks as the following:

  ByteBuffer.prototype.readBytes = function (length, offset){
    length = typeof length !== 'undefined' ? length : this.length;
    offset = typeof offset !== 'undefined' ? offset : (this.offset+=length)-length;
    if (offset + length > this.array.byteLength) {
      throw(new Error('Cannot read ' + length + ' bytes from ' + this + ' at ' + offset + ': Capacity overflow'));
    }

    var out = new ByteBuffer(length, this.littleEndian); // this instead of []
    for (var i = 0; i < length; i++) {
      out.writeUint8(this.view.getInt8(offset + i, this.littleEndian)); // this instead of out.push()
    }
    out.flip();

    return out; // returns a bytebuffer instead of array, since cant use ByteBuffer.wrap on array
  };

ByteBuffer.wrap errors out with Cannot wrap buffer of type object, Array. I know it expects a native Buffer, ByteBuffer or ArrayBuffer, but I wanted to keep it "neutral", so I can use it on the browser, is it possible or I should use a typed array anyway?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions