UNPKG

dy3dmap

Version:

1,389 lines (1,246 loc) 1 MB
/*! * 基于MikesWei的CesiumVectorTile代码整理规范修改,并用webpack打包 * 版本信息:v2.0.0, hash值: d0acdda6c1d94d453884 * 编译日期:2022-04-30 17:22:32 * Github:https://github.com/muyao1987/CesiumVectorTile/ * */ ;(function webpackUniversalModuleDefinition(root, factory) { if (typeof exports === "object" && typeof module === "object") module.exports = factory(require("mars3d-cesium"), require("@turf/turf")) else if (typeof define === "function" && define.amd) define("CesiumVectorTile", ["mars3d-cesium", "@turf/turf"], factory) else if (typeof exports === "object") exports["CesiumVectorTile"] = factory(require("mars3d-cesium"), require("@turf/turf")) else root["CesiumVectorTile"] = factory(root["Cesium"], root["turf"]) })(window, function (__WEBPACK_EXTERNAL_MODULE__0__, __WEBPACK_EXTERNAL_MODULE__1__) { return /******/ (function (modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {} /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) { /******/ return installedModules[moduleId].exports /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = (installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }) /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__) /******/ /******/ // Flag the module as loaded /******/ module.l = true /******/ /******/ // Return the exports of the module /******/ return module.exports /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function (exports, name, getter) { /******/ if (!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }) /******/ } /******/ } /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function (exports) { /******/ if (typeof Symbol !== "undefined" && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }) /******/ } /******/ Object.defineProperty(exports, "__esModule", { value: true }) /******/ } /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function (value, mode) { /******/ if (mode & 1) value = __webpack_require__(value) /******/ if (mode & 8) return value /******/ if (mode & 4 && typeof value === "object" && value && value.__esModule) return value /******/ var ns = Object.create(null) /******/ __webpack_require__.r(ns) /******/ Object.defineProperty(ns, "default", { enumerable: true, value: value }) /******/ if (mode & 2 && typeof value != "string") for (var key in value) __webpack_require__.d( ns, key, function (key) { return value[key] }.bind(null, key) ) /******/ return ns /******/ } /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function (module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module["default"] } : /******/ function getModuleExports() { return module } /******/ __webpack_require__.d(getter, "a", getter) /******/ return getter /******/ } /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function (object, property) { return Object.prototype.hasOwnProperty.call(object, property) } /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "" /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__((__webpack_require__.s = 64)) /******/ })( /************************************************************************/ /******/ [ /* 0 */ /***/ function (module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__0__ /***/ }, /* 1 */ /***/ function (module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE__1__ /***/ }, /* 2 */ /***/ function (module, exports, __webpack_require__) { "use strict" var support = __webpack_require__(4) var compressions = __webpack_require__(10) var nodeBuffer = __webpack_require__(12) /** * Convert a string to a "binary string" : a string containing only char codes between 0 and 255. * @param {string} str the string to transform. * @return {String} the binary string. */ exports.string2binary = function (str) { var result = "" for (var i = 0; i < str.length; i++) { result += String.fromCharCode(str.charCodeAt(i) & 0xff) } return result } exports.arrayBuffer2Blob = function (buffer, mimeType) { exports.checkSupport("blob") mimeType = mimeType || "application/zip" try { // Blob constructor return new Blob([buffer], { type: mimeType }) } catch (e) { try { // deprecated, browser only, old way var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder var builder = new Builder() builder.append(buffer) return builder.getBlob(mimeType) } catch (e) { // well, fuck ?! throw new Error("Bug : can't construct the Blob.") } } } /** * The identity function. * @param {Object} input the input. * @return {Object} the same input. */ function identity(input) { return input } /** * Fill in an array with a string. * @param {String} str the string to use. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. */ function stringToArrayLike(str, array) { for (var i = 0; i < str.length; ++i) { array[i] = str.charCodeAt(i) & 0xff } return array } /** * Transform an array-like object to a string. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ function arrayLikeToString(array) { // Performances notes : // -------------------- // String.fromCharCode.apply(null, array) is the fastest, see // see http://jsperf.com/converting-a-uint8array-to-a-string/2 // but the stack is limited (and we can get huge arrays !). // // result += String.fromCharCode(array[i]); generate too many strings ! // // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 var chunk = 65536 var result = [], len = array.length, type = exports.getTypeOf(array), k = 0, canUseApply = true try { switch (type) { case "uint8array": String.fromCharCode.apply(null, new Uint8Array(0)) break case "nodebuffer": String.fromCharCode.apply(null, nodeBuffer(0)) break } } catch (e) { canUseApply = false } // no apply : slow and painful algorithm // default browser on android 4.* if (!canUseApply) { var resultStr = "" for (var i = 0; i < array.length; i++) { resultStr += String.fromCharCode(array[i]) } return resultStr } while (k < len && chunk > 1) { try { if (type === "array" || type === "nodebuffer") { result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))) } else { result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))) } k += chunk } catch (e) { chunk = Math.floor(chunk / 2) } } return result.join("") } exports.applyFromCharCode = arrayLikeToString /** * Copy the data from an array-like to an other array-like. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. */ function arrayLikeToArrayLike(arrayFrom, arrayTo) { for (var i = 0; i < arrayFrom.length; i++) { arrayTo[i] = arrayFrom[i] } return arrayTo } // a matrix containing functions to transform everything into everything. var transform = {} // string to ? transform["string"] = { string: identity, array: function (input) { return stringToArrayLike(input, new Array(input.length)) }, arraybuffer: function (input) { return transform["string"]["uint8array"](input).buffer }, uint8array: function (input) { return stringToArrayLike(input, new Uint8Array(input.length)) }, nodebuffer: function (input) { return stringToArrayLike(input, nodeBuffer(input.length)) } } // array to ? transform["array"] = { string: arrayLikeToString, array: identity, arraybuffer: function (input) { return new Uint8Array(input).buffer }, uint8array: function (input) { return new Uint8Array(input) }, nodebuffer: function (input) { return nodeBuffer(input) } } // arraybuffer to ? transform["arraybuffer"] = { string: function (input) { return arrayLikeToString(new Uint8Array(input)) }, array: function (input) { return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)) }, arraybuffer: identity, uint8array: function (input) { return new Uint8Array(input) }, nodebuffer: function (input) { return nodeBuffer(new Uint8Array(input)) } } // uint8array to ? transform["uint8array"] = { string: arrayLikeToString, array: function (input) { return arrayLikeToArrayLike(input, new Array(input.length)) }, arraybuffer: function (input) { return input.buffer }, uint8array: identity, nodebuffer: function (input) { return nodeBuffer(input) } } // nodebuffer to ? transform["nodebuffer"] = { string: arrayLikeToString, array: function (input) { return arrayLikeToArrayLike(input, new Array(input.length)) }, arraybuffer: function (input) { return transform["nodebuffer"]["uint8array"](input).buffer }, uint8array: function (input) { return arrayLikeToArrayLike(input, new Uint8Array(input.length)) }, nodebuffer: identity } /** * Transform an input into any type. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. * If no output type is specified, the unmodified input will be returned. * @param {String} outputType the output type. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. * @throws {Error} an Error if the browser doesn't support the requested output type. */ exports.transformTo = function (outputType, input) { if (!input) { // undefined, null, etc // an empty string won't harm. input = "" } if (!outputType) { return input } exports.checkSupport(outputType) var inputType = exports.getTypeOf(input) var result = transform[inputType][outputType](input) return result } /** * Return the type of the input. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. * @param {Object} input the input to identify. * @return {String} the (lowercase) type of the input. */ exports.getTypeOf = function (input) { if (typeof input === "string") { return "string" } if (Object.prototype.toString.call(input) === "[object Array]") { return "array" } if (support.nodebuffer && nodeBuffer.test(input)) { return "nodebuffer" } if (support.uint8array && input instanceof Uint8Array) { return "uint8array" } if (support.arraybuffer && input instanceof ArrayBuffer) { return "arraybuffer" } } /** * Throw an exception if the type is not supported. * @param {String} type the type to check. * @throws {Error} an Error if the browser doesn't support the requested type. */ exports.checkSupport = function (type) { var supported = support[type.toLowerCase()] if (!supported) { throw new Error(type + " is not supported by this browser") } } exports.MAX_VALUE_16BITS = 65535 exports.MAX_VALUE_32BITS = -1 // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 /** * Prettify a string read as binary. * @param {string} str the string to prettify. * @return {string} a pretty string. */ exports.pretty = function (str) { var res = "", code, i for (i = 0; i < (str || "").length; i++) { code = str.charCodeAt(i) res += "\\x" + (code < 16 ? "0" : "") + code.toString(16).toUpperCase() } return res } /** * Find a compression registered in JSZip. * @param {string} compressionMethod the method magic to find. * @return {Object|null} the JSZip compression object, null if none found. */ exports.findCompression = function (compressionMethod) { for (var method in compressions) { if (!compressions.hasOwnProperty(method)) { continue } if (compressions[method].magic === compressionMethod) { return compressions[method] } } return null } /** * Cross-window, cross-Node-context regular expression detection * @param {Object} object Anything * @return {Boolean} true if the object is a regular expression, * false otherwise */ exports.isRegExp = function (object) { return Object.prototype.toString.call(object) === "[object RegExp]" } /** * Merge the objects passed as parameters into a new one. * @private * @param {...Object} var_args All objects to merge. * @return {Object} a new object with the data of the others. */ exports.extend = function () { var result = {}, i, attr for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers for (attr in arguments[i]) { if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { result[attr] = arguments[i][attr] } } } return result } /***/ }, /* 3 */ /***/ function (module, exports, __webpack_require__) { "use strict" var TYPED_OK = typeof Uint8Array !== "undefined" && typeof Uint16Array !== "undefined" && typeof Int32Array !== "undefined" function _has(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) } exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1) while (sources.length) { var source = sources.shift() if (!source) { continue } if (typeof source !== "object") { throw new TypeError(source + "must be non-object") } for (var p in source) { if (_has(source, p)) { obj[p] = source[p] } } } return obj } // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf } if (buf.subarray) { return buf.subarray(0, size) } buf.length = size return buf } var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs) return } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i] } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result // calculate data length len = 0 for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length } // join chunks result = new Uint8Array(len) pos = 0 for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i] result.set(chunk, pos) pos += chunk.length } return result } } var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i] } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks) } } // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array exports.Buf16 = Uint16Array exports.Buf32 = Int32Array exports.assign(exports, fnTyped) } else { exports.Buf8 = Array exports.Buf16 = Array exports.Buf32 = Array exports.assign(exports, fnUntyped) } } exports.setTyped(TYPED_OK) /***/ }, /* 4 */ /***/ function (module, exports, __webpack_require__) { "use strict" /* WEBPACK VAR INJECTION */ ;(function (Buffer) { exports.base64 = true exports.array = true exports.string = true exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined" // contains true if JSZip can read/generate nodejs Buffer, false otherwise. // Browserify will provide a Buffer implementation for browsers, which is // an augmented Uint8Array (i.e., can be used as either Buffer or U8). exports.nodebuffer = typeof Buffer !== "undefined" // contains true if JSZip can read/generate Uint8Array, false otherwise. exports.uint8array = typeof Uint8Array !== "undefined" if (typeof ArrayBuffer === "undefined") { exports.blob = false } else { var buffer = new ArrayBuffer(0) try { exports.blob = new Blob([buffer], { type: "application/zip" }).size === 0 } catch (e) { try { var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder var builder = new Builder() builder.append(buffer) exports.blob = builder.getBlob("application/zip").size === 0 } catch (e) { exports.blob = false } } } /* WEBPACK VAR INJECTION */ }).call(this, __webpack_require__(5).Buffer) /***/ }, /* 5 */ /***/ function (module, exports, __webpack_require__) { "use strict" /* WEBPACK VAR INJECTION */ ;(function (global) { /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ var base64 = __webpack_require__(30) var ieee754 = __webpack_require__(31) var isArray = __webpack_require__(32) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport() { try { var arr = new Uint8Array(1) arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } return ( arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === "function" && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 ) // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength() { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer(that, length) { if (kMaxLength() < length) { throw new RangeError("Invalid typed array length") } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer(arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === "number") { if (typeof encodingOrOffset === "string") { throw new Error("If encoding is specified then the first argument must be a string") } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from(that, value, encodingOrOffset, length) { if (typeof value === "number") { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === "string") { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize(size) { if (typeof size !== "number") { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc(that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe(that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString(that, string, encoding) { if (typeof encoding !== "string" || encoding === "") { encoding = "utf8" } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike(that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer(that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError("'offset' is out of bounds") } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError("'length' is out of bounds") } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject(that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer) || "length" in obj) { if (typeof obj.length !== "number" || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === "Buffer" && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.") } function checked(length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + kMaxLength().toString(16) + " bytes") } return length | 0 } function SlowBuffer(length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer(b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare(a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError("Arguments must be Buffers") } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding(encoding) { switch (String(encoding).toLowerCase()) { case "hex": case "utf8": case "utf-8": case "ascii": case "latin1": case "binary": case "base64": case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return true default: return false } } Buffer.concat = function concat(list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength(string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if ( typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer) ) { return string.byteLength } if (typeof string !== "string") { string = "" + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case "ascii": case "latin1": case "binary": return len case "utf8": case "utf-8": case undefined: return utf8ToBytes(string).length case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return len * 2 case "hex": return len >>> 1 case "base64": return base64ToBytes(string).length default: // assume utf8 if (loweredCase) return utf8ToBytes(string).length encoding = ("" + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString(encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return "" } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return "" } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return "" } if (!encoding) encoding = "utf8" while (true) { switch (encoding) { case "hex": return hexSlice(this, start, end) case "utf8": case "utf-8": return utf8Slice(this, start, end) case "ascii": return asciiSlice(this, start, end) case "latin1": case "binary": return latin1Slice(this, start, end) case "base64": return base64Slice(this, start, end) case "ucs2": case "ucs-2": case "utf16le": case "utf-16le": return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError("Unknown encoding: " + encoding) encoding = (encoding + "").toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap(b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16() { var len = this.length if (len % 2 !== 0) { throw new RangeError("Buffer size must be a multiple of 16-bits") } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32() { var len = this.length if (len % 4 !== 0) { throw new RangeError("Buffer size must be a multiple of 32-bits") } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64() { var len = this.length if (len % 8 !== 0) { throw new RangeError("Buffer size must be a multiple of 64-bits") } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString() { var length = this.length | 0 if (length === 0) return "" if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals(b) { if (!Buffer.isBuffer(b)) throw new TypeError("Argument must be a Buffer") if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect() { var str = "" var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString("hex", 0, max).match(/.{2}/g).join(" ") if (this.length > max) str += " ... " } return "<Buffer " + str + ">" } Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError("Argument must be a Buffer") } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError("out of range index") } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === "string") { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : buffer.length - 1 } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === "string") { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === "number") { val = val & 0xff // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) } throw new TypeError("val must be string, number or Buffer") } function arrayIndexOf(arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read(buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1