kig / DataStream.js

DataStream.js is a library for reading data from ArrayBuffers
173 stars 39 forks source link

RangeErrors when using readString() #3

Closed andygup closed 10 years ago

andygup commented 10 years ago

When using Chrome, I encountered range limits when using readString on large binary objects.

In order to get around these errors I modified the readString method as follows. I haven't 100% tested this but I figured I would share in case anyone else encounters these issues:

DataStream.prototype.readString = function(length, encoding) {
    if (encoding == null || encoding == "ASCII") {
        try{
            var str = "";
            var arr =  this.mapUint8Array(length == null ? this.byteLength-this.position : length);
            var length = arr.length;
            for (var i=0; i < length; i++){
                str += String.fromCharCode(arr[i])
            }
            //return String.fromCharCode.apply(null,arr);
            return str
        }
        catch(err){
            console.error("ERROR " + err.message)
        }
    } else {
        return (new TextDecoder(encoding)).decode(this.mapUint8Array(length));
    }
};
kig commented 10 years ago

Good catch, thanks! Do you have any more detail on how long strings this starts to happen? Or benchmarks for the two approaches. The reason I wanted to avoid str += String.fromCharCode(...) was my assumption that applying fromCharCode to an array would be a lot faster. If that's not the case, I'd be happy to go with this version. Well, if this version works for arbitrary-size strings, I'd go with this version as well.

kig commented 10 years ago

According to this jsPerf the speed is not an issue. What's more, the loop is faster on Firefox.