Skip to content

ByteBuffer.wrap should accept an array #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pocesar opened this issue Mar 2, 2014 · 0 comments
Closed

ByteBuffer.wrap should accept an array #10

pocesar opened this issue Mar 2, 2014 · 0 comments

Comments

@pocesar
Copy link

pocesar commented Mar 2, 2014

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants