UNPKG

pbrtools

Version:
142 lines (141 loc) 3.9 kB
"use strict"; function str2Array(str) { //var te = window['TextEncoder']; var te = require('text-encoding').TextEncoder; if (te) { return (new te()).encode(str); } else { throw ('no TextEncoder support!'); } } class BufferReader { constructor() { this.readpos = 0; } init(buff) { this.buff = buff; this.viewer = new DataView(buff, 0); } readString() { var l = this.viewer.getUint16(this.readpos, true); this.readpos += 2; var strBuff = this.buff.slice(this.readpos, l + this.readpos); this.readpos += l; //var texdec = window['TextDecoder'] as any; var texdec = require('text-encoding').TextDecoder; var str = ''; if (texdec) { var dec = new texdec(); str = dec.decode(new Uint8Array(strBuff)); } else { alert('不支持TextDecoder'); } return str; //str = String.fromCharCode.apply(null, } readU8() { var r = this.viewer.getUint8(this.readpos); this.readpos++; return r; } readU16() { var r = this.viewer.getUint16(this.readpos, true); this.readpos += 2; return r; } readU32() { var r = this.viewer.getUint32(this.readpos, true); this.readpos += 4; return r; } readF32() { var r = this.viewer.getFloat32(this.readpos, true); this.readpos += 4; return r; } seek(pos) { this.readpos = pos; } } exports.BufferReader = BufferReader; /** * 字符串的写按照先uint16 len再utf8内容的方式 */ class BufferWriter { constructor(sz) { this._writePos = 0; this.nowrite = false; if (sz > 0) { this.buff = new ArrayBuffer(sz); this.datav = new DataView(this.buff); } } getStrSize(str) { return 2 + str2Array(str).length; } wstr(str) { var strarr = str2Array(str); this.wu16(strarr.length); if (!this.nowrite) { var udata = new Uint8Array(strarr); new Uint8Array(this.buff, this._writePos).set(udata); //TODO test } this._writePos += strarr.length; return this; } ; wu16(n) { if (!this.nowrite) this.datav.setUint16(this._writePos, n, true); this._writePos += 2; return this; } ; wu8(n) { if (!this.nowrite) this.datav.setUint8(this._writePos, n); this._writePos++; return this; } ; wu32(n) { if (!this.nowrite) this.datav.setUint32(this._writePos, n, true); this._writePos += 4; return this; } ; wf32(n) { if (!this.nowrite) this.datav.setFloat32(this._writePos, n, true); this._writePos += 4; return this; } ; wab(arraybuffer, length, offset) { if (length == undefined || length == null) length = arraybuffer.byteLength; if (length == 0) return; offset = offset ? offset : 0; if (length < 0) throw "wab error - Out of bounds"; var ab = null; if (arraybuffer instanceof ArrayBuffer) ab = arraybuffer; else if (arraybuffer.buffer) ab = arraybuffer.buffer; else throw "not arraybuffer/dataview "; if (!this.nowrite) { var uint8array = new Uint8Array(ab, offset, length); new Uint8Array(this.buff).set(uint8array, this._writePos); } this._writePos += length; //需要对齐么 return this; } } exports.BufferWriter = BufferWriter;