jackxiao / jslibs

Automatically exported from code.google.com/p/jslibs
0 stars 0 forks source link

Provide peek(), poke(), insert(), ndread() for buffers #108

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
Please consider providing functionality in native code, equivalent to the 
following:

// Non-destructively retrieve values from a specified offset of the buffer
// offset: positive integer less than buffer length - offset to start read
// len: positive integer less than (buffer length - offset) - bytes to read
// returns: String containing the bytes that were read

Buffer.prototype.peek = function (offset, len) {

    var start,
        val;

    start = new Buffer();
    start.write(this.read(offset), offset);
    val = this.ndRead(len);
    this.unread(start);
    return val;

};

// offset: offset to start inserting data
// data: data to insert as anything compatible with Buffer.write (another 
buffer, string, etc)
// insert: true = insert non-destructively at the given offset, used to 
alias insert from this.
// returns: any overwritten data, or an empty string if none
Buffer.prototype.poke = function (offset, data, insert) {

    var len = data.length,
        oldData = -1,
        start;

    start = new Buffer();
    start.write(this.read(offset), offset);

    if (insert === true) {
        this.ndRead(len);
    } else {
        oldData = this.read(len);
    }

    this.unread(data);
    this.unread(start);
    return oldData;

};

// Insert data non-destructively into a buffer
// See Buffer.prototype.poke

Buffer.prototype.insert = function(offset, data) {
    return this.poke(offset, data, true);
};

// Non-destructively read the buffer
// Self-explanatory

Buffer.prototype.ndRead = function (len) {
    return this.unread(this.read(len));
};

Attached file has a more complete implementation with more checking and 
unit tests for use until jslibs does this natively.

Original issue reported on code.google.com by phil_rho...@rocketmail.com on 25 Dec 2009 at 3:01

Attachments: