buffer.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. /*!
  2. * The buffer module from node.js, for the browser.
  3. *
  4. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  5. * @license MIT
  6. */
  7. var base64 = require('base64-js')
  8. var ieee754 = require('ieee754')
  9. exports.Buffer = Buffer
  10. exports.SlowBuffer = Buffer
  11. exports.INSPECT_MAX_BYTES = 50
  12. Buffer.poolSize = 8192
  13. /**
  14. * If `Buffer._useTypedArrays`:
  15. * === true Use Uint8Array implementation (fastest)
  16. * === false Use Object implementation (compatible down to IE6)
  17. */
  18. Buffer._useTypedArrays = false; (function () {
  19. // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
  20. // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
  21. // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
  22. // because we need to be able to add all the node Buffer API methods. This is an issue
  23. // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
  24. try {
  25. var buf = new ArrayBuffer(0)
  26. var arr = new Uint8Array(buf)
  27. arr.foo = function () { return 42 }
  28. return 42 === arr.foo() &&
  29. typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
  30. } catch (e) {
  31. return false
  32. }
  33. })()
  34. /**
  35. * Class: Buffer
  36. * =============
  37. *
  38. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  39. * with function properties for all the node `Buffer` API functions. We use
  40. * `Uint8Array` so that square bracket notation works as expected -- it returns
  41. * a single octet.
  42. *
  43. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  44. * prototype.
  45. */
  46. function Buffer (subject, encoding, noZero) {
  47. if (!(this instanceof Buffer))
  48. return new Buffer(subject, encoding, noZero)
  49. var type = typeof subject
  50. // Workaround: node's base64 implementation allows for non-padded strings
  51. // while base64-js does not.
  52. if (encoding === 'base64' && type === 'string') {
  53. subject = stringtrim(subject)
  54. while (subject.length % 4 !== 0) {
  55. subject = subject + '='
  56. }
  57. }
  58. // Find the length
  59. var length
  60. if (type === 'number')
  61. length = coerce(subject)
  62. else if (type === 'string')
  63. length = Buffer.byteLength(subject, encoding)
  64. else if (type === 'object')
  65. length = coerce(subject.length) // assume that object is array-like
  66. else
  67. throw new Error('First argument needs to be a number, array or string.')
  68. var buf
  69. if (Buffer._useTypedArrays) {
  70. // Preferred: Return an augmented `Uint8Array` instance for best performance
  71. buf = Buffer._augment(new Uint8Array(length))
  72. } else {
  73. // Fallback: Return THIS instance of Buffer (created by `new`)
  74. buf = this
  75. buf.length = length
  76. buf._isBuffer = true
  77. }
  78. var i
  79. if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
  80. // Speed optimization -- use set if we're copying from a typed array
  81. buf._set(subject)
  82. } else if (isArrayish(subject)) {
  83. // Treat array-ish objects as a byte array
  84. for (i = 0; i < length; i++) {
  85. if (Buffer.isBuffer(subject))
  86. buf[i] = subject.readUInt8(i)
  87. else
  88. buf[i] = subject[i]
  89. }
  90. } else if (type === 'string') {
  91. buf.write(subject, 0, encoding)
  92. } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
  93. for (i = 0; i < length; i++) {
  94. buf[i] = 0
  95. }
  96. }
  97. return buf
  98. }
  99. // STATIC METHODS
  100. // ==============
  101. Buffer.isEncoding = function (encoding) {
  102. switch (String(encoding).toLowerCase()) {
  103. case 'hex':
  104. case 'utf8':
  105. case 'utf-8':
  106. case 'ascii':
  107. case 'binary':
  108. case 'base64':
  109. case 'raw':
  110. case 'ucs2':
  111. case 'ucs-2':
  112. case 'utf16le':
  113. case 'utf-16le':
  114. return true
  115. default:
  116. return false
  117. }
  118. }
  119. Buffer.isBuffer = function (b) {
  120. return !!(b !== null && b !== undefined && b._isBuffer)
  121. }
  122. Buffer.byteLength = function (str, encoding) {
  123. var ret
  124. str = str + ''
  125. switch (encoding || 'utf8') {
  126. case 'hex':
  127. ret = str.length / 2
  128. break
  129. case 'utf8':
  130. case 'utf-8':
  131. ret = utf8ToBytes(str).length
  132. break
  133. case 'ascii':
  134. case 'binary':
  135. case 'raw':
  136. ret = str.length
  137. break
  138. case 'base64':
  139. ret = base64ToBytes(str).length
  140. break
  141. case 'ucs2':
  142. case 'ucs-2':
  143. case 'utf16le':
  144. case 'utf-16le':
  145. ret = str.length * 2
  146. break
  147. default:
  148. throw new Error('Unknown encoding')
  149. }
  150. return ret
  151. }
  152. Buffer.concat = function (list, totalLength) {
  153. assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
  154. 'list should be an Array.')
  155. if (list.length === 0) {
  156. return new Buffer(0)
  157. } else if (list.length === 1) {
  158. return list[0]
  159. }
  160. var i
  161. if (typeof totalLength !== 'number') {
  162. totalLength = 0
  163. for (i = 0; i < list.length; i++) {
  164. totalLength += list[i].length
  165. }
  166. }
  167. var buf = new Buffer(totalLength)
  168. var pos = 0
  169. for (i = 0; i < list.length; i++) {
  170. var item = list[i]
  171. item.copy(buf, pos)
  172. pos += item.length
  173. }
  174. return buf
  175. }
  176. // BUFFER INSTANCE METHODS
  177. // =======================
  178. function _hexWrite (buf, string, offset, length) {
  179. offset = Number(offset) || 0
  180. var remaining = buf.length - offset
  181. if (!length) {
  182. length = remaining
  183. } else {
  184. length = Number(length)
  185. if (length > remaining) {
  186. length = remaining
  187. }
  188. }
  189. // must be an even number of digits
  190. var strLen = string.length
  191. assert(strLen % 2 === 0, 'Invalid hex string')
  192. if (length > strLen / 2) {
  193. length = strLen / 2
  194. }
  195. for (var i = 0; i < length; i++) {
  196. var byte = parseInt(string.substr(i * 2, 2), 16)
  197. assert(!isNaN(byte), 'Invalid hex string')
  198. buf[offset + i] = byte
  199. }
  200. Buffer._charsWritten = i * 2
  201. return i
  202. }
  203. function _utf8Write (buf, string, offset, length) {
  204. var charsWritten = Buffer._charsWritten =
  205. blitBuffer(utf8ToBytes(string), buf, offset, length)
  206. return charsWritten
  207. }
  208. function _asciiWrite (buf, string, offset, length) {
  209. var charsWritten = Buffer._charsWritten =
  210. blitBuffer(asciiToBytes(string), buf, offset, length)
  211. return charsWritten
  212. }
  213. function _binaryWrite (buf, string, offset, length) {
  214. return _asciiWrite(buf, string, offset, length)
  215. }
  216. function _base64Write (buf, string, offset, length) {
  217. var charsWritten = Buffer._charsWritten =
  218. blitBuffer(base64ToBytes(string), buf, offset, length)
  219. return charsWritten
  220. }
  221. function _utf16leWrite (buf, string, offset, length) {
  222. var charsWritten = Buffer._charsWritten =
  223. blitBuffer(utf16leToBytes(string), buf, offset, length)
  224. return charsWritten
  225. }
  226. Buffer.prototype.write = function (string, offset, length, encoding) {
  227. // Support both (string, offset, length, encoding)
  228. // and the legacy (string, encoding, offset, length)
  229. if (isFinite(offset)) {
  230. if (!isFinite(length)) {
  231. encoding = length
  232. length = undefined
  233. }
  234. } else { // legacy
  235. var swap = encoding
  236. encoding = offset
  237. offset = length
  238. length = swap
  239. }
  240. offset = Number(offset) || 0
  241. var remaining = this.length - offset
  242. if (!length) {
  243. length = remaining
  244. } else {
  245. length = Number(length)
  246. if (length > remaining) {
  247. length = remaining
  248. }
  249. }
  250. encoding = String(encoding || 'utf8').toLowerCase()
  251. var ret
  252. switch (encoding) {
  253. case 'hex':
  254. ret = _hexWrite(this, string, offset, length)
  255. break
  256. case 'utf8':
  257. case 'utf-8':
  258. ret = _utf8Write(this, string, offset, length)
  259. break
  260. case 'ascii':
  261. ret = _asciiWrite(this, string, offset, length)
  262. break
  263. case 'binary':
  264. ret = _binaryWrite(this, string, offset, length)
  265. break
  266. case 'base64':
  267. ret = _base64Write(this, string, offset, length)
  268. break
  269. case 'ucs2':
  270. case 'ucs-2':
  271. case 'utf16le':
  272. case 'utf-16le':
  273. ret = _utf16leWrite(this, string, offset, length)
  274. break
  275. default:
  276. throw new Error('Unknown encoding')
  277. }
  278. return ret
  279. }
  280. Buffer.prototype.toString = function (encoding, start, end) {
  281. var self = this
  282. encoding = String(encoding || 'utf8').toLowerCase()
  283. start = Number(start) || 0
  284. end = (end !== undefined)
  285. ? Number(end)
  286. : end = self.length
  287. // Fastpath empty strings
  288. if (end === start)
  289. return ''
  290. var ret
  291. switch (encoding) {
  292. case 'hex':
  293. ret = _hexSlice(self, start, end)
  294. break
  295. case 'utf8':
  296. case 'utf-8':
  297. ret = _utf8Slice(self, start, end)
  298. break
  299. case 'ascii':
  300. ret = _asciiSlice(self, start, end)
  301. break
  302. case 'binary':
  303. ret = _binarySlice(self, start, end)
  304. break
  305. case 'base64':
  306. ret = _base64Slice(self, start, end)
  307. break
  308. case 'ucs2':
  309. case 'ucs-2':
  310. case 'utf16le':
  311. case 'utf-16le':
  312. ret = _utf16leSlice(self, start, end)
  313. break
  314. default:
  315. throw new Error('Unknown encoding')
  316. }
  317. return ret
  318. }
  319. Buffer.prototype.toJSON = function () {
  320. return {
  321. type: 'Buffer',
  322. data: Array.prototype.slice.call(this._arr || this, 0)
  323. }
  324. }
  325. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  326. Buffer.prototype.copy = function (target, target_start, start, end) {
  327. var source = this
  328. if (!start) start = 0
  329. if (!end && end !== 0) end = this.length
  330. if (!target_start) target_start = 0
  331. // Copy 0 bytes; we're done
  332. if (end === start) return
  333. if (target.length === 0 || source.length === 0) return
  334. // Fatal error conditions
  335. assert(end >= start, 'sourceEnd < sourceStart')
  336. assert(target_start >= 0 && target_start < target.length,
  337. 'targetStart out of bounds')
  338. assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
  339. assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
  340. // Are we oob?
  341. if (end > this.length)
  342. end = this.length
  343. if (target.length - target_start < end - start)
  344. end = target.length - target_start + start
  345. var len = end - start
  346. if (len < 100 || !Buffer._useTypedArrays) {
  347. for (var i = 0; i < len; i++)
  348. target[i + target_start] = this[i + start]
  349. } else {
  350. target._set(this.subarray(start, start + len), target_start)
  351. }
  352. }
  353. function _base64Slice (buf, start, end) {
  354. if (start === 0 && end === buf.length) {
  355. return base64.fromByteArray(buf)
  356. } else {
  357. return base64.fromByteArray(buf.slice(start, end))
  358. }
  359. }
  360. function _utf8Slice (buf, start, end) {
  361. var res = ''
  362. var tmp = ''
  363. end = Math.min(buf.length, end)
  364. for (var i = start; i < end; i++) {
  365. if (buf[i] <= 0x7F) {
  366. res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
  367. tmp = ''
  368. } else {
  369. tmp += '%' + buf[i].toString(16)
  370. }
  371. }
  372. return res + decodeUtf8Char(tmp)
  373. }
  374. function _asciiSlice (buf, start, end) {
  375. var ret = ''
  376. end = Math.min(buf.length, end)
  377. for (var i = start; i < end; i++)
  378. ret += String.fromCharCode(buf[i])
  379. return ret
  380. }
  381. function _binarySlice (buf, start, end) {
  382. return _asciiSlice(buf, start, end)
  383. }
  384. function _hexSlice (buf, start, end) {
  385. var len = buf.length
  386. if (!start || start < 0) start = 0
  387. if (!end || end < 0 || end > len) end = len
  388. var out = ''
  389. for (var i = start; i < end; i++) {
  390. out += toHex(buf[i])
  391. }
  392. return out
  393. }
  394. function _utf16leSlice (buf, start, end) {
  395. var bytes = buf.slice(start, end)
  396. var res = ''
  397. for (var i = 0; i < bytes.length; i += 2) {
  398. res += String.fromCharCode(bytes[i] + bytes[i+1] * 256)
  399. }
  400. return res
  401. }
  402. Buffer.prototype.slice = function (start, end) {
  403. var len = this.length
  404. start = clamp(start, len, 0)
  405. end = clamp(end, len, len)
  406. if (Buffer._useTypedArrays) {
  407. return Buffer._augment(this.subarray(start, end))
  408. } else {
  409. var sliceLen = end - start
  410. var newBuf = new Buffer(sliceLen, undefined, true)
  411. for (var i = 0; i < sliceLen; i++) {
  412. newBuf[i] = this[i + start]
  413. }
  414. return newBuf
  415. }
  416. }
  417. // `get` will be removed in Node 0.13+
  418. Buffer.prototype.get = function (offset) {
  419. console.log('.get() is deprecated. Access using array indexes instead.')
  420. return this.readUInt8(offset)
  421. }
  422. // `set` will be removed in Node 0.13+
  423. Buffer.prototype.set = function (v, offset) {
  424. console.log('.set() is deprecated. Access using array indexes instead.')
  425. return this.writeUInt8(v, offset)
  426. }
  427. Buffer.prototype.readUInt8 = function (offset, noAssert) {
  428. if (!noAssert) {
  429. assert(offset !== undefined && offset !== null, 'missing offset')
  430. assert(offset < this.length, 'Trying to read beyond buffer length')
  431. }
  432. if (offset >= this.length)
  433. return
  434. return this[offset]
  435. }
  436. function _readUInt16 (buf, offset, littleEndian, noAssert) {
  437. if (!noAssert) {
  438. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  439. assert(offset !== undefined && offset !== null, 'missing offset')
  440. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  441. }
  442. var len = buf.length
  443. if (offset >= len)
  444. return
  445. var val
  446. if (littleEndian) {
  447. val = buf[offset]
  448. if (offset + 1 < len)
  449. val |= buf[offset + 1] << 8
  450. } else {
  451. val = buf[offset] << 8
  452. if (offset + 1 < len)
  453. val |= buf[offset + 1]
  454. }
  455. return val
  456. }
  457. Buffer.prototype.readUInt16LE = function (offset, noAssert) {
  458. return _readUInt16(this, offset, true, noAssert)
  459. }
  460. Buffer.prototype.readUInt16BE = function (offset, noAssert) {
  461. return _readUInt16(this, offset, false, noAssert)
  462. }
  463. function _readUInt32 (buf, offset, littleEndian, noAssert) {
  464. if (!noAssert) {
  465. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  466. assert(offset !== undefined && offset !== null, 'missing offset')
  467. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  468. }
  469. var len = buf.length
  470. if (offset >= len)
  471. return
  472. var val
  473. if (littleEndian) {
  474. if (offset + 2 < len)
  475. val = buf[offset + 2] << 16
  476. if (offset + 1 < len)
  477. val |= buf[offset + 1] << 8
  478. val |= buf[offset]
  479. if (offset + 3 < len)
  480. val = val + (buf[offset + 3] << 24 >>> 0)
  481. } else {
  482. if (offset + 1 < len)
  483. val = buf[offset + 1] << 16
  484. if (offset + 2 < len)
  485. val |= buf[offset + 2] << 8
  486. if (offset + 3 < len)
  487. val |= buf[offset + 3]
  488. val = val + (buf[offset] << 24 >>> 0)
  489. }
  490. return val
  491. }
  492. Buffer.prototype.readUInt32LE = function (offset, noAssert) {
  493. return _readUInt32(this, offset, true, noAssert)
  494. }
  495. Buffer.prototype.readUInt32BE = function (offset, noAssert) {
  496. return _readUInt32(this, offset, false, noAssert)
  497. }
  498. Buffer.prototype.readInt8 = function (offset, noAssert) {
  499. if (!noAssert) {
  500. assert(offset !== undefined && offset !== null,
  501. 'missing offset')
  502. assert(offset < this.length, 'Trying to read beyond buffer length')
  503. }
  504. if (offset >= this.length)
  505. return
  506. var neg = this[offset] & 0x80
  507. if (neg)
  508. return (0xff - this[offset] + 1) * -1
  509. else
  510. return this[offset]
  511. }
  512. function _readInt16 (buf, offset, littleEndian, noAssert) {
  513. if (!noAssert) {
  514. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  515. assert(offset !== undefined && offset !== null, 'missing offset')
  516. assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
  517. }
  518. var len = buf.length
  519. if (offset >= len)
  520. return
  521. var val = _readUInt16(buf, offset, littleEndian, true)
  522. var neg = val & 0x8000
  523. if (neg)
  524. return (0xffff - val + 1) * -1
  525. else
  526. return val
  527. }
  528. Buffer.prototype.readInt16LE = function (offset, noAssert) {
  529. return _readInt16(this, offset, true, noAssert)
  530. }
  531. Buffer.prototype.readInt16BE = function (offset, noAssert) {
  532. return _readInt16(this, offset, false, noAssert)
  533. }
  534. function _readInt32 (buf, offset, littleEndian, noAssert) {
  535. if (!noAssert) {
  536. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  537. assert(offset !== undefined && offset !== null, 'missing offset')
  538. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  539. }
  540. var len = buf.length
  541. if (offset >= len)
  542. return
  543. var val = _readUInt32(buf, offset, littleEndian, true)
  544. var neg = val & 0x80000000
  545. if (neg)
  546. return (0xffffffff - val + 1) * -1
  547. else
  548. return val
  549. }
  550. Buffer.prototype.readInt32LE = function (offset, noAssert) {
  551. return _readInt32(this, offset, true, noAssert)
  552. }
  553. Buffer.prototype.readInt32BE = function (offset, noAssert) {
  554. return _readInt32(this, offset, false, noAssert)
  555. }
  556. function _readFloat (buf, offset, littleEndian, noAssert) {
  557. if (!noAssert) {
  558. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  559. assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
  560. }
  561. return ieee754.read(buf, offset, littleEndian, 23, 4)
  562. }
  563. Buffer.prototype.readFloatLE = function (offset, noAssert) {
  564. return _readFloat(this, offset, true, noAssert)
  565. }
  566. Buffer.prototype.readFloatBE = function (offset, noAssert) {
  567. return _readFloat(this, offset, false, noAssert)
  568. }
  569. function _readDouble (buf, offset, littleEndian, noAssert) {
  570. if (!noAssert) {
  571. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  572. assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
  573. }
  574. return ieee754.read(buf, offset, littleEndian, 52, 8)
  575. }
  576. Buffer.prototype.readDoubleLE = function (offset, noAssert) {
  577. return _readDouble(this, offset, true, noAssert)
  578. }
  579. Buffer.prototype.readDoubleBE = function (offset, noAssert) {
  580. return _readDouble(this, offset, false, noAssert)
  581. }
  582. Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
  583. if (!noAssert) {
  584. assert(value !== undefined && value !== null, 'missing value')
  585. assert(offset !== undefined && offset !== null, 'missing offset')
  586. assert(offset < this.length, 'trying to write beyond buffer length')
  587. verifuint(value, 0xff)
  588. }
  589. if (offset >= this.length) return
  590. this[offset] = value
  591. }
  592. function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
  593. if (!noAssert) {
  594. assert(value !== undefined && value !== null, 'missing value')
  595. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  596. assert(offset !== undefined && offset !== null, 'missing offset')
  597. assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
  598. verifuint(value, 0xffff)
  599. }
  600. var len = buf.length
  601. if (offset >= len)
  602. return
  603. for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
  604. buf[offset + i] =
  605. (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  606. (littleEndian ? i : 1 - i) * 8
  607. }
  608. }
  609. Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
  610. _writeUInt16(this, value, offset, true, noAssert)
  611. }
  612. Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
  613. _writeUInt16(this, value, offset, false, noAssert)
  614. }
  615. function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
  616. if (!noAssert) {
  617. assert(value !== undefined && value !== null, 'missing value')
  618. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  619. assert(offset !== undefined && offset !== null, 'missing offset')
  620. assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
  621. verifuint(value, 0xffffffff)
  622. }
  623. var len = buf.length
  624. if (offset >= len)
  625. return
  626. for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
  627. buf[offset + i] =
  628. (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  629. }
  630. }
  631. Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
  632. _writeUInt32(this, value, offset, true, noAssert)
  633. }
  634. Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
  635. _writeUInt32(this, value, offset, false, noAssert)
  636. }
  637. Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
  638. if (!noAssert) {
  639. assert(value !== undefined && value !== null, 'missing value')
  640. assert(offset !== undefined && offset !== null, 'missing offset')
  641. assert(offset < this.length, 'Trying to write beyond buffer length')
  642. verifsint(value, 0x7f, -0x80)
  643. }
  644. if (offset >= this.length)
  645. return
  646. if (value >= 0)
  647. this.writeUInt8(value, offset, noAssert)
  648. else
  649. this.writeUInt8(0xff + value + 1, offset, noAssert)
  650. }
  651. function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
  652. if (!noAssert) {
  653. assert(value !== undefined && value !== null, 'missing value')
  654. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  655. assert(offset !== undefined && offset !== null, 'missing offset')
  656. assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
  657. verifsint(value, 0x7fff, -0x8000)
  658. }
  659. var len = buf.length
  660. if (offset >= len)
  661. return
  662. if (value >= 0)
  663. _writeUInt16(buf, value, offset, littleEndian, noAssert)
  664. else
  665. _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
  666. }
  667. Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
  668. _writeInt16(this, value, offset, true, noAssert)
  669. }
  670. Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
  671. _writeInt16(this, value, offset, false, noAssert)
  672. }
  673. function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
  674. if (!noAssert) {
  675. assert(value !== undefined && value !== null, 'missing value')
  676. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  677. assert(offset !== undefined && offset !== null, 'missing offset')
  678. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  679. verifsint(value, 0x7fffffff, -0x80000000)
  680. }
  681. var len = buf.length
  682. if (offset >= len)
  683. return
  684. if (value >= 0)
  685. _writeUInt32(buf, value, offset, littleEndian, noAssert)
  686. else
  687. _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
  688. }
  689. Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
  690. _writeInt32(this, value, offset, true, noAssert)
  691. }
  692. Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
  693. _writeInt32(this, value, offset, false, noAssert)
  694. }
  695. function _writeFloat (buf, value, offset, littleEndian, noAssert) {
  696. if (!noAssert) {
  697. assert(value !== undefined && value !== null, 'missing value')
  698. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  699. assert(offset !== undefined && offset !== null, 'missing offset')
  700. assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
  701. verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
  702. }
  703. var len = buf.length
  704. if (offset >= len)
  705. return
  706. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  707. }
  708. Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
  709. _writeFloat(this, value, offset, true, noAssert)
  710. }
  711. Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
  712. _writeFloat(this, value, offset, false, noAssert)
  713. }
  714. function _writeDouble (buf, value, offset, littleEndian, noAssert) {
  715. if (!noAssert) {
  716. assert(value !== undefined && value !== null, 'missing value')
  717. assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
  718. assert(offset !== undefined && offset !== null, 'missing offset')
  719. assert(offset + 7 < buf.length,
  720. 'Trying to write beyond buffer length')
  721. verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
  722. }
  723. var len = buf.length
  724. if (offset >= len)
  725. return
  726. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  727. }
  728. Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
  729. _writeDouble(this, value, offset, true, noAssert)
  730. }
  731. Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
  732. _writeDouble(this, value, offset, false, noAssert)
  733. }
  734. // fill(value, start=0, end=buffer.length)
  735. Buffer.prototype.fill = function (value, start, end) {
  736. if (!value) value = 0
  737. if (!start) start = 0
  738. if (!end) end = this.length
  739. if (typeof value === 'string') {
  740. value = value.charCodeAt(0)
  741. }
  742. assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
  743. assert(end >= start, 'end < start')
  744. // Fill 0 bytes; we're done
  745. if (end === start) return
  746. if (this.length === 0) return
  747. assert(start >= 0 && start < this.length, 'start out of bounds')
  748. assert(end >= 0 && end <= this.length, 'end out of bounds')
  749. for (var i = start; i < end; i++) {
  750. this[i] = value
  751. }
  752. }
  753. Buffer.prototype.inspect = function () {
  754. var out = []
  755. var len = this.length
  756. for (var i = 0; i < len; i++) {
  757. out[i] = toHex(this[i])
  758. if (i === exports.INSPECT_MAX_BYTES) {
  759. out[i + 1] = '...'
  760. break
  761. }
  762. }
  763. return '<Buffer ' + out.join(' ') + '>'
  764. }
  765. /**
  766. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  767. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  768. */
  769. Buffer.prototype.toArrayBuffer = function () {
  770. if (typeof Uint8Array !== 'undefined') {
  771. if (Buffer._useTypedArrays) {
  772. return (new Buffer(this)).buffer
  773. } else {
  774. var buf = new Uint8Array(this.length)
  775. for (var i = 0, len = buf.length; i < len; i += 1)
  776. buf[i] = this[i]
  777. return buf.buffer
  778. }
  779. } else {
  780. throw new Error('Buffer.toArrayBuffer not supported in this browser')
  781. }
  782. }
  783. require("./extend")(Buffer.prototype);
  784. // HELPER FUNCTIONS
  785. // ================
  786. function stringtrim (str) {
  787. if (str.trim) return str.trim()
  788. return str.replace(/^\s+|\s+$/g, '')
  789. }
  790. var BP = Buffer.prototype
  791. /**
  792. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  793. */
  794. Buffer._augment = function (arr) {
  795. arr._isBuffer = true
  796. // save reference to original Uint8Array get/set methods before overwriting
  797. arr._get = arr.get
  798. arr._set = arr.set
  799. // deprecated, will be removed in node 0.13+
  800. arr.get = BP.get
  801. arr.set = BP.set
  802. arr.write = BP.write
  803. arr.toString = BP.toString
  804. arr.toLocaleString = BP.toString
  805. arr.toJSON = BP.toJSON
  806. arr.copy = BP.copy
  807. arr.slice = BP.slice
  808. arr.readUInt8 = BP.readUInt8
  809. arr.readUInt16LE = BP.readUInt16LE
  810. arr.readUInt16BE = BP.readUInt16BE
  811. arr.readUInt32LE = BP.readUInt32LE
  812. arr.readUInt32BE = BP.readUInt32BE
  813. arr.readInt8 = BP.readInt8
  814. arr.readInt16LE = BP.readInt16LE
  815. arr.readInt16BE = BP.readInt16BE
  816. arr.readInt32LE = BP.readInt32LE
  817. arr.readInt32BE = BP.readInt32BE
  818. arr.readFloatLE = BP.readFloatLE
  819. arr.readFloatBE = BP.readFloatBE
  820. arr.readDoubleLE = BP.readDoubleLE
  821. arr.readDoubleBE = BP.readDoubleBE
  822. arr.writeUInt8 = BP.writeUInt8
  823. arr.writeUInt16LE = BP.writeUInt16LE
  824. arr.writeUInt16BE = BP.writeUInt16BE
  825. arr.writeUInt32LE = BP.writeUInt32LE
  826. arr.writeUInt32BE = BP.writeUInt32BE
  827. arr.writeInt8 = BP.writeInt8
  828. arr.writeInt16LE = BP.writeInt16LE
  829. arr.writeInt16BE = BP.writeInt16BE
  830. arr.writeInt32LE = BP.writeInt32LE
  831. arr.writeInt32BE = BP.writeInt32BE
  832. arr.writeFloatLE = BP.writeFloatLE
  833. arr.writeFloatBE = BP.writeFloatBE
  834. arr.writeDoubleLE = BP.writeDoubleLE
  835. arr.writeDoubleBE = BP.writeDoubleBE
  836. arr.fill = BP.fill
  837. arr.inspect = BP.inspect
  838. arr.toArrayBuffer = BP.toArrayBuffer
  839. return arr
  840. }
  841. // slice(start, end)
  842. function clamp (index, len, defaultValue) {
  843. if (typeof index !== 'number') return defaultValue
  844. index = ~~index; // Coerce to integer.
  845. if (index >= len) return len
  846. if (index >= 0) return index
  847. index += len
  848. if (index >= 0) return index
  849. return 0
  850. }
  851. function coerce (length) {
  852. // Coerce length to a number (possibly NaN), round up
  853. // in case it's fractional (e.g. 123.456) then do a
  854. // double negate to coerce a NaN to 0. Easy, right?
  855. length = ~~Math.ceil(+length)
  856. return length < 0 ? 0 : length
  857. }
  858. function isArray (subject) {
  859. return (Array.isArray || function (subject) {
  860. return Object.prototype.toString.call(subject) === '[object Array]'
  861. })(subject)
  862. }
  863. function isArrayish (subject) {
  864. return isArray(subject) || Buffer.isBuffer(subject) ||
  865. subject && typeof subject === 'object' &&
  866. typeof subject.length === 'number'
  867. }
  868. function toHex (n) {
  869. if (n < 16) return '0' + n.toString(16)
  870. return n.toString(16)
  871. }
  872. function utf8ToBytes (str) {
  873. var byteArray = []
  874. for (var i = 0; i < str.length; i++) {
  875. var b = str.charCodeAt(i)
  876. if (b <= 0x7F)
  877. byteArray.push(str.charCodeAt(i))
  878. else {
  879. var start = i
  880. if (b >= 0xD800 && b <= 0xDFFF) i++
  881. var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
  882. for (var j = 0; j < h.length; j++)
  883. byteArray.push(parseInt(h[j], 16))
  884. }
  885. }
  886. return byteArray
  887. }
  888. function asciiToBytes (str) {
  889. var byteArray = []
  890. for (var i = 0; i < str.length; i++) {
  891. // Node's code seems to be doing this and not & 0x7F..
  892. byteArray.push(str.charCodeAt(i) & 0xFF)
  893. }
  894. return byteArray
  895. }
  896. function utf16leToBytes (str) {
  897. var c, hi, lo
  898. var byteArray = []
  899. for (var i = 0; i < str.length; i++) {
  900. c = str.charCodeAt(i)
  901. hi = c >> 8
  902. lo = c % 256
  903. byteArray.push(lo)
  904. byteArray.push(hi)
  905. }
  906. return byteArray
  907. }
  908. function base64ToBytes (str) {
  909. return base64.toByteArray(str)
  910. }
  911. function blitBuffer (src, dst, offset, length) {
  912. var pos
  913. for (var i = 0; i < length; i++) {
  914. if ((i + offset >= dst.length) || (i >= src.length))
  915. break
  916. dst[i + offset] = src[i]
  917. }
  918. return i
  919. }
  920. function decodeUtf8Char (str) {
  921. try {
  922. return decodeURIComponent(str)
  923. } catch (err) {
  924. return String.fromCharCode(0xFFFD) // UTF 8 invalid char
  925. }
  926. }
  927. /*
  928. * We have to make sure that the value is a valid integer. This means that it
  929. * is non-negative. It has no fractional component and that it does not
  930. * exceed the maximum allowed value.
  931. */
  932. function verifuint (value, max) {
  933. assert(typeof value === 'number', 'cannot write a non-number as a number')
  934. assert(value >= 0, 'specified a negative value for writing an unsigned value')
  935. assert(value <= max, 'value is larger than maximum value for type')
  936. assert(Math.floor(value) === value, 'value has a fractional component')
  937. }
  938. function verifsint (value, max, min) {
  939. assert(typeof value === 'number', 'cannot write a non-number as a number')
  940. assert(value <= max, 'value larger than maximum allowed value')
  941. assert(value >= min, 'value smaller than minimum allowed value')
  942. assert(Math.floor(value) === value, 'value has a fractional component')
  943. }
  944. function verifIEEE754 (value, max, min) {
  945. assert(typeof value === 'number', 'cannot write a non-number as a number')
  946. assert(value <= max, 'value larger than maximum allowed value')
  947. assert(value >= min, 'value smaller than minimum allowed value')
  948. }
  949. function assert (test, message) {
  950. if (!test) throw new Error(message || 'Failed assertion')
  951. }