12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746 |
- /*
- Copyright 2013-2014 Daniel Wirtz <dcode@dcode.io>
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
- /**
- * @license bytebuffer.js (c) 2015 Daniel Wirtz <dcode@dcode.io>
- * Backing buffer: ArrayBuffer, Accessor: Uint8Array
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/bytebuffer.js for details
- */
- (function(global, factory) {
- /* AMD */ if (typeof define === 'function' && define["amd"])
- define(["long"], factory);
- /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
- module['exports'] = (function() {
- var Long; try { Long = require("long"); } catch (e) {}
- return factory(Long);
- })();
- /* Global */ else
- (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
- })(this, function(Long) {
- "use strict";
- /**
- * Constructs a new ByteBuffer.
- * @class The swiss army knife for binary data in JavaScript.
- * @exports ByteBuffer
- * @constructor
- * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @expose
- */
- var ByteBuffer = function(capacity, littleEndian, noAssert) {
- if (typeof capacity === 'undefined')
- capacity = ByteBuffer.DEFAULT_CAPACITY;
- if (typeof littleEndian === 'undefined')
- littleEndian = ByteBuffer.DEFAULT_ENDIAN;
- if (typeof noAssert === 'undefined')
- noAssert = ByteBuffer.DEFAULT_NOASSERT;
- if (!noAssert) {
- capacity = capacity | 0;
- if (capacity < 0)
- throw RangeError("Illegal capacity");
- littleEndian = !!littleEndian;
- noAssert = !!noAssert;
- }
- /**
- * Backing ArrayBuffer.
- * @type {!ArrayBuffer}
- * @expose
- */
- this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
- /**
- * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
- * @type {?Uint8Array}
- * @expose
- */
- this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
- /**
- * Absolute read/write offset.
- * @type {number}
- * @expose
- * @see ByteBuffer#flip
- * @see ByteBuffer#clear
- */
- this.offset = 0;
- /**
- * Marked offset.
- * @type {number}
- * @expose
- * @see ByteBuffer#mark
- * @see ByteBuffer#reset
- */
- this.markedOffset = -1;
- /**
- * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
- * @type {number}
- * @expose
- * @see ByteBuffer#flip
- * @see ByteBuffer#clear
- */
- this.limit = capacity;
- /**
- * Whether to use little endian byte order, defaults to `false` for big endian.
- * @type {boolean}
- * @expose
- */
- this.littleEndian = littleEndian;
- /**
- * Whether to skip assertions of offsets and values, defaults to `false`.
- * @type {boolean}
- * @expose
- */
- this.noAssert = noAssert;
- };
- /**
- * ByteBuffer version.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.VERSION = "5.0.1";
- /**
- * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
- * @type {boolean}
- * @const
- * @expose
- */
- ByteBuffer.LITTLE_ENDIAN = true;
- /**
- * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
- * @type {boolean}
- * @const
- * @expose
- */
- ByteBuffer.BIG_ENDIAN = false;
- /**
- * Default initial capacity of `16`.
- * @type {number}
- * @expose
- */
- ByteBuffer.DEFAULT_CAPACITY = 16;
- /**
- * Default endianess of `false` for big endian.
- * @type {boolean}
- * @expose
- */
- ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
- /**
- * Default no assertions flag of `false`.
- * @type {boolean}
- * @expose
- */
- ByteBuffer.DEFAULT_NOASSERT = false;
- /**
- * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
- * and int64 support is not available.
- * @type {?Long}
- * @const
- * @see https://github.com/dcodeIO/long.js
- * @expose
- */
- ByteBuffer.Long = Long || null;
- /**
- * @alias ByteBuffer.prototype
- * @inner
- */
- var ByteBufferPrototype = ByteBuffer.prototype;
- /**
- * An indicator used to reliably determine if an object is a ByteBuffer or not.
- * @type {boolean}
- * @const
- * @expose
- * @private
- */
- ByteBufferPrototype.__isByteBuffer__;
- Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
- value: true,
- enumerable: false,
- configurable: false
- });
- // helpers
- /**
- * @type {!ArrayBuffer}
- * @inner
- */
- var EMPTY_BUFFER = new ArrayBuffer(0);
- /**
- * String.fromCharCode reference for compile-time renaming.
- * @type {function(...number):string}
- * @inner
- */
- var stringFromCharCode = String.fromCharCode;
- /**
- * Creates a source function for a string.
- * @param {string} s String to read from
- * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
- * no more characters left.
- * @throws {TypeError} If the argument is invalid
- * @inner
- */
- function stringSource(s) {
- var i=0; return function() {
- return i < s.length ? s.charCodeAt(i++) : null;
- };
- }
- /**
- * Creates a destination function for a string.
- * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
- * Returns the final string when called without arguments.
- * @inner
- */
- function stringDestination() {
- var cs = [], ps = []; return function() {
- if (arguments.length === 0)
- return ps.join('')+stringFromCharCode.apply(String, cs);
- if (cs.length + arguments.length > 1024)
- ps.push(stringFromCharCode.apply(String, cs)),
- cs.length = 0;
- Array.prototype.push.apply(cs, arguments);
- };
- }
- /**
- * Gets the accessor type.
- * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
- * @expose
- */
- ByteBuffer.accessor = function() {
- return Uint8Array;
- };
- /**
- * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
- * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
- return new ByteBuffer(capacity, littleEndian, noAssert);
- };
- /**
- * Concatenates multiple ByteBuffers into one.
- * @param {!Array.<!ByteBuffer|!ArrayBuffer|!Uint8Array|string>} buffers Buffers to concatenate
- * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
- * defaults to "utf8")
- * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
- * to {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} Concatenated ByteBuffer
- * @expose
- */
- ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
- if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
- noAssert = littleEndian;
- littleEndian = encoding;
- encoding = undefined;
- }
- var capacity = 0;
- for (var i=0, k=buffers.length, length; i<k; ++i) {
- if (!ByteBuffer.isByteBuffer(buffers[i]))
- buffers[i] = ByteBuffer.wrap(buffers[i], encoding);
- length = buffers[i].limit - buffers[i].offset;
- if (length > 0) capacity += length;
- }
- if (capacity === 0)
- return new ByteBuffer(0, littleEndian, noAssert);
- var bb = new ByteBuffer(capacity, littleEndian, noAssert),
- bi;
- i=0; while (i<k) {
- bi = buffers[i++];
- length = bi.limit - bi.offset;
- if (length <= 0) continue;
- bb.view.set(bi.view.subarray(bi.offset, bi.limit), bb.offset);
- bb.offset += length;
- }
- bb.limit = bb.offset;
- bb.offset = 0;
- return bb;
- };
- /**
- * Tests if the specified type is a ByteBuffer.
- * @param {*} bb ByteBuffer to test
- * @returns {boolean} `true` if it is a ByteBuffer, otherwise `false`
- * @expose
- */
- ByteBuffer.isByteBuffer = function(bb) {
- return (bb && bb["__isByteBuffer__"]) === true;
- };
- /**
- * Gets the backing buffer type.
- * @returns {Function} `Buffer` under node.js, `ArrayBuffer` in the browser (classes)
- * @expose
- */
- ByteBuffer.type = function() {
- return ArrayBuffer;
- };
- /**
- * Wraps a buffer or a string. Sets the allocated ByteBuffer's {@link ByteBuffer#offset} to `0` and its
- * {@link ByteBuffer#limit} to the length of the wrapped data.
- * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string|!Array.<number>} buffer Anything that can be wrapped
- * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
- * "utf8")
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
- * @expose
- */
- ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
- if (typeof encoding !== 'string') {
- noAssert = littleEndian;
- littleEndian = encoding;
- encoding = undefined;
- }
- if (typeof buffer === 'string') {
- if (typeof encoding === 'undefined')
- encoding = "utf8";
- switch (encoding) {
- case "base64":
- return ByteBuffer.fromBase64(buffer, littleEndian);
- case "hex":
- return ByteBuffer.fromHex(buffer, littleEndian);
- case "binary":
- return ByteBuffer.fromBinary(buffer, littleEndian);
- case "utf8":
- return ByteBuffer.fromUTF8(buffer, littleEndian);
- case "debug":
- return ByteBuffer.fromDebug(buffer, littleEndian);
- default:
- throw Error("Unsupported encoding: "+encoding);
- }
- }
- if (buffer === null || typeof buffer !== 'object')
- throw TypeError("Illegal buffer");
- var bb;
- if (ByteBuffer.isByteBuffer(buffer)) {
- bb = ByteBufferPrototype.clone.call(buffer);
- bb.markedOffset = -1;
- return bb;
- }
- if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
- bb = new ByteBuffer(0, littleEndian, noAssert);
- if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
- bb.buffer = buffer.buffer;
- bb.offset = buffer.byteOffset;
- bb.limit = buffer.byteOffset + buffer.byteLength;
- bb.view = new Uint8Array(buffer.buffer);
- }
- } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
- bb = new ByteBuffer(0, littleEndian, noAssert);
- if (buffer.byteLength > 0) {
- bb.buffer = buffer;
- bb.offset = 0;
- bb.limit = buffer.byteLength;
- bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
- }
- } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
- bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
- bb.limit = buffer.length;
- for (var i=0; i<buffer.length; ++i)
- bb.view[i] = buffer[i];
- } else
- throw TypeError("Illegal buffer"); // Otherwise fail
- return bb;
- };
- /**
- * Writes the array as a bitset.
- * @param {Array<boolean>} value Array of booleans to write
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBufferPrototype.writeBitSet = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (!(value instanceof Array))
- throw TypeError("Illegal BitSet: Not an array");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- bits = value.length,
- bytes = (bits >> 3),
- bit = 0,
- k;
- offset += this.writeVarint32(bits,offset);
- while(bytes--) {
- k = (!!value[bit++] & 1) |
- ((!!value[bit++] & 1) << 1) |
- ((!!value[bit++] & 1) << 2) |
- ((!!value[bit++] & 1) << 3) |
- ((!!value[bit++] & 1) << 4) |
- ((!!value[bit++] & 1) << 5) |
- ((!!value[bit++] & 1) << 6) |
- ((!!value[bit++] & 1) << 7);
- this.writeByte(k,offset++);
- }
- if(bit < bits) {
- var m = 0; k = 0;
- while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
- this.writeByte(k,offset++);
- }
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- }
- /**
- * Reads a BitSet as an array of booleans.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {Array<boolean>
- * @expose
- */
- ByteBufferPrototype.readBitSet = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- var ret = this.readVarint32(offset),
- bits = ret.value,
- bytes = (bits >> 3),
- bit = 0,
- value = [],
- k;
- offset += ret.length;
- while(bytes--) {
- k = this.readByte(offset++);
- value[bit++] = !!(k & 0x01);
- value[bit++] = !!(k & 0x02);
- value[bit++] = !!(k & 0x04);
- value[bit++] = !!(k & 0x08);
- value[bit++] = !!(k & 0x10);
- value[bit++] = !!(k & 0x20);
- value[bit++] = !!(k & 0x40);
- value[bit++] = !!(k & 0x80);
- }
- if(bit < bits) {
- var m = 0;
- k = this.readByte(offset++);
- while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
- }
- if (relative) {
- this.offset = offset;
- }
- return value;
- }
- /**
- * Reads the specified number of bytes.
- * @param {number} length Number of bytes to read
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBufferPrototype.readBytes = function(length, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + length > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
- }
- var slice = this.slice(offset, offset + length);
- if (relative) this.offset += length;
- return slice;
- };
- /**
- * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
- * @function
- * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
- * will be modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
- // types/ints/int8
- /**
- * Writes an 8bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeInt8 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 1;
- var capacity0 = this.buffer.byteLength;
- if (offset > capacity0)
- this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
- offset -= 1;
- this.view[offset] = value;
- if (relative) this.offset += 1;
- return this;
- };
- /**
- * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
- /**
- * Reads an 8bit signed integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt8 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var value = this.view[offset];
- if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
- if (relative) this.offset += 1;
- return value;
- };
- /**
- * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
- /**
- * Writes an 8bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUint8 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 1;
- var capacity1 = this.buffer.byteLength;
- if (offset > capacity1)
- this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
- offset -= 1;
- this.view[offset] = value;
- if (relative) this.offset += 1;
- return this;
- };
- /**
- * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
- /**
- * Reads an 8bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUint8 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var value = this.view[offset];
- if (relative) this.offset += 1;
- return value;
- };
- /**
- * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
- // types/ints/int16
- /**
- * Writes a 16bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeInt16 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 2;
- var capacity2 = this.buffer.byteLength;
- if (offset > capacity2)
- this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
- offset -= 2;
- if (this.littleEndian) {
- this.view[offset+1] = (value & 0xFF00) >>> 8;
- this.view[offset ] = value & 0x00FF;
- } else {
- this.view[offset] = (value & 0xFF00) >>> 8;
- this.view[offset+1] = value & 0x00FF;
- }
- if (relative) this.offset += 2;
- return this;
- };
- /**
- * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
- /**
- * Reads a 16bit signed integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readInt16 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 2 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset ];
- value |= this.view[offset+1] << 8;
- } else {
- value = this.view[offset ] << 8;
- value |= this.view[offset+1];
- }
- if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
- if (relative) this.offset += 2;
- return value;
- };
- /**
- * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
- /**
- * Writes a 16bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeUint16 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 2;
- var capacity3 = this.buffer.byteLength;
- if (offset > capacity3)
- this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
- offset -= 2;
- if (this.littleEndian) {
- this.view[offset+1] = (value & 0xFF00) >>> 8;
- this.view[offset ] = value & 0x00FF;
- } else {
- this.view[offset] = (value & 0xFF00) >>> 8;
- this.view[offset+1] = value & 0x00FF;
- }
- if (relative) this.offset += 2;
- return this;
- };
- /**
- * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
- /**
- * Reads a 16bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readUint16 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 2 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset ];
- value |= this.view[offset+1] << 8;
- } else {
- value = this.view[offset ] << 8;
- value |= this.view[offset+1];
- }
- if (relative) this.offset += 2;
- return value;
- };
- /**
- * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
- // types/ints/int32
- /**
- * Writes a 32bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeInt32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity4 = this.buffer.byteLength;
- if (offset > capacity4)
- this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
- offset -= 4;
- if (this.littleEndian) {
- this.view[offset+3] = (value >>> 24) & 0xFF;
- this.view[offset+2] = (value >>> 16) & 0xFF;
- this.view[offset+1] = (value >>> 8) & 0xFF;
- this.view[offset ] = value & 0xFF;
- } else {
- this.view[offset ] = (value >>> 24) & 0xFF;
- this.view[offset+1] = (value >>> 16) & 0xFF;
- this.view[offset+2] = (value >>> 8) & 0xFF;
- this.view[offset+3] = value & 0xFF;
- }
- if (relative) this.offset += 4;
- return this;
- };
- /**
- * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
- /**
- * Reads a 32bit signed integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset+2] << 16;
- value |= this.view[offset+1] << 8;
- value |= this.view[offset ];
- value += this.view[offset+3] << 24 >>> 0;
- } else {
- value = this.view[offset+1] << 16;
- value |= this.view[offset+2] << 8;
- value |= this.view[offset+3];
- value += this.view[offset ] << 24 >>> 0;
- }
- value |= 0; // Cast to signed
- if (relative) this.offset += 4;
- return value;
- };
- /**
- * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
- /**
- * Writes a 32bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeUint32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity5 = this.buffer.byteLength;
- if (offset > capacity5)
- this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
- offset -= 4;
- if (this.littleEndian) {
- this.view[offset+3] = (value >>> 24) & 0xFF;
- this.view[offset+2] = (value >>> 16) & 0xFF;
- this.view[offset+1] = (value >>> 8) & 0xFF;
- this.view[offset ] = value & 0xFF;
- } else {
- this.view[offset ] = (value >>> 24) & 0xFF;
- this.view[offset+1] = (value >>> 16) & 0xFF;
- this.view[offset+2] = (value >>> 8) & 0xFF;
- this.view[offset+3] = value & 0xFF;
- }
- if (relative) this.offset += 4;
- return this;
- };
- /**
- * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
- /**
- * Reads a 32bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUint32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset+2] << 16;
- value |= this.view[offset+1] << 8;
- value |= this.view[offset ];
- value += this.view[offset+3] << 24 >>> 0;
- } else {
- value = this.view[offset+1] << 16;
- value |= this.view[offset+2] << 8;
- value |= this.view[offset+3];
- value += this.view[offset ] << 24 >>> 0;
- }
- if (relative) this.offset += 4;
- return value;
- };
- /**
- * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
- // types/ints/int64
- if (Long) {
- /**
- * Writes a 64bit signed integer.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeInt64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- offset += 8;
- var capacity6 = this.buffer.byteLength;
- if (offset > capacity6)
- this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
- offset -= 8;
- var lo = value.low,
- hi = value.high;
- if (this.littleEndian) {
- this.view[offset+3] = (lo >>> 24) & 0xFF;
- this.view[offset+2] = (lo >>> 16) & 0xFF;
- this.view[offset+1] = (lo >>> 8) & 0xFF;
- this.view[offset ] = lo & 0xFF;
- offset += 4;
- this.view[offset+3] = (hi >>> 24) & 0xFF;
- this.view[offset+2] = (hi >>> 16) & 0xFF;
- this.view[offset+1] = (hi >>> 8) & 0xFF;
- this.view[offset ] = hi & 0xFF;
- } else {
- this.view[offset ] = (hi >>> 24) & 0xFF;
- this.view[offset+1] = (hi >>> 16) & 0xFF;
- this.view[offset+2] = (hi >>> 8) & 0xFF;
- this.view[offset+3] = hi & 0xFF;
- offset += 4;
- this.view[offset ] = (lo >>> 24) & 0xFF;
- this.view[offset+1] = (lo >>> 16) & 0xFF;
- this.view[offset+2] = (lo >>> 8) & 0xFF;
- this.view[offset+3] = lo & 0xFF;
- }
- if (relative) this.offset += 8;
- return this;
- };
- /**
- * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
- /**
- * Reads a 64bit signed integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readInt64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var lo = 0,
- hi = 0;
- if (this.littleEndian) {
- lo = this.view[offset+2] << 16;
- lo |= this.view[offset+1] << 8;
- lo |= this.view[offset ];
- lo += this.view[offset+3] << 24 >>> 0;
- offset += 4;
- hi = this.view[offset+2] << 16;
- hi |= this.view[offset+1] << 8;
- hi |= this.view[offset ];
- hi += this.view[offset+3] << 24 >>> 0;
- } else {
- hi = this.view[offset+1] << 16;
- hi |= this.view[offset+2] << 8;
- hi |= this.view[offset+3];
- hi += this.view[offset ] << 24 >>> 0;
- offset += 4;
- lo = this.view[offset+1] << 16;
- lo |= this.view[offset+2] << 8;
- lo |= this.view[offset+3];
- lo += this.view[offset ] << 24 >>> 0;
- }
- var value = new Long(lo, hi, false);
- if (relative) this.offset += 8;
- return value;
- };
- /**
- * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
- /**
- * Writes a 64bit unsigned integer.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUint64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- offset += 8;
- var capacity7 = this.buffer.byteLength;
- if (offset > capacity7)
- this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
- offset -= 8;
- var lo = value.low,
- hi = value.high;
- if (this.littleEndian) {
- this.view[offset+3] = (lo >>> 24) & 0xFF;
- this.view[offset+2] = (lo >>> 16) & 0xFF;
- this.view[offset+1] = (lo >>> 8) & 0xFF;
- this.view[offset ] = lo & 0xFF;
- offset += 4;
- this.view[offset+3] = (hi >>> 24) & 0xFF;
- this.view[offset+2] = (hi >>> 16) & 0xFF;
- this.view[offset+1] = (hi >>> 8) & 0xFF;
- this.view[offset ] = hi & 0xFF;
- } else {
- this.view[offset ] = (hi >>> 24) & 0xFF;
- this.view[offset+1] = (hi >>> 16) & 0xFF;
- this.view[offset+2] = (hi >>> 8) & 0xFF;
- this.view[offset+3] = hi & 0xFF;
- offset += 4;
- this.view[offset ] = (lo >>> 24) & 0xFF;
- this.view[offset+1] = (lo >>> 16) & 0xFF;
- this.view[offset+2] = (lo >>> 8) & 0xFF;
- this.view[offset+3] = lo & 0xFF;
- }
- if (relative) this.offset += 8;
- return this;
- };
- /**
- * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
- * @function
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
- /**
- * Reads a 64bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readUint64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var lo = 0,
- hi = 0;
- if (this.littleEndian) {
- lo = this.view[offset+2] << 16;
- lo |= this.view[offset+1] << 8;
- lo |= this.view[offset ];
- lo += this.view[offset+3] << 24 >>> 0;
- offset += 4;
- hi = this.view[offset+2] << 16;
- hi |= this.view[offset+1] << 8;
- hi |= this.view[offset ];
- hi += this.view[offset+3] << 24 >>> 0;
- } else {
- hi = this.view[offset+1] << 16;
- hi |= this.view[offset+2] << 8;
- hi |= this.view[offset+3];
- hi += this.view[offset ] << 24 >>> 0;
- offset += 4;
- lo = this.view[offset+1] << 16;
- lo |= this.view[offset+2] << 8;
- lo |= this.view[offset+3];
- lo += this.view[offset ] << 24 >>> 0;
- }
- var value = new Long(lo, hi, true);
- if (relative) this.offset += 8;
- return value;
- };
- /**
- * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
- } // Long
- // types/floats/float32
- /*
- ieee754 - https://github.com/feross/ieee754
- The MIT License (MIT)
- Copyright (c) Feross Aboukhadijeh
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- */
- /**
- * Reads an IEEE754 float from a byte array.
- * @param {!Array} buffer
- * @param {number} offset
- * @param {boolean} isLE
- * @param {number} mLen
- * @param {number} nBytes
- * @returns {number}
- * @inner
- */
- function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
- var e, m,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- nBits = -7,
- i = isLE ? (nBytes - 1) : 0,
- d = isLE ? -1 : 1,
- s = buffer[offset + i];
- i += d;
- e = s & ((1 << (-nBits)) - 1);
- s >>= (-nBits);
- nBits += eLen;
- for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- m = e & ((1 << (-nBits)) - 1);
- e >>= (-nBits);
- nBits += mLen;
- for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
- if (e === 0) {
- e = 1 - eBias;
- } else if (e === eMax) {
- return m ? NaN : ((s ? -1 : 1) * Infinity);
- } else {
- m = m + Math.pow(2, mLen);
- e = e - eBias;
- }
- return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
- }
- /**
- * Writes an IEEE754 float to a byte array.
- * @param {!Array} buffer
- * @param {number} value
- * @param {number} offset
- * @param {boolean} isLE
- * @param {number} mLen
- * @param {number} nBytes
- * @inner
- */
- function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
- i = isLE ? 0 : (nBytes - 1),
- d = isLE ? 1 : -1,
- s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;
- value = Math.abs(value);
- if (isNaN(value) || value === Infinity) {
- m = isNaN(value) ? 1 : 0;
- e = eMax;
- } else {
- e = Math.floor(Math.log(value) / Math.LN2);
- if (value * (c = Math.pow(2, -e)) < 1) {
- e--;
- c *= 2;
- }
- if (e + eBias >= 1) {
- value += rt / c;
- } else {
- value += rt * Math.pow(2, 1 - eBias);
- }
- if (value * c >= 2) {
- e++;
- c /= 2;
- }
- if (e + eBias >= eMax) {
- m = 0;
- e = eMax;
- } else if (e + eBias >= 1) {
- m = (value * c - 1) * Math.pow(2, mLen);
- e = e + eBias;
- } else {
- m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
- e = 0;
- }
- }
- for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
- e = (e << mLen) | m;
- eLen += mLen;
- for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
- buffer[offset + i - d] |= s * 128;
- }
- /**
- * Writes a 32bit float.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number')
- throw TypeError("Illegal value: "+value+" (not a number)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity8 = this.buffer.byteLength;
- if (offset > capacity8)
- this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
- offset -= 4;
- ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
- if (relative) this.offset += 4;
- return this;
- };
- /**
- * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
- /**
- * Reads a 32bit float.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
- if (relative) this.offset += 4;
- return value;
- };
- /**
- * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
- // types/floats/float64
- /**
- * Writes a 64bit float.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number')
- throw TypeError("Illegal value: "+value+" (not a number)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 8;
- var capacity9 = this.buffer.byteLength;
- if (offset > capacity9)
- this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
- offset -= 8;
- ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
- if (relative) this.offset += 8;
- return this;
- };
- /**
- * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
- /**
- * Reads a 64bit float.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
- if (relative) this.offset += 8;
- return value;
- };
- /**
- * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
- // types/varints/varint32
- /**
- * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
- * @type {number}
- * @const
- * @expose
- */
- ByteBuffer.MAX_VARINT32_BYTES = 5;
- /**
- * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
- * @param {number} value Value to encode
- * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
- * @expose
- */
- ByteBuffer.calculateVarint32 = function(value) {
- // ref: src/google/protobuf/io/coded_stream.cc
- value = value >>> 0;
- if (value < 1 << 7 ) return 1;
- else if (value < 1 << 14) return 2;
- else if (value < 1 << 21) return 3;
- else if (value < 1 << 28) return 4;
- else return 5;
- };
- /**
- * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
- * @param {number} n Signed 32bit integer
- * @returns {number} Unsigned zigzag encoded 32bit integer
- * @expose
- */
- ByteBuffer.zigZagEncode32 = function(n) {
- return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
- };
- /**
- * Decodes a zigzag encoded signed 32bit integer.
- * @param {number} n Unsigned zigzag encoded 32bit integer
- * @returns {number} Signed 32bit integer
- * @expose
- */
- ByteBuffer.zigZagDecode32 = function(n) {
- return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
- };
- /**
- * Writes a 32bit base 128 variable-length integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeVarint32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var size = ByteBuffer.calculateVarint32(value),
- b;
- offset += size;
- var capacity10 = this.buffer.byteLength;
- if (offset > capacity10)
- this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
- offset -= size;
- value >>>= 0;
- while (value >= 0x80) {
- b = (value & 0x7f) | 0x80;
- this.view[offset++] = b;
- value >>>= 7;
- }
- this.view[offset++] = value;
- if (relative) {
- this.offset = offset;
- return this;
- }
- return size;
- };
- /**
- * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
- return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
- };
- /**
- * Reads a 32bit base 128 variable-length integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
- * and the actual number of bytes read.
- * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
- * to fully decode the varint.
- * @expose
- */
- ByteBufferPrototype.readVarint32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var c = 0,
- value = 0 >>> 0,
- b;
- do {
- if (!this.noAssert && offset > this.limit) {
- var err = Error("Truncated");
- err['truncated'] = true;
- throw err;
- }
- b = this.view[offset++];
- if (c < 5)
- value |= (b & 0x7f) << (7*c);
- ++c;
- } while ((b & 0x80) !== 0);
- value |= 0;
- if (relative) {
- this.offset = offset;
- return value;
- }
- return {
- "value": value,
- "length": c
- };
- };
- /**
- * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
- * and the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint32ZigZag = function(offset) {
- var val = this.readVarint32(offset);
- if (typeof val === 'object')
- val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
- else
- val = ByteBuffer.zigZagDecode32(val);
- return val;
- };
- // types/varints/varint64
- if (Long) {
- /**
- * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
- * @type {number}
- * @const
- * @expose
- */
- ByteBuffer.MAX_VARINT64_BYTES = 10;
- /**
- * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
- * @param {number|!Long} value Value to encode
- * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
- * @expose
- */
- ByteBuffer.calculateVarint64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- // ref: src/google/protobuf/io/coded_stream.cc
- var part0 = value.toInt() >>> 0,
- part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
- part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
- if (part2 == 0) {
- if (part1 == 0) {
- if (part0 < 1 << 14)
- return part0 < 1 << 7 ? 1 : 2;
- else
- return part0 < 1 << 21 ? 3 : 4;
- } else {
- if (part1 < 1 << 14)
- return part1 < 1 << 7 ? 5 : 6;
- else
- return part1 < 1 << 21 ? 7 : 8;
- }
- } else
- return part2 < 1 << 7 ? 9 : 10;
- };
- /**
- * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
- * @param {number|!Long} value Signed long
- * @returns {!Long} Unsigned zigzag encoded long
- * @expose
- */
- ByteBuffer.zigZagEncode64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- // ref: src/google/protobuf/wire_format_lite.h
- return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
- };
- /**
- * Decodes a zigzag encoded signed 64bit integer.
- * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
- * @returns {!Long} Signed long
- * @expose
- */
- ByteBuffer.zigZagDecode64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- // ref: src/google/protobuf/wire_format_lite.h
- return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
- };
- /**
- * Writes a 64bit base 128 variable-length integer.
- * @param {number|Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeVarint64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- var size = ByteBuffer.calculateVarint64(value),
- part0 = value.toInt() >>> 0,
- part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
- part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
- offset += size;
- var capacity11 = this.buffer.byteLength;
- if (offset > capacity11)
- this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
- offset -= size;
- switch (size) {
- case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
- case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
- case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
- case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
- case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
- case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
- case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
- case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
- case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
- case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
- }
- if (relative) {
- this.offset += size;
- return this;
- } else {
- return size;
- }
- };
- /**
- * Writes a zig-zag encoded 64bit base 128 variable-length integer.
- * @param {number|Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
- return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
- };
- /**
- * Reads a 64bit base 128 variable-length integer. Requires Long.js.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
- * the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- // ref: src/google/protobuf/io/coded_stream.cc
- var start = offset,
- part0 = 0,
- part1 = 0,
- part2 = 0,
- b = 0;
- b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- throw Error("Buffer overrun"); }}}}}}}}}}
- var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
- if (relative) {
- this.offset = offset;
- return value;
- } else {
- return {
- 'value': value,
- 'length': offset-start
- };
- }
- };
- /**
- * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
- * the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint64ZigZag = function(offset) {
- var val = this.readVarint64(offset);
- if (val && val['value'] instanceof Long)
- val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
- else
- val = ByteBuffer.zigZagDecode64(val);
- return val;
- };
- } // Long
- // types/strings/cstring
- /**
- * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
- * characters itself.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * contained in `str` + 1 if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeCString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- var i,
- k = str.length;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- for (i=0; i<k; ++i) {
- if (str.charCodeAt(i) === 0)
- throw RangeError("Illegal str: Contains NULL-characters");
- }
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- // UTF8 strings do not contain zero bytes in between except for the zero character, so:
- k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
- offset += k+1;
- var capacity12 = this.buffer.byteLength;
- if (offset > capacity12)
- this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
- offset -= k+1;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- this.view[offset++] = 0;
- if (relative) {
- this.offset = offset;
- return this;
- }
- return k;
- };
- /**
- * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
- * itself.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readCString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- temp;
- // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
- var sd, b = -1;
- utfx.decodeUTF8toUTF16(function() {
- if (b === 0) return null;
- if (offset >= this.limit)
- throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
- b = this.view[offset++];
- return b === 0 ? null : b;
- }.bind(this), sd = stringDestination(), true);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- "string": sd(),
- "length": offset - start
- };
- }
- };
- // types/strings/istring
- /**
- * Writes a length as uint32 prefixed UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
- * @expose
- * @see ByteBuffer#writeVarint32
- */
- ByteBufferPrototype.writeIString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- k;
- k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
- offset += 4+k;
- var capacity13 = this.buffer.byteLength;
- if (offset > capacity13)
- this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
- offset -= 4+k;
- if (this.littleEndian) {
- this.view[offset+3] = (k >>> 24) & 0xFF;
- this.view[offset+2] = (k >>> 16) & 0xFF;
- this.view[offset+1] = (k >>> 8) & 0xFF;
- this.view[offset ] = k & 0xFF;
- } else {
- this.view[offset ] = (k >>> 24) & 0xFF;
- this.view[offset+1] = (k >>> 16) & 0xFF;
- this.view[offset+2] = (k >>> 8) & 0xFF;
- this.view[offset+3] = k & 0xFF;
- }
- offset += 4;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (offset !== start + 4 + k)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
- /**
- * Reads a length as uint32 prefixed UTF8 encoded string.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- * @see ByteBuffer#readVarint32
- */
- ByteBufferPrototype.readIString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var start = offset;
- var len = this.readUint32(offset);
- var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
- offset += str['length'];
- if (relative) {
- this.offset = offset;
- return str['string'];
- } else {
- return {
- 'string': str['string'],
- 'length': offset - start
- };
- }
- };
- // types/strings/utf8string
- /**
- * Metrics representing number of UTF8 characters. Evaluates to `c`.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.METRICS_CHARS = 'c';
- /**
- * Metrics representing number of bytes. Evaluates to `b`.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.METRICS_BYTES = 'b';
- /**
- * Writes an UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeUTF8String = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var k;
- var start = offset;
- k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
- offset += k;
- var capacity14 = this.buffer.byteLength;
- if (offset > capacity14)
- this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
- offset -= k;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
- /**
- * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
- * @function
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
- /**
- * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
- * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 characters
- * @expose
- */
- ByteBuffer.calculateUTF8Chars = function(str) {
- return utfx.calculateUTF16asUTF8(stringSource(str))[0];
- };
- /**
- * Calculates the number of UTF8 bytes of a string.
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 bytes
- * @expose
- */
- ByteBuffer.calculateUTF8Bytes = function(str) {
- return utfx.calculateUTF16asUTF8(stringSource(str))[1];
- };
- /**
- * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
- * @function
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 bytes
- * @expose
- */
- ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
- /**
- * Reads an UTF8 encoded string.
- * @param {number} length Number of characters or bytes to read.
- * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
- * {@link ByteBuffer.METRICS_CHARS}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
- if (typeof metrics === 'number') {
- offset = metrics;
- metrics = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
- if (!this.noAssert) {
- if (typeof length !== 'number' || length % 1 !== 0)
- throw TypeError("Illegal length: "+length+" (not an integer)");
- length |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var i = 0,
- start = offset,
- sd;
- if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
- sd = stringDestination();
- utfx.decodeUTF8(function() {
- return i < length && offset < this.limit ? this.view[offset++] : null;
- }.bind(this), function(cp) {
- ++i; utfx.UTF8toUTF16(cp, sd);
- });
- if (i !== length)
- throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- "string": sd(),
- "length": offset - start
- };
- }
- } else if (metrics === ByteBuffer.METRICS_BYTES) {
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + length > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
- }
- var k = offset + length;
- utfx.decodeUTF8toUTF16(function() {
- return offset < k ? this.view[offset++] : null;
- }.bind(this), sd = stringDestination(), this.noAssert);
- if (offset !== k)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- 'string': sd(),
- 'length': offset - start
- };
- }
- } else
- throw TypeError("Unsupported metrics: "+metrics);
- };
- /**
- * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
- * @function
- * @param {number} length Number of characters or bytes to read
- * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
- * {@link ByteBuffer.METRICS_CHARS}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
- // types/strings/vstring
- /**
- * Writes a length as varint32 prefixed UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
- * @expose
- * @see ByteBuffer#writeVarint32
- */
- ByteBufferPrototype.writeVString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- k, l;
- k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
- l = ByteBuffer.calculateVarint32(k);
- offset += l+k;
- var capacity15 = this.buffer.byteLength;
- if (offset > capacity15)
- this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
- offset -= l+k;
- offset += this.writeVarint32(k, offset);
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (offset !== start+k+l)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
- /**
- * Reads a length as varint32 prefixed UTF8 encoded string.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- * @see ByteBuffer#readVarint32
- */
- ByteBufferPrototype.readVString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var start = offset;
- var len = this.readVarint32(offset);
- var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
- offset += str['length'];
- if (relative) {
- this.offset = offset;
- return str['string'];
- } else {
- return {
- 'string': str['string'],
- 'length': offset - start
- };
- }
- };
- /**
- * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
- * data's length.
- * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
- * will be modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
- * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
- */
- ByteBufferPrototype.append = function(source, encoding, offset) {
- if (typeof encoding === 'number' || typeof encoding !== 'string') {
- offset = encoding;
- encoding = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (!(source instanceof ByteBuffer))
- source = ByteBuffer.wrap(source, encoding);
- var length = source.limit - source.offset;
- if (length <= 0) return this; // Nothing to append
- offset += length;
- var capacity16 = this.buffer.byteLength;
- if (offset > capacity16)
- this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
- offset -= length;
- this.view.set(source.view.subarray(source.offset, source.limit), offset);
- source.offset += length;
- if (relative) this.offset += length;
- return this;
- };
- /**
- * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
- specified offset up to the length of this ByteBuffer's data.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @see ByteBuffer#append
- */
- ByteBufferPrototype.appendTo = function(target, offset) {
- target.append(this, offset);
- return this;
- };
- /**
- * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
- * disable them if your code already makes sure that everything is valid.
- * @param {boolean} assert `true` to enable assertions, otherwise `false`
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.assert = function(assert) {
- this.noAssert = !assert;
- return this;
- };
- /**
- * Gets the capacity of this ByteBuffer's backing buffer.
- * @returns {number} Capacity of the backing buffer
- * @expose
- */
- ByteBufferPrototype.capacity = function() {
- return this.buffer.byteLength;
- };
- /**
- * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
- * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.clear = function() {
- this.offset = 0;
- this.limit = this.buffer.byteLength;
- this.markedOffset = -1;
- return this;
- };
- /**
- * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
- * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
- * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
- * @returns {!ByteBuffer} Cloned instance
- * @expose
- */
- ByteBufferPrototype.clone = function(copy) {
- var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
- if (copy) {
- bb.buffer = new ArrayBuffer(this.buffer.byteLength);
- bb.view = new Uint8Array(bb.buffer);
- } else {
- bb.buffer = this.buffer;
- bb.view = this.view;
- }
- bb.offset = this.offset;
- bb.markedOffset = this.markedOffset;
- bb.limit = this.limit;
- return bb;
- };
- /**
- * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
- * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
- * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
- * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.compact = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === 0 && end === this.buffer.byteLength)
- return this; // Already compacted
- var len = end - begin;
- if (len === 0) {
- this.buffer = EMPTY_BUFFER;
- this.view = null;
- if (this.markedOffset >= 0) this.markedOffset -= begin;
- this.offset = 0;
- this.limit = 0;
- return this;
- }
- var buffer = new ArrayBuffer(len);
- var view = new Uint8Array(buffer);
- view.set(this.view.subarray(begin, end));
- this.buffer = buffer;
- this.view = view;
- if (this.markedOffset >= 0) this.markedOffset -= begin;
- this.offset = 0;
- this.limit = len;
- return this;
- };
- /**
- * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}.
- * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} Copy
- * @expose
- */
- ByteBufferPrototype.copy = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === end)
- return new ByteBuffer(0, this.littleEndian, this.noAssert);
- var capacity = end - begin,
- bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
- bb.offset = 0;
- bb.limit = capacity;
- if (bb.markedOffset >= 0) bb.markedOffset -= begin;
- this.copyTo(bb, 0, begin, end);
- return bb;
- };
- /**
- * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
- * by the number of bytes copied if omitted.
- * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
- * number of bytes copied if omitted.
- * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
- var relative,
- targetRelative;
- if (!this.noAssert) {
- if (!ByteBuffer.isByteBuffer(target))
- throw TypeError("Illegal target: Not a ByteBuffer");
- }
- targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
- sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
- sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
- if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
- throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
- if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
- throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
- var len = sourceLimit - sourceOffset;
- if (len === 0)
- return target; // Nothing to copy
- target.ensureCapacity(targetOffset + len);
- target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
- if (relative) this.offset += len;
- if (targetRelative) target.offset += len;
- return this;
- };
- /**
- * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
- * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
- * the required capacity will be used instead.
- * @param {number} capacity Required capacity
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.ensureCapacity = function(capacity) {
- var current = this.buffer.byteLength;
- if (current < capacity)
- return this.resize((current *= 2) > capacity ? current : capacity);
- return this;
- };
- /**
- * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
- * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
- * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted. defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} this
- * @expose
- * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
- */
- ByteBufferPrototype.fill = function(value, begin, end) {
- var relative = typeof begin === 'undefined';
- if (relative) begin = this.offset;
- if (typeof value === 'string' && value.length > 0)
- value = value.charCodeAt(0);
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin >= end)
- return this; // Nothing to fill
- while (begin < end) this.view[begin++] = value;
- if (relative) this.offset = begin;
- return this;
- };
- /**
- * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
- * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.flip = function() {
- this.limit = this.offset;
- this.offset = 0;
- return this;
- };
- /**
- * Marks an offset on this ByteBuffer to be used later.
- * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
- * @returns {!ByteBuffer} this
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @see ByteBuffer#reset
- * @expose
- */
- ByteBufferPrototype.mark = function(offset) {
- offset = typeof offset === 'undefined' ? this.offset : offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- this.markedOffset = offset;
- return this;
- };
- /**
- * Sets the byte order.
- * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.order = function(littleEndian) {
- if (!this.noAssert) {
- if (typeof littleEndian !== 'boolean')
- throw TypeError("Illegal littleEndian: Not a boolean");
- }
- this.littleEndian = !!littleEndian;
- return this;
- };
- /**
- * Switches (to) little endian byte order.
- * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.LE = function(littleEndian) {
- this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
- return this;
- };
- /**
- * Switches (to) big endian byte order.
- * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.BE = function(bigEndian) {
- this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
- return this;
- };
- /**
- * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
- * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
- * will be resized and its contents moved accordingly.
- * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
- * modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
- * prepended if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
- * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
- */
- ByteBufferPrototype.prepend = function(source, encoding, offset) {
- if (typeof encoding === 'number' || typeof encoding !== 'string') {
- offset = encoding;
- encoding = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (!(source instanceof ByteBuffer))
- source = ByteBuffer.wrap(source, encoding);
- var len = source.limit - source.offset;
- if (len <= 0) return this; // Nothing to prepend
- var diff = len - offset;
- if (diff > 0) { // Not enough space before offset, so resize + move
- var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
- var view = new Uint8Array(buffer);
- view.set(this.view.subarray(offset, this.buffer.byteLength), len);
- this.buffer = buffer;
- this.view = view;
- this.offset += diff;
- if (this.markedOffset >= 0) this.markedOffset += diff;
- this.limit += diff;
- offset += diff;
- } else {
- var arrayView = new Uint8Array(this.buffer);
- }
- this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
- source.offset = source.limit;
- if (relative)
- this.offset -= len;
- return this;
- };
- /**
- * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
- * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
- * will be resized and its contents moved accordingly.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
- * prepended if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @see ByteBuffer#prepend
- */
- ByteBufferPrototype.prependTo = function(target, offset) {
- target.prepend(this, offset);
- return this;
- };
- /**
- * Prints debug information about this ByteBuffer's contents.
- * @param {function(string)=} out Output function to call, defaults to console.log
- * @expose
- */
- ByteBufferPrototype.printDebug = function(out) {
- if (typeof out !== 'function') out = console.log.bind(console);
- out(
- this.toString()+"\n"+
- "-------------------------------------------------------------------\n"+
- this.toDebug(/* columns */ true)
- );
- };
- /**
- * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}, so this returns `limit - offset`.
- * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
- * @expose
- */
- ByteBufferPrototype.remaining = function() {
- return this.limit - this.offset;
- };
- /**
- * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
- * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
- * marked, sets `offset = 0`.
- * @returns {!ByteBuffer} this
- * @see ByteBuffer#mark
- * @expose
- */
- ByteBufferPrototype.reset = function() {
- if (this.markedOffset >= 0) {
- this.offset = this.markedOffset;
- this.markedOffset = -1;
- } else {
- this.offset = 0;
- }
- return this;
- };
- /**
- * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
- * large or larger.
- * @param {number} capacity Capacity required
- * @returns {!ByteBuffer} this
- * @throws {TypeError} If `capacity` is not a number
- * @throws {RangeError} If `capacity < 0`
- * @expose
- */
- ByteBufferPrototype.resize = function(capacity) {
- if (!this.noAssert) {
- if (typeof capacity !== 'number' || capacity % 1 !== 0)
- throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
- capacity |= 0;
- if (capacity < 0)
- throw RangeError("Illegal capacity: 0 <= "+capacity);
- }
- if (this.buffer.byteLength < capacity) {
- var buffer = new ArrayBuffer(capacity);
- var view = new Uint8Array(buffer);
- view.set(this.view);
- this.buffer = buffer;
- this.view = view;
- }
- return this;
- };
- /**
- * Reverses this ByteBuffer's contents.
- * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.reverse = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === end)
- return this; // Nothing to reverse
- Array.prototype.reverse.call(this.view.subarray(begin, end));
- return this;
- };
- /**
- * Skips the next `length` bytes. This will just advance
- * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.skip = function(length) {
- if (!this.noAssert) {
- if (typeof length !== 'number' || length % 1 !== 0)
- throw TypeError("Illegal length: "+length+" (not an integer)");
- length |= 0;
- }
- var offset = this.offset + length;
- if (!this.noAssert) {
- if (offset < 0 || offset > this.buffer.byteLength)
- throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
- }
- this.offset = offset;
- return this;
- };
- /**
- * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
- * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
- * @expose
- */
- ByteBufferPrototype.slice = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var bb = this.clone();
- bb.offset = begin;
- bb.limit = end;
- return bb;
- };
- /**
- * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
- * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
- * possible. Defaults to `false`
- * @returns {!ArrayBuffer} Contents as an ArrayBuffer
- * @expose
- */
- ByteBufferPrototype.toBuffer = function(forceCopy) {
- var offset = this.offset,
- limit = this.limit;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: Not an integer");
- offset >>>= 0;
- if (typeof limit !== 'number' || limit % 1 !== 0)
- throw TypeError("Illegal limit: Not an integer");
- limit >>>= 0;
- if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
- }
- // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
- // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
- if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
- return this.buffer;
- if (offset === limit)
- return EMPTY_BUFFER;
- var buffer = new ArrayBuffer(limit - offset);
- new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
- return buffer;
- };
- /**
- * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
- * @function
- * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
- * Defaults to `false`
- * @returns {!ArrayBuffer} Contents as an ArrayBuffer
- * @expose
- */
- ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
- /**
- * Converts the ByteBuffer's contents to a string.
- * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
- * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
- * highlighted offsets.
- * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {string} String representation
- * @throws {Error} If `encoding` is invalid
- * @expose
- */
- ByteBufferPrototype.toString = function(encoding, begin, end) {
- if (typeof encoding === 'undefined')
- return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
- if (typeof encoding === 'number')
- encoding = "utf8",
- begin = encoding,
- end = begin;
- switch (encoding) {
- case "utf8":
- return this.toUTF8(begin, end);
- case "base64":
- return this.toBase64(begin, end);
- case "hex":
- return this.toHex(begin, end);
- case "binary":
- return this.toBinary(begin, end);
- case "debug":
- return this.toDebug();
- case "columns":
- return this.toColumns();
- default:
- throw Error("Unsupported encoding: "+encoding);
- }
- };
- // lxiv-embeddable
- /**
- * lxiv-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/lxiv for details
- */
- var lxiv = function() {
- "use strict";
- /**
- * lxiv namespace.
- * @type {!Object.<string,*>}
- * @exports lxiv
- */
- var lxiv = {};
- /**
- * Character codes for output.
- * @type {!Array.<number>}
- * @inner
- */
- var aout = [
- 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
- 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
- 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
- 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
- ];
- /**
- * Character codes for input.
- * @type {!Array.<number>}
- * @inner
- */
- var ain = [];
- for (var i=0, k=aout.length; i<k; ++i)
- ain[aout[i]] = i;
- /**
- * Encodes bytes to base64 char codes.
- * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if
- * there are no more bytes left.
- * @param {!function(number)} dst Characters destination as a function successively called with each encoded char
- * code.
- */
- lxiv.encode = function(src, dst) {
- var b, t;
- while ((b = src()) !== null) {
- dst(aout[(b>>2)&0x3f]);
- t = (b&0x3)<<4;
- if ((b = src()) !== null) {
- t |= (b>>4)&0xf;
- dst(aout[(t|((b>>4)&0xf))&0x3f]);
- t = (b&0xf)<<2;
- if ((b = src()) !== null)
- dst(aout[(t|((b>>6)&0x3))&0x3f]),
- dst(aout[b&0x3f]);
- else
- dst(aout[t&0x3f]),
- dst(61);
- } else
- dst(aout[t&0x3f]),
- dst(61),
- dst(61);
- }
- };
- /**
- * Decodes base64 char codes to bytes.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
- * @throws {Error} If a character code is invalid
- */
- lxiv.decode = function(src, dst) {
- var c, t1, t2;
- function fail(c) {
- throw Error("Illegal character code: "+c);
- }
- while ((c = src()) !== null) {
- t1 = ain[c];
- if (typeof t1 === 'undefined') fail(c);
- if ((c = src()) !== null) {
- t2 = ain[c];
- if (typeof t2 === 'undefined') fail(c);
- dst((t1<<2)>>>0|(t2&0x30)>>4);
- if ((c = src()) !== null) {
- t1 = ain[c];
- if (typeof t1 === 'undefined')
- if (c === 61) break; else fail(c);
- dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
- if ((c = src()) !== null) {
- t2 = ain[c];
- if (typeof t2 === 'undefined')
- if (c === 61) break; else fail(c);
- dst(((t1&0x3)<<6)>>>0|t2);
- }
- }
- }
- }
- };
- /**
- * Tests if a string is valid base64.
- * @param {string} str String to test
- * @returns {boolean} `true` if valid, otherwise `false`
- */
- lxiv.test = function(str) {
- return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
- };
- return lxiv;
- }();
- // encodings/base64
- /**
- * Encodes this ByteBuffer's contents to a base64 encoded string.
- * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
- * @returns {string} Base64 encoded string
- * @throws {RangeError} If `begin` or `end` is out of bounds
- * @expose
- */
- ByteBufferPrototype.toBase64 = function(begin, end) {
- if (typeof begin === 'undefined')
- begin = this.offset;
- if (typeof end === 'undefined')
- end = this.limit;
- begin = begin | 0; end = end | 0;
- if (begin < 0 || end > this.capacity || begin > end)
- throw RangeError("begin, end");
- var sd; lxiv.encode(function() {
- return begin < end ? this.view[begin++] : null;
- }.bind(this), sd = stringDestination());
- return sd();
- };
- /**
- * Decodes a base64 encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromBase64 = function(str, littleEndian) {
- if (typeof str !== 'string')
- throw TypeError("str");
- var bb = new ByteBuffer(str.length/4*3, littleEndian),
- i = 0;
- lxiv.decode(stringSource(str), function(b) {
- bb.view[i++] = b;
- });
- bb.limit = i;
- return bb;
- };
- /**
- * Encodes a binary string to base64 like `window.btoa` does.
- * @param {string} str Binary string
- * @returns {string} Base64 encoded string
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
- * @expose
- */
- ByteBuffer.btoa = function(str) {
- return ByteBuffer.fromBinary(str).toBase64();
- };
- /**
- * Decodes a base64 encoded string to binary like `window.atob` does.
- * @param {string} b64 Base64 encoded string
- * @returns {string} Binary string
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
- * @expose
- */
- ByteBuffer.atob = function(b64) {
- return ByteBuffer.fromBase64(b64).toBinary();
- };
- // encodings/binary
- /**
- * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
- * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
- * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
- * @returns {string} Binary encoded string
- * @throws {RangeError} If `offset > limit`
- * @expose
- */
- ByteBufferPrototype.toBinary = function(begin, end) {
- if (typeof begin === 'undefined')
- begin = this.offset;
- if (typeof end === 'undefined')
- end = this.limit;
- begin |= 0; end |= 0;
- if (begin < 0 || end > this.capacity() || begin > end)
- throw RangeError("begin, end");
- if (begin === end)
- return "";
- var chars = [],
- parts = [];
- while (begin < end) {
- chars.push(this.view[begin++]);
- if (chars.length >= 1024)
- parts.push(String.fromCharCode.apply(String, chars)),
- chars = [];
- }
- return parts.join('') + String.fromCharCode.apply(String, chars);
- };
- /**
- * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromBinary = function(str, littleEndian) {
- if (typeof str !== 'string')
- throw TypeError("str");
- var i = 0,
- k = str.length,
- charCode,
- bb = new ByteBuffer(k, littleEndian);
- while (i<k) {
- charCode = str.charCodeAt(i);
- if (charCode > 0xff)
- throw RangeError("illegal char code: "+charCode);
- bb.view[i++] = charCode;
- }
- bb.limit = k;
- return bb;
- };
- // encodings/debug
- /**
- * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
- * * `<` : offset,
- * * `'` : markedOffset,
- * * `>` : limit,
- * * `|` : offset and limit,
- * * `[` : offset and markedOffset,
- * * `]` : markedOffset and limit,
- * * `!` : offset, markedOffset and limit
- * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
- * @returns {string|!Array.<string>} Debug string or array of lines if `asArray = true`
- * @expose
- * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
- * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
- * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
- * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
- */
- ByteBufferPrototype.toDebug = function(columns) {
- var i = -1,
- k = this.buffer.byteLength,
- b,
- hex = "",
- asc = "",
- out = "";
- while (i<k) {
- if (i !== -1) {
- b = this.view[i];
- if (b < 0x10) hex += "0"+b.toString(16).toUpperCase();
- else hex += b.toString(16).toUpperCase();
- if (columns)
- asc += b > 32 && b < 127 ? String.fromCharCode(b) : '.';
- }
- ++i;
- if (columns) {
- if (i > 0 && i % 16 === 0 && i !== k) {
- while (hex.length < 3*16+3) hex += " ";
- out += hex+asc+"\n";
- hex = asc = "";
- }
- }
- if (i === this.offset && i === this.limit)
- hex += i === this.markedOffset ? "!" : "|";
- else if (i === this.offset)
- hex += i === this.markedOffset ? "[" : "<";
- else if (i === this.limit)
- hex += i === this.markedOffset ? "]" : ">";
- else
- hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
- }
- if (columns && hex !== " ") {
- while (hex.length < 3*16+3)
- hex += " ";
- out += hex + asc + "\n";
- }
- return columns ? out : hex;
- };
- /**
- * Decodes a hex encoded string with marked offsets to a ByteBuffer.
- * @param {string} str Debug string to decode (not be generated with `columns = true`)
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- * @see ByteBuffer#toDebug
- */
- ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
- var k = str.length,
- bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
- var i = 0, j = 0, ch, b,
- rs = false, // Require symbol next
- ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
- fail = false;
- while (i<k) {
- switch (ch = str.charAt(i++)) {
- case '!':
- if (!noAssert) {
- if (ho || hm || hl) {
- fail = true;
- break;
- }
- ho = hm = hl = true;
- }
- bb.offset = bb.markedOffset = bb.limit = j;
- rs = false;
- break;
- case '|':
- if (!noAssert) {
- if (ho || hl) {
- fail = true;
- break;
- }
- ho = hl = true;
- }
- bb.offset = bb.limit = j;
- rs = false;
- break;
- case '[':
- if (!noAssert) {
- if (ho || hm) {
- fail = true;
- break;
- }
- ho = hm = true;
- }
- bb.offset = bb.markedOffset = j;
- rs = false;
- break;
- case '<':
- if (!noAssert) {
- if (ho) {
- fail = true;
- break;
- }
- ho = true;
- }
- bb.offset = j;
- rs = false;
- break;
- case ']':
- if (!noAssert) {
- if (hl || hm) {
- fail = true;
- break;
- }
- hl = hm = true;
- }
- bb.limit = bb.markedOffset = j;
- rs = false;
- break;
- case '>':
- if (!noAssert) {
- if (hl) {
- fail = true;
- break;
- }
- hl = true;
- }
- bb.limit = j;
- rs = false;
- break;
- case "'":
- if (!noAssert) {
- if (hm) {
- fail = true;
- break;
- }
- hm = true;
- }
- bb.markedOffset = j;
- rs = false;
- break;
- case ' ':
- rs = false;
- break;
- default:
- if (!noAssert) {
- if (rs) {
- fail = true;
- break;
- }
- }
- b = parseInt(ch+str.charAt(i++), 16);
- if (!noAssert) {
- if (isNaN(b) || b < 0 || b > 255)
- throw TypeError("Illegal str: Not a debug encoded string");
- }
- bb.view[j++] = b;
- rs = true;
- }
- if (fail)
- throw TypeError("Illegal str: Invalid symbol at "+i);
- }
- if (!noAssert) {
- if (!ho || !hl)
- throw TypeError("Illegal str: Missing offset or limit");
- if (j<bb.buffer.byteLength)
- throw TypeError("Illegal str: Not a debug encoded string (is it hex?) "+j+" < "+k);
- }
- return bb;
- };
- // encodings/hex
- /**
- * Encodes this ByteBuffer's contents to a hex encoded string.
- * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
- * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
- * @returns {string} Hex encoded string
- * @expose
- */
- ByteBufferPrototype.toHex = function(begin, end) {
- begin = typeof begin === 'undefined' ? this.offset : begin;
- end = typeof end === 'undefined' ? this.limit : end;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var out = new Array(end - begin),
- b;
- while (begin < end) {
- b = this.view[begin++];
- if (b < 0x10)
- out.push("0", b.toString(16));
- else out.push(b.toString(16));
- }
- return out.join('');
- };
- /**
- * Decodes a hex encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
- if (!noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (str.length % 2 !== 0)
- throw TypeError("Illegal str: Length not a multiple of 2");
- }
- var k = str.length,
- bb = new ByteBuffer((k / 2) | 0, littleEndian),
- b;
- for (var i=0, j=0; i<k; i+=2) {
- b = parseInt(str.substring(i, i+2), 16);
- if (!noAssert)
- if (!isFinite(b) || b < 0 || b > 255)
- throw TypeError("Illegal str: Contains non-hex characters");
- bb.view[j++] = b;
- }
- bb.limit = j;
- return bb;
- };
- // utfx-embeddable
- /**
- * utfx-embeddable (c) 2014 Daniel Wirtz <dcode@dcode.io>
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/utfx for details
- */
- var utfx = function() {
- "use strict";
- /**
- * utfx namespace.
- * @inner
- * @type {!Object.<string,*>}
- */
- var utfx = {};
- /**
- * Maximum valid code point.
- * @type {number}
- * @const
- */
- utfx.MAX_CODEPOINT = 0x10FFFF;
- /**
- * Encodes UTF8 code points to UTF8 bytes.
- * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
- * respectively `null` if there are no more code points left or a single numeric code point.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
- */
- utfx.encodeUTF8 = function(src, dst) {
- var cp = null;
- if (typeof src === 'number')
- cp = src,
- src = function() { return null; };
- while (cp !== null || (cp = src()) !== null) {
- if (cp < 0x80)
- dst(cp&0x7F);
- else if (cp < 0x800)
- dst(((cp>>6)&0x1F)|0xC0),
- dst((cp&0x3F)|0x80);
- else if (cp < 0x10000)
- dst(((cp>>12)&0x0F)|0xE0),
- dst(((cp>>6)&0x3F)|0x80),
- dst((cp&0x3F)|0x80);
- else
- dst(((cp>>18)&0x07)|0xF0),
- dst(((cp>>12)&0x3F)|0x80),
- dst(((cp>>6)&0x3F)|0x80),
- dst((cp&0x3F)|0x80);
- cp = null;
- }
- };
- /**
- * Decodes UTF8 bytes to UTF8 code points.
- * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
- * are no more bytes left.
- * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
- * @throws {RangeError} If a starting byte is invalid in UTF8
- * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
- * remaining bytes.
- */
- utfx.decodeUTF8 = function(src, dst) {
- var a, b, c, d, fail = function(b) {
- b = b.slice(0, b.indexOf(null));
- var err = Error(b.toString());
- err.name = "TruncatedError";
- err['bytes'] = b;
- throw err;
- };
- while ((a = src()) !== null) {
- if ((a&0x80) === 0)
- dst(a);
- else if ((a&0xE0) === 0xC0)
- ((b = src()) === null) && fail([a, b]),
- dst(((a&0x1F)<<6) | (b&0x3F));
- else if ((a&0xF0) === 0xE0)
- ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
- dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
- else if ((a&0xF8) === 0xF0)
- ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
- dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
- else throw RangeError("Illegal starting byte: "+a);
- }
- };
- /**
- * Converts UTF16 characters to UTF8 code points.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @param {!function(number)} dst Code points destination as a function successively called with each converted code
- * point.
- */
- utfx.UTF16toUTF8 = function(src, dst) {
- var c1, c2 = null;
- while (true) {
- if ((c1 = c2 !== null ? c2 : src()) === null)
- break;
- if (c1 >= 0xD800 && c1 <= 0xDFFF) {
- if ((c2 = src()) !== null) {
- if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
- dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
- c2 = null; continue;
- }
- }
- }
- dst(c1);
- }
- if (c2 !== null) dst(c2);
- };
- /**
- * Converts UTF8 code points to UTF16 characters.
- * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
- * respectively `null` if there are no more code points left or a single numeric code point.
- * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
- * @throws {RangeError} If a code point is out of range
- */
- utfx.UTF8toUTF16 = function(src, dst) {
- var cp = null;
- if (typeof src === 'number')
- cp = src, src = function() { return null; };
- while (cp !== null || (cp = src()) !== null) {
- if (cp <= 0xFFFF)
- dst(cp);
- else
- cp -= 0x10000,
- dst((cp>>10)+0xD800),
- dst((cp%0x400)+0xDC00);
- cp = null;
- }
- };
- /**
- * Converts and encodes UTF16 characters to UTF8 bytes.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
- * if there are no more characters left.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
- */
- utfx.encodeUTF16toUTF8 = function(src, dst) {
- utfx.UTF16toUTF8(src, function(cp) {
- utfx.encodeUTF8(cp, dst);
- });
- };
- /**
- * Decodes and converts UTF8 bytes to UTF16 characters.
- * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
- * are no more bytes left.
- * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
- * @throws {RangeError} If a starting byte is invalid in UTF8
- * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
- */
- utfx.decodeUTF8toUTF16 = function(src, dst) {
- utfx.decodeUTF8(src, function(cp) {
- utfx.UTF8toUTF16(cp, dst);
- });
- };
- /**
- * Calculates the byte length of an UTF8 code point.
- * @param {number} cp UTF8 code point
- * @returns {number} Byte length
- */
- utfx.calculateCodePoint = function(cp) {
- return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- };
- /**
- * Calculates the number of UTF8 bytes required to store UTF8 code points.
- * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
- * `null` if there are no more code points left.
- * @returns {number} The number of UTF8 bytes required
- */
- utfx.calculateUTF8 = function(src) {
- var cp, l=0;
- while ((cp = src()) !== null)
- l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- return l;
- };
- /**
- * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
- * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @returns {!Array.<number>} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
- */
- utfx.calculateUTF16asUTF8 = function(src) {
- var n=0, l=0;
- utfx.UTF16toUTF8(src, function(cp) {
- ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- });
- return [n,l];
- };
- return utfx;
- }();
- // encodings/utf8
- /**
- * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
- * string.
- * @returns {string} Hex encoded string
- * @throws {RangeError} If `offset > limit`
- * @expose
- */
- ByteBufferPrototype.toUTF8 = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var sd; try {
- utfx.decodeUTF8toUTF16(function() {
- return begin < end ? this.view[begin++] : null;
- }.bind(this), sd = stringDestination());
- } catch (e) {
- if (begin !== end)
- throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
- }
- return sd();
- };
- /**
- * Decodes an UTF8 encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
- if (!noAssert)
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
- i = 0;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- bb.view[i++] = b;
- });
- bb.limit = i;
- return bb;
- };
- return ByteBuffer;
- });
|