652 changed files with 170978 additions and 28 deletions
@ -1,10 +0,0 @@ |
|||||
const express = require('express'); |
|
||||
const app = express(); |
|
||||
|
|
||||
app.use((req, res, next) => { |
|
||||
res.status(200).json({ |
|
||||
message: "C'est bon!" |
|
||||
}); // pour envoyer une json response 200
|
|
||||
}); |
|
||||
|
|
||||
module.exports = app; |
|
@ -0,0 +1,35 @@ |
|||||
|
{ |
||||
|
"numEtudiant" : "etu2020001", |
||||
|
"firstname" : "Cecilia", |
||||
|
"lastname" : "Lawrence", |
||||
|
"cycle" : 2, |
||||
|
"adresse" : { |
||||
|
"num" : 12, |
||||
|
"rue" : "des Cailloux", |
||||
|
"ville" : "Amiens", |
||||
|
"pays" : "France" |
||||
|
}, |
||||
|
"email" : [ |
||||
|
"lawrence@gmail.com" |
||||
|
], |
||||
|
"cours" : [ |
||||
|
{ |
||||
|
"code" : "UE001", |
||||
|
"titre" : "réseaux", |
||||
|
"description" : "UE metier", |
||||
|
"credit" : 30 |
||||
|
}, |
||||
|
{ |
||||
|
"code" : "UE005", |
||||
|
"titre" : "administration", |
||||
|
"description" : "UE spécialité", |
||||
|
"credit" : 20 |
||||
|
}, |
||||
|
{ |
||||
|
"code" : "UE003", |
||||
|
"titre" : "systèmes", |
||||
|
"description" : "UE Option", |
||||
|
"credit" : 10 |
||||
|
} |
||||
|
] |
||||
|
} |
@ -0,0 +1,19 @@ |
|||||
|
// Import Etudiant model
|
||||
|
Etudiant = require('./etudiantModel'); |
||||
|
|
||||
|
// Handle index actions
|
||||
|
exports.index = function (req, res) { |
||||
|
Etudiant.get(function (err, etudiants) { |
||||
|
if (err) { |
||||
|
res.json({ |
||||
|
status: "error", |
||||
|
message: err, |
||||
|
}); |
||||
|
} |
||||
|
res.json({ |
||||
|
status: "success", |
||||
|
message: "Voici la liste des etudiants", |
||||
|
data: etudiants |
||||
|
}); |
||||
|
}); |
||||
|
}; |
@ -0,0 +1,32 @@ |
|||||
|
var mongoose = require('mongoose'); // Setup schema
|
||||
|
var etudiantSchema = mongoose.Schema({ |
||||
|
numEtudiant: { |
||||
|
type: String, |
||||
|
required: true |
||||
|
}, |
||||
|
firstname: { |
||||
|
type: String, |
||||
|
required: true |
||||
|
}, |
||||
|
lastname: { |
||||
|
type: String, |
||||
|
required: true |
||||
|
}, |
||||
|
cycle: { |
||||
|
type: Number, |
||||
|
required: true |
||||
|
} |
||||
|
}, |
||||
|
{ |
||||
|
collection : "etudiant" |
||||
|
} |
||||
|
|
||||
|
); |
||||
|
|
||||
|
// Export Etudiant model
|
||||
|
|
||||
|
var Etudiant = module.exports = mongoose.model('etudiant', etudiantSchema); |
||||
|
|
||||
|
module.exports.get = function (callback, limit) { |
||||
|
Etudiant.find(callback).limit(limit); |
||||
|
} |
@ -0,0 +1,42 @@ |
|||||
|
// Import des packages
|
||||
|
const express = require("express") |
||||
|
const mongoose = require("mongoose") |
||||
|
const bodyParser = require('body-parser'); |
||||
|
|
||||
|
// Initialisation de l'app
|
||||
|
const app = express() |
||||
|
|
||||
|
// Import des routes
|
||||
|
const routes = require("./routes") |
||||
|
|
||||
|
// Configure bodyparser to handle post requests
|
||||
|
app.use(bodyParser.urlencoded({ |
||||
|
extended: true |
||||
|
})); |
||||
|
|
||||
|
app.use(bodyParser.json()); |
||||
|
|
||||
|
|
||||
|
app.get('/', (req, res) => res.send('Hello, allez à <a href="/api/etudiants">API-Etudiants</a>')); // route racine
|
||||
|
|
||||
|
app.use("/api",routes) // route /api par défaut
|
||||
|
|
||||
|
|
||||
|
// Connexion à MongoDB database
|
||||
|
mongoose.connect("mongodb://localhost:27017/TestDB", { useNewUrlParser: true }) |
||||
|
|
||||
|
var db = mongoose.connection; |
||||
|
|
||||
|
// Verification de connexion à MongoDB
|
||||
|
if(!db) |
||||
|
console.log("Erreur de connexion à la base MondoDB") |
||||
|
else |
||||
|
console.log("Connexion MongoDB success") |
||||
|
|
||||
|
// Setup server port
|
||||
|
var port = process.env.PORT || 3000; |
||||
|
|
||||
|
|
||||
|
app.listen(port, () => { |
||||
|
console.log("Server has started! Port:" + port) |
||||
|
}) |
@ -0,0 +1 @@ |
|||||
|
../semver/bin/semver |
@ -0,0 +1,60 @@ |
|||||
|
{ |
||||
|
"predef": [ ] |
||||
|
, "bitwise": false |
||||
|
, "camelcase": false |
||||
|
, "curly": false |
||||
|
, "eqeqeq": false |
||||
|
, "forin": false |
||||
|
, "immed": false |
||||
|
, "latedef": false |
||||
|
, "noarg": true |
||||
|
, "noempty": true |
||||
|
, "nonew": true |
||||
|
, "plusplus": false |
||||
|
, "quotmark": true |
||||
|
, "regexp": false |
||||
|
, "undef": true |
||||
|
, "unused": true |
||||
|
, "strict": false |
||||
|
, "trailing": true |
||||
|
, "maxlen": 120 |
||||
|
, "asi": true |
||||
|
, "boss": true |
||||
|
, "debug": true |
||||
|
, "eqnull": true |
||||
|
, "esnext": false |
||||
|
, "evil": true |
||||
|
, "expr": true |
||||
|
, "funcscope": false |
||||
|
, "globalstrict": false |
||||
|
, "iterator": false |
||||
|
, "lastsemic": true |
||||
|
, "laxbreak": true |
||||
|
, "laxcomma": true |
||||
|
, "loopfunc": true |
||||
|
, "multistr": false |
||||
|
, "onecase": false |
||||
|
, "proto": false |
||||
|
, "regexdash": false |
||||
|
, "scripturl": true |
||||
|
, "smarttabs": false |
||||
|
, "shadow": false |
||||
|
, "sub": true |
||||
|
, "supernew": false |
||||
|
, "validthis": true |
||||
|
, "browser": true |
||||
|
, "couch": false |
||||
|
, "devel": false |
||||
|
, "dojo": false |
||||
|
, "mootools": false |
||||
|
, "node": true |
||||
|
, "nonstandard": true |
||||
|
, "prototypejs": false |
||||
|
, "rhino": false |
||||
|
, "worker": true |
||||
|
, "wsh": false |
||||
|
, "nomen": false |
||||
|
, "onevar": false |
||||
|
, "passfail": false |
||||
|
, "esversion": 3 |
||||
|
} |
@ -0,0 +1,15 @@ |
|||||
|
sudo: false |
||||
|
language: node_js |
||||
|
node_js: |
||||
|
- '4' |
||||
|
- '6' |
||||
|
- '8' |
||||
|
- '9' |
||||
|
- '10' |
||||
|
branches: |
||||
|
only: |
||||
|
- master |
||||
|
notifications: |
||||
|
email: |
||||
|
- rod@vagg.org |
||||
|
- matteo.collina@gmail.com |
@ -0,0 +1,13 @@ |
|||||
|
The MIT License (MIT) |
||||
|
===================== |
||||
|
|
||||
|
Copyright (c) 2013-2018 bl contributors |
||||
|
---------------------------------- |
||||
|
|
||||
|
*bl contributors listed at <https://github.com/rvagg/bl#contributors>* |
||||
|
|
||||
|
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. |
@ -0,0 +1,218 @@ |
|||||
|
# bl *(BufferList)* |
||||
|
|
||||
|
[](https://travis-ci.org/rvagg/bl) |
||||
|
|
||||
|
**A Node.js Buffer list collector, reader and streamer thingy.** |
||||
|
|
||||
|
[](https://nodei.co/npm/bl/) |
||||
|
[](https://nodei.co/npm/bl/) |
||||
|
|
||||
|
**bl** is a storage object for collections of Node Buffers, exposing them with the main Buffer readable API. Also works as a duplex stream so you can collect buffers from a stream that emits them and emit buffers to a stream that consumes them! |
||||
|
|
||||
|
The original buffers are kept intact and copies are only done as necessary. Any reads that require the use of a single original buffer will return a slice of that buffer only (which references the same memory as the original buffer). Reads that span buffers perform concatenation as required and return the results transparently. |
||||
|
|
||||
|
```js |
||||
|
const BufferList = require('bl') |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append('hi') // bl will also accept & convert Strings |
||||
|
bl.append(Buffer.from('j')) |
||||
|
bl.append(Buffer.from([ 0x3, 0x4 ])) |
||||
|
|
||||
|
console.log(bl.length) // 12 |
||||
|
|
||||
|
console.log(bl.slice(0, 10).toString('ascii')) // 'abcdefghij' |
||||
|
console.log(bl.slice(3, 10).toString('ascii')) // 'defghij' |
||||
|
console.log(bl.slice(3, 6).toString('ascii')) // 'def' |
||||
|
console.log(bl.slice(3, 8).toString('ascii')) // 'defgh' |
||||
|
console.log(bl.slice(5, 10).toString('ascii')) // 'fghij' |
||||
|
|
||||
|
console.log(bl.indexOf('def')) // 3 |
||||
|
console.log(bl.indexOf('asdf')) // -1 |
||||
|
|
||||
|
// or just use toString! |
||||
|
console.log(bl.toString()) // 'abcdefghij\u0003\u0004' |
||||
|
console.log(bl.toString('ascii', 3, 8)) // 'defgh' |
||||
|
console.log(bl.toString('ascii', 5, 10)) // 'fghij' |
||||
|
|
||||
|
// other standard Buffer readables |
||||
|
console.log(bl.readUInt16BE(10)) // 0x0304 |
||||
|
console.log(bl.readUInt16LE(10)) // 0x0403 |
||||
|
``` |
||||
|
|
||||
|
Give it a callback in the constructor and use it just like **[concat-stream](https://github.com/maxogden/node-concat-stream)**: |
||||
|
|
||||
|
```js |
||||
|
const bl = require('bl') |
||||
|
, fs = require('fs') |
||||
|
|
||||
|
fs.createReadStream('README.md') |
||||
|
.pipe(bl(function (err, data) { // note 'new' isn't strictly required |
||||
|
// `data` is a complete Buffer object containing the full data |
||||
|
console.log(data.toString()) |
||||
|
})) |
||||
|
``` |
||||
|
|
||||
|
Note that when you use the *callback* method like this, the resulting `data` parameter is a concatenation of all `Buffer` objects in the list. If you want to avoid the overhead of this concatenation (in cases of extreme performance consciousness), then avoid the *callback* method and just listen to `'end'` instead, like a standard Stream. |
||||
|
|
||||
|
Or to fetch a URL using [hyperquest](https://github.com/substack/hyperquest) (should work with [request](http://github.com/mikeal/request) and even plain Node http too!): |
||||
|
```js |
||||
|
const hyperquest = require('hyperquest') |
||||
|
, bl = require('bl') |
||||
|
, url = 'https://raw.github.com/rvagg/bl/master/README.md' |
||||
|
|
||||
|
hyperquest(url).pipe(bl(function (err, data) { |
||||
|
console.log(data.toString()) |
||||
|
})) |
||||
|
``` |
||||
|
|
||||
|
Or, use it as a readable stream to recompose a list of Buffers to an output source: |
||||
|
|
||||
|
```js |
||||
|
const BufferList = require('bl') |
||||
|
, fs = require('fs') |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
|
||||
|
bl.pipe(fs.createWriteStream('gibberish.txt')) |
||||
|
``` |
||||
|
|
||||
|
## API |
||||
|
|
||||
|
* <a href="#ctor"><code><b>new BufferList([ callback ])</b></code></a> |
||||
|
* <a href="#length"><code>bl.<b>length</b></code></a> |
||||
|
* <a href="#append"><code>bl.<b>append(buffer)</b></code></a> |
||||
|
* <a href="#get"><code>bl.<b>get(index)</b></code></a> |
||||
|
* <a href="#indexOf"><code>bl.<b>indexOf(value[, byteOffset][, encoding])</b></code></a> |
||||
|
* <a href="#slice"><code>bl.<b>slice([ start[, end ] ])</b></code></a> |
||||
|
* <a href="#shallowSlice"><code>bl.<b>shallowSlice([ start[, end ] ])</b></code></a> |
||||
|
* <a href="#copy"><code>bl.<b>copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ])</b></code></a> |
||||
|
* <a href="#duplicate"><code>bl.<b>duplicate()</b></code></a> |
||||
|
* <a href="#consume"><code>bl.<b>consume(bytes)</b></code></a> |
||||
|
* <a href="#toString"><code>bl.<b>toString([encoding, [ start, [ end ]]])</b></code></a> |
||||
|
* <a href="#readXX"><code>bl.<b>readDoubleBE()</b></code>, <code>bl.<b>readDoubleLE()</b></code>, <code>bl.<b>readFloatBE()</b></code>, <code>bl.<b>readFloatLE()</b></code>, <code>bl.<b>readInt32BE()</b></code>, <code>bl.<b>readInt32LE()</b></code>, <code>bl.<b>readUInt32BE()</b></code>, <code>bl.<b>readUInt32LE()</b></code>, <code>bl.<b>readInt16BE()</b></code>, <code>bl.<b>readInt16LE()</b></code>, <code>bl.<b>readUInt16BE()</b></code>, <code>bl.<b>readUInt16LE()</b></code>, <code>bl.<b>readInt8()</b></code>, <code>bl.<b>readUInt8()</b></code></a> |
||||
|
* <a href="#streams">Streams</a> |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="ctor"></a> |
||||
|
### new BufferList([ callback | Buffer | Buffer array | BufferList | BufferList array | String ]) |
||||
|
The constructor takes an optional callback, if supplied, the callback will be called with an error argument followed by a reference to the **bl** instance, when `bl.end()` is called (i.e. from a piped stream). This is a convenient method of collecting the entire contents of a stream, particularly when the stream is *chunky*, such as a network stream. |
||||
|
|
||||
|
Normally, no arguments are required for the constructor, but you can initialise the list by passing in a single `Buffer` object or an array of `Buffer` object. |
||||
|
|
||||
|
`new` is not strictly required, if you don't instantiate a new object, it will be done automatically for you so you can create a new instance simply with: |
||||
|
|
||||
|
```js |
||||
|
var bl = require('bl') |
||||
|
var myinstance = bl() |
||||
|
|
||||
|
// equivalent to: |
||||
|
|
||||
|
var BufferList = require('bl') |
||||
|
var myinstance = new BufferList() |
||||
|
``` |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="length"></a> |
||||
|
### bl.length |
||||
|
Get the length of the list in bytes. This is the sum of the lengths of all of the buffers contained in the list, minus any initial offset for a semi-consumed buffer at the beginning. Should accurately represent the total number of bytes that can be read from the list. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="append"></a> |
||||
|
### bl.append(Buffer | Buffer array | BufferList | BufferList array | String) |
||||
|
`append(buffer)` adds an additional buffer or BufferList to the internal list. `this` is returned so it can be chained. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="get"></a> |
||||
|
### bl.get(index) |
||||
|
`get()` will return the byte at the specified index. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="indexOf"></a> |
||||
|
### bl.indexOf(value[, byteOffset][, encoding]) |
||||
|
`get()` will return the byte at the specified index. |
||||
|
`indexOf()` method returns the first index at which a given element can be found in the BufferList, or -1 if it is not present. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="slice"></a> |
||||
|
### bl.slice([ start, [ end ] ]) |
||||
|
`slice()` returns a new `Buffer` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. |
||||
|
|
||||
|
If the requested range spans a single internal buffer then a slice of that buffer will be returned which shares the original memory range of that Buffer. If the range spans multiple buffers then copy operations will likely occur to give you a uniform Buffer. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="shallowSlice"></a> |
||||
|
### bl.shallowSlice([ start, [ end ] ]) |
||||
|
`shallowSlice()` returns a new `BufferList` object containing the bytes within the range specified. Both `start` and `end` are optional and will default to the beginning and end of the list respectively. |
||||
|
|
||||
|
No copies will be performed. All buffers in the result share memory with the original list. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="copy"></a> |
||||
|
### bl.copy(dest, [ destStart, [ srcStart [, srcEnd ] ] ]) |
||||
|
`copy()` copies the content of the list in the `dest` buffer, starting from `destStart` and containing the bytes within the range specified with `srcStart` to `srcEnd`. `destStart`, `start` and `end` are optional and will default to the beginning of the `dest` buffer, and the beginning and end of the list respectively. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="duplicate"></a> |
||||
|
### bl.duplicate() |
||||
|
`duplicate()` performs a **shallow-copy** of the list. The internal Buffers remains the same, so if you change the underlying Buffers, the change will be reflected in both the original and the duplicate. This method is needed if you want to call `consume()` or `pipe()` and still keep the original list.Example: |
||||
|
|
||||
|
```js |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append('hello') |
||||
|
bl.append(' world') |
||||
|
bl.append('\n') |
||||
|
|
||||
|
bl.duplicate().pipe(process.stdout, { end: false }) |
||||
|
|
||||
|
console.log(bl.toString()) |
||||
|
``` |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="consume"></a> |
||||
|
### bl.consume(bytes) |
||||
|
`consume()` will shift bytes *off the start of the list*. The number of bytes consumed don't need to line up with the sizes of the internal Buffers—initial offsets will be calculated accordingly in order to give you a consistent view of the data. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="toString"></a> |
||||
|
### bl.toString([encoding, [ start, [ end ]]]) |
||||
|
`toString()` will return a string representation of the buffer. The optional `start` and `end` arguments are passed on to `slice()`, while the `encoding` is passed on to `toString()` of the resulting Buffer. See the [Buffer#toString()](http://nodejs.org/docs/latest/api/buffer.html#buffer_buf_tostring_encoding_start_end) documentation for more information. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="readXX"></a> |
||||
|
### bl.readDoubleBE(), bl.readDoubleLE(), bl.readFloatBE(), bl.readFloatLE(), bl.readInt32BE(), bl.readInt32LE(), bl.readUInt32BE(), bl.readUInt32LE(), bl.readInt16BE(), bl.readInt16LE(), bl.readUInt16BE(), bl.readUInt16LE(), bl.readInt8(), bl.readUInt8() |
||||
|
|
||||
|
All of the standard byte-reading methods of the `Buffer` interface are implemented and will operate across internal Buffer boundaries transparently. |
||||
|
|
||||
|
See the <b><code>[Buffer](http://nodejs.org/docs/latest/api/buffer.html)</code></b> documentation for how these work. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
<a name="streams"></a> |
||||
|
### Streams |
||||
|
**bl** is a Node **[Duplex Stream](http://nodejs.org/docs/latest/api/stream.html#stream_class_stream_duplex)**, so it can be read from and written to like a standard Node stream. You can also `pipe()` to and from a **bl** instance. |
||||
|
|
||||
|
-------------------------------------------------------- |
||||
|
|
||||
|
## Contributors |
||||
|
|
||||
|
**bl** is brought to you by the following hackers: |
||||
|
|
||||
|
* [Rod Vagg](https://github.com/rvagg) |
||||
|
* [Matteo Collina](https://github.com/mcollina) |
||||
|
* [Jarett Cruger](https://github.com/jcrugzz) |
||||
|
|
||||
|
======= |
||||
|
|
||||
|
<a name="license"></a> |
||||
|
## License & copyright |
||||
|
|
||||
|
Copyright (c) 2013-2018 bl contributors (listed above). |
||||
|
|
||||
|
bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details. |
@ -0,0 +1,383 @@ |
|||||
|
'use strict' |
||||
|
var DuplexStream = require('readable-stream').Duplex |
||||
|
, util = require('util') |
||||
|
, Buffer = require('safe-buffer').Buffer |
||||
|
|
||||
|
function BufferList (callback) { |
||||
|
if (!(this instanceof BufferList)) |
||||
|
return new BufferList(callback) |
||||
|
|
||||
|
this._bufs = [] |
||||
|
this.length = 0 |
||||
|
|
||||
|
if (typeof callback == 'function') { |
||||
|
this._callback = callback |
||||
|
|
||||
|
var piper = function piper (err) { |
||||
|
if (this._callback) { |
||||
|
this._callback(err) |
||||
|
this._callback = null |
||||
|
} |
||||
|
}.bind(this) |
||||
|
|
||||
|
this.on('pipe', function onPipe (src) { |
||||
|
src.on('error', piper) |
||||
|
}) |
||||
|
this.on('unpipe', function onUnpipe (src) { |
||||
|
src.removeListener('error', piper) |
||||
|
}) |
||||
|
} else { |
||||
|
this.append(callback) |
||||
|
} |
||||
|
|
||||
|
DuplexStream.call(this) |
||||
|
} |
||||
|
|
||||
|
|
||||
|
util.inherits(BufferList, DuplexStream) |
||||
|
|
||||
|
|
||||
|
BufferList.prototype._offset = function _offset (offset) { |
||||
|
var tot = 0, i = 0, _t |
||||
|
if (offset === 0) return [ 0, 0 ] |
||||
|
for (; i < this._bufs.length; i++) { |
||||
|
_t = tot + this._bufs[i].length |
||||
|
if (offset < _t || i == this._bufs.length - 1) { |
||||
|
return [ i, offset - tot ] |
||||
|
} |
||||
|
tot = _t |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype._reverseOffset = function (blOffset) { |
||||
|
var bufferId = blOffset[0] |
||||
|
var offset = blOffset[1] |
||||
|
for (var i = 0; i < bufferId; i++) { |
||||
|
offset += this._bufs[i].length |
||||
|
} |
||||
|
return offset |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype.append = function append (buf) { |
||||
|
var i = 0 |
||||
|
|
||||
|
if (Buffer.isBuffer(buf)) { |
||||
|
this._appendBuffer(buf) |
||||
|
} else if (Array.isArray(buf)) { |
||||
|
for (; i < buf.length; i++) |
||||
|
this.append(buf[i]) |
||||
|
} else if (buf instanceof BufferList) { |
||||
|
// unwrap argument into individual BufferLists
|
||||
|
for (; i < buf._bufs.length; i++) |
||||
|
this.append(buf._bufs[i]) |
||||
|
} else if (buf != null) { |
||||
|
// coerce number arguments to strings, since Buffer(number) does
|
||||
|
// uninitialized memory allocation
|
||||
|
if (typeof buf == 'number') |
||||
|
buf = buf.toString() |
||||
|
|
||||
|
this._appendBuffer(Buffer.from(buf)) |
||||
|
} |
||||
|
|
||||
|
return this |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype._appendBuffer = function appendBuffer (buf) { |
||||
|
this._bufs.push(buf) |
||||
|
this.length += buf.length |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype._write = function _write (buf, encoding, callback) { |
||||
|
this._appendBuffer(buf) |
||||
|
|
||||
|
if (typeof callback == 'function') |
||||
|
callback() |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype._read = function _read (size) { |
||||
|
if (!this.length) |
||||
|
return this.push(null) |
||||
|
|
||||
|
size = Math.min(size, this.length) |
||||
|
this.push(this.slice(0, size)) |
||||
|
this.consume(size) |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.end = function end (chunk) { |
||||
|
DuplexStream.prototype.end.call(this, chunk) |
||||
|
|
||||
|
if (this._callback) { |
||||
|
this._callback(null, this.slice()) |
||||
|
this._callback = null |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.get = function get (index) { |
||||
|
if (index > this.length || index < 0) { |
||||
|
return undefined |
||||
|
} |
||||
|
var offset = this._offset(index) |
||||
|
return this._bufs[offset[0]][offset[1]] |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.slice = function slice (start, end) { |
||||
|
if (typeof start == 'number' && start < 0) |
||||
|
start += this.length |
||||
|
if (typeof end == 'number' && end < 0) |
||||
|
end += this.length |
||||
|
return this.copy(null, 0, start, end) |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { |
||||
|
if (typeof srcStart != 'number' || srcStart < 0) |
||||
|
srcStart = 0 |
||||
|
if (typeof srcEnd != 'number' || srcEnd > this.length) |
||||
|
srcEnd = this.length |
||||
|
if (srcStart >= this.length) |
||||
|
return dst || Buffer.alloc(0) |
||||
|
if (srcEnd <= 0) |
||||
|
return dst || Buffer.alloc(0) |
||||
|
|
||||
|
var copy = !!dst |
||||
|
, off = this._offset(srcStart) |
||||
|
, len = srcEnd - srcStart |
||||
|
, bytes = len |
||||
|
, bufoff = (copy && dstStart) || 0 |
||||
|
, start = off[1] |
||||
|
, l |
||||
|
, i |
||||
|
|
||||
|
// copy/slice everything
|
||||
|
if (srcStart === 0 && srcEnd == this.length) { |
||||
|
if (!copy) { // slice, but full concat if multiple buffers
|
||||
|
return this._bufs.length === 1 |
||||
|
? this._bufs[0] |
||||
|
: Buffer.concat(this._bufs, this.length) |
||||
|
} |
||||
|
|
||||
|
// copy, need to copy individual buffers
|
||||
|
for (i = 0; i < this._bufs.length; i++) { |
||||
|
this._bufs[i].copy(dst, bufoff) |
||||
|
bufoff += this._bufs[i].length |
||||
|
} |
||||
|
|
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
// easy, cheap case where it's a subset of one of the buffers
|
||||
|
if (bytes <= this._bufs[off[0]].length - start) { |
||||
|
return copy |
||||
|
? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) |
||||
|
: this._bufs[off[0]].slice(start, start + bytes) |
||||
|
} |
||||
|
|
||||
|
if (!copy) // a slice, we need something to copy in to
|
||||
|
dst = Buffer.allocUnsafe(len) |
||||
|
|
||||
|
for (i = off[0]; i < this._bufs.length; i++) { |
||||
|
l = this._bufs[i].length - start |
||||
|
|
||||
|
if (bytes > l) { |
||||
|
this._bufs[i].copy(dst, bufoff, start) |
||||
|
} else { |
||||
|
this._bufs[i].copy(dst, bufoff, start, start + bytes) |
||||
|
break |
||||
|
} |
||||
|
|
||||
|
bufoff += l |
||||
|
bytes -= l |
||||
|
|
||||
|
if (start) |
||||
|
start = 0 |
||||
|
} |
||||
|
|
||||
|
return dst |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype.shallowSlice = function shallowSlice (start, end) { |
||||
|
start = start || 0 |
||||
|
end = typeof end !== 'number' ? this.length : end |
||||
|
|
||||
|
if (start < 0) |
||||
|
start += this.length |
||||
|
if (end < 0) |
||||
|
end += this.length |
||||
|
|
||||
|
if (start === end) { |
||||
|
return new BufferList() |
||||
|
} |
||||
|
var startOffset = this._offset(start) |
||||
|
, endOffset = this._offset(end) |
||||
|
, buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) |
||||
|
|
||||
|
if (endOffset[1] == 0) |
||||
|
buffers.pop() |
||||
|
else |
||||
|
buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1]) |
||||
|
|
||||
|
if (startOffset[1] != 0) |
||||
|
buffers[0] = buffers[0].slice(startOffset[1]) |
||||
|
|
||||
|
return new BufferList(buffers) |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype.toString = function toString (encoding, start, end) { |
||||
|
return this.slice(start, end).toString(encoding) |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype.consume = function consume (bytes) { |
||||
|
while (this._bufs.length) { |
||||
|
if (bytes >= this._bufs[0].length) { |
||||
|
bytes -= this._bufs[0].length |
||||
|
this.length -= this._bufs[0].length |
||||
|
this._bufs.shift() |
||||
|
} else { |
||||
|
this._bufs[0] = this._bufs[0].slice(bytes) |
||||
|
this.length -= bytes |
||||
|
break |
||||
|
} |
||||
|
} |
||||
|
return this |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.duplicate = function duplicate () { |
||||
|
var i = 0 |
||||
|
, copy = new BufferList() |
||||
|
|
||||
|
for (; i < this._bufs.length; i++) |
||||
|
copy.append(this._bufs[i]) |
||||
|
|
||||
|
return copy |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.destroy = function destroy () { |
||||
|
this._bufs.length = 0 |
||||
|
this.length = 0 |
||||
|
this.push(null) |
||||
|
} |
||||
|
|
||||
|
|
||||
|
BufferList.prototype.indexOf = function (search, offset, encoding) { |
||||
|
if (encoding === undefined && typeof offset === 'string') { |
||||
|
encoding = offset |
||||
|
offset = undefined |
||||
|
} |
||||
|
if (typeof search === 'function' || Array.isArray(search)) { |
||||
|
throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') |
||||
|
} else if (typeof search === 'number') { |
||||
|
search = Buffer.from([search]) |
||||
|
} else if (typeof search === 'string') { |
||||
|
search = Buffer.from(search, encoding) |
||||
|
} else if (search instanceof BufferList) { |
||||
|
search = search.slice() |
||||
|
} else if (!Buffer.isBuffer(search)) { |
||||
|
search = Buffer.from(search) |
||||
|
} |
||||
|
|
||||
|
offset = Number(offset || 0) |
||||
|
if (isNaN(offset)) { |
||||
|
offset = 0 |
||||
|
} |
||||
|
|
||||
|
if (offset < 0) { |
||||
|
offset = this.length + offset |
||||
|
} |
||||
|
|
||||
|
if (offset < 0) { |
||||
|
offset = 0 |
||||
|
} |
||||
|
|
||||
|
if (search.length === 0) { |
||||
|
return offset > this.length ? this.length : offset |
||||
|
} |
||||
|
|
||||
|
var blOffset = this._offset(offset) |
||||
|
var blIndex = blOffset[0] // index of which internal buffer we're working on
|
||||
|
var buffOffset = blOffset[1] // offset of the internal buffer we're working on
|
||||
|
|
||||
|
// scan over each buffer
|
||||
|
for (blIndex; blIndex < this._bufs.length; blIndex++) { |
||||
|
var buff = this._bufs[blIndex] |
||||
|
while(buffOffset < buff.length) { |
||||
|
var availableWindow = buff.length - buffOffset |
||||
|
if (availableWindow >= search.length) { |
||||
|
var nativeSearchResult = buff.indexOf(search, buffOffset) |
||||
|
if (nativeSearchResult !== -1) { |
||||
|
return this._reverseOffset([blIndex, nativeSearchResult]) |
||||
|
} |
||||
|
buffOffset = buff.length - search.length + 1 // end of native search window
|
||||
|
} else { |
||||
|
var revOffset = this._reverseOffset([blIndex, buffOffset]) |
||||
|
if (this._match(revOffset, search)) { |
||||
|
return revOffset |
||||
|
} |
||||
|
buffOffset++ |
||||
|
} |
||||
|
} |
||||
|
buffOffset = 0 |
||||
|
} |
||||
|
return -1 |
||||
|
} |
||||
|
|
||||
|
BufferList.prototype._match = function(offset, search) { |
||||
|
if (this.length - offset < search.length) { |
||||
|
return false |
||||
|
} |
||||
|
for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) { |
||||
|
if(this.get(offset + searchOffset) !== search[searchOffset]){ |
||||
|
return false |
||||
|
} |
||||
|
} |
||||
|
return true |
||||
|
} |
||||
|
|
||||
|
|
||||
|
;(function () { |
||||
|
var methods = { |
||||
|
'readDoubleBE' : 8 |
||||
|
, 'readDoubleLE' : 8 |
||||
|
, 'readFloatBE' : 4 |
||||
|
, 'readFloatLE' : 4 |
||||
|
, 'readInt32BE' : 4 |
||||
|
, 'readInt32LE' : 4 |
||||
|
, 'readUInt32BE' : 4 |
||||
|
, 'readUInt32LE' : 4 |
||||
|
, 'readInt16BE' : 2 |
||||
|
, 'readInt16LE' : 2 |
||||
|
, 'readUInt16BE' : 2 |
||||
|
, 'readUInt16LE' : 2 |
||||
|
, 'readInt8' : 1 |
||||
|
, 'readUInt8' : 1 |
||||
|
, 'readIntBE' : null |
||||
|
, 'readIntLE' : null |
||||
|
, 'readUIntBE' : null |
||||
|
, 'readUIntLE' : null |
||||
|
} |
||||
|
|
||||
|
for (var m in methods) { |
||||
|
(function (m) { |
||||
|
if (methods[m] === null) { |
||||
|
BufferList.prototype[m] = function (offset, byteLength) { |
||||
|
return this.slice(offset, offset + byteLength)[m](0, byteLength) |
||||
|
} |
||||
|
} |
||||
|
else { |
||||
|
BufferList.prototype[m] = function (offset) { |
||||
|
return this.slice(offset, offset + methods[m])[m](0) |
||||
|
} |
||||
|
} |
||||
|
}(m)) |
||||
|
} |
||||
|
}()) |
||||
|
|
||||
|
|
||||
|
module.exports = BufferList |
@ -0,0 +1,99 @@ |
|||||
|
{ |
||||
|
"_args": [ |
||||
|
[ |
||||
|
"bl@^2.2.0", |
||||
|
"/home/art/Documents/API-REST-Etudiants/api/node_modules/mongodb" |
||||
|
] |
||||
|
], |
||||
|
"_from": "bl@>=2.2.0 <3.0.0", |
||||
|
"_hasShrinkwrap": false, |
||||
|
"_id": "bl@2.2.0", |
||||
|
"_inCache": true, |
||||
|
"_installable": true, |
||||
|
"_location": "/bl", |
||||
|
"_nodeVersion": "10.14.2", |
||||
|
"_npmOperationalInternal": { |
||||
|
"host": "s3://npm-registry-packages", |
||||
|
"tmp": "tmp/bl_2.2.0_1549182523075_0.8810481806404531" |
||||
|
}, |
||||
|
"_npmUser": { |
||||
|
"email": "hello@matteocollina.com", |
||||
|
"name": "matteo.collina" |
||||
|
}, |
||||
|
"_npmVersion": "6.7.0", |
||||
|
"_phantomChildren": {}, |
||||
|
"_requested": { |
||||
|
"name": "bl", |
||||
|
"raw": "bl@^2.2.0", |
||||
|
"rawSpec": "^2.2.0", |
||||
|
"scope": null, |
||||
|
"spec": ">=2.2.0 <3.0.0", |
||||
|
"type": "range" |
||||
|
}, |
||||
|
"_requiredBy": [ |
||||
|
"/mongodb" |
||||
|
], |
||||
|
"_resolved": "https://registry.npmjs.org/bl/-/bl-2.2.0.tgz", |
||||
|
"_shasum": "e1a574cdf528e4053019bb800b041c0ac88da493", |
||||
|
"_shrinkwrap": null, |
||||
|
"_spec": "bl@^2.2.0", |
||||
|
"_where": "/home/art/Documents/API-REST-Etudiants/api/node_modules/mongodb", |
||||
|
"authors": [ |
||||
|
"Jarett Cruger <jcrugzz@gmail.com> (https://github.com/jcrugzz)", |
||||
|
"Matteo Collina <matteo.collina@gmail.com> (https://github.com/mcollina)", |
||||
|
"Rod Vagg <rod@vagg.org> (https://github.com/rvagg)" |
||||
|
], |
||||
|
"bugs": { |
||||
|
"url": "https://github.com/rvagg/bl/issues" |
||||
|
}, |
||||
|
"dependencies": { |
||||
|
"readable-stream": "^2.3.5", |
||||
|
"safe-buffer": "^5.1.1" |
||||
|
}, |
||||
|
"description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!", |
||||
|
"devDependencies": { |
||||
|
"faucet": "0.0.1", |
||||
|
"hash_file": "~0.1.1", |
||||
|
"tape": "~4.9.0" |
||||
|
}, |
||||
|
"directories": {}, |
||||
|
"dist": { |
||||
|
"fileCount": 8, |
||||
|
"integrity": "sha512-wbgvOpqopSr7uq6fJrLH8EsvYMJf9gzfo2jCsL2eTy75qXPukA4pCgHamOQkZtY5vmfVtjB+P3LNlMHW5CEZXA==", |
||||
|
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJcVqY7CRA9TVsSAnZWagAAzoYP/2T28EHNevUmzZz/mqtI\n7kk7RXGycVXjuGcMK/OfTenSOxeZ3eQWOelWW7LGJI5O611iPUM8Yvp9X2Hq\nBa217h3KDZ0kaooNS85seflVDLufjgsh2SsPz9zP58UjTCRK0768U1xwB7A/\nT4ExS63s5NjqRfxTbydcpvt4ObCrib+z5aSSHRbhiml18oYfWlKHqknsgWfe\nBNAUz7tPEzHtnlY1nprup2n96kZwBrOD7m1SX0X1wh6ND2Yuex8LGwdtgzL6\nSmadUyv7c6Pvzkb4JVGBGd3flKdIWzexFNscgLNEpkihi6NQLTmSaMrzxVdt\nc8gpbbTgA4IBiX5sYZ3s70/iBR0baxVlLe43yiHXr4B2MvcmJVQT1SYiSZoP\nMM8vSYkA3FgO8gRLozyZ7lLrK0DqYJpWwhOVMh5BU+9Tk9FD0cKmmo0QT19V\nhmr30NfIN/JKzvwj+6eIuJfEJ+l0Lpn/tRpnIP4ZFWKo1APs6IqSDTR7bQWP\nRsguv7C2lzcxAsf7MqNpQFbI4VGr5P6o2hW7rp4cWb3zrjij0PKyxNQkeDji\n5IVJ3KRL1jAnthiHMdTofGlh5fs8bUqb5WRzhxmRaV7lPKthwIg/YHU34HJ/\nmDA3d99iz4+4vh7u89YAJw06C+TIFhHart3TKoWd3XNJ6mVJS9QVXzv8pb2T\nJtfg\r\n=6SMP\r\n-----END PGP SIGNATURE-----\r\n", |
||||
|
"shasum": "e1a574cdf528e4053019bb800b041c0ac88da493", |
||||
|
"tarball": "https://registry.npmjs.org/bl/-/bl-2.2.0.tgz", |
||||
|
"unpackedSize": 58589 |
||||
|
}, |
||||
|
"gitHead": "b6284a824a8aae312e640afb0d59ac24139f0a36", |
||||
|
"homepage": "https://github.com/rvagg/bl", |
||||
|
"keywords": [ |
||||
|
"awesomesauce", |
||||
|
"buffer", |
||||
|
"buffers", |
||||
|
"stream" |
||||
|
], |
||||
|
"license": "MIT", |
||||
|
"main": "bl.js", |
||||
|
"maintainers": [ |
||||
|
{ |
||||
|
"name": "matteo.collina", |
||||
|
"email": "hello@matteocollina.com" |
||||
|
}, |
||||
|
{ |
||||
|
"name": "rvagg", |
||||
|
"email": "rod@vagg.org" |
||||
|
} |
||||
|
], |
||||
|
"name": "bl", |
||||
|
"optionalDependencies": {}, |
||||
|
"readme": "ERROR: No README data found!", |
||||
|
"repository": { |
||||
|
"type": "git", |
||||
|
"url": "git+https://github.com/rvagg/bl.git" |
||||
|
}, |
||||
|
"scripts": { |
||||
|
"test": "node test/test.js | faucet" |
||||
|
}, |
||||
|
"version": "2.2.0" |
||||
|
} |
@ -0,0 +1,463 @@ |
|||||
|
'use strict' |
||||
|
|
||||
|
var tape = require('tape') |
||||
|
, BufferList = require('../') |
||||
|
, Buffer = require('safe-buffer').Buffer |
||||
|
|
||||
|
tape('indexOf single byte needle', t => { |
||||
|
const bl = new BufferList(['abcdefg', 'abcdefg', '12345']) |
||||
|
t.equal(bl.indexOf('e'), 4) |
||||
|
t.equal(bl.indexOf('e', 5), 11) |
||||
|
t.equal(bl.indexOf('e', 12), -1) |
||||
|
t.equal(bl.indexOf('5'), 18) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf multiple byte needle', t => { |
||||
|
const bl = new BufferList(['abcdefg', 'abcdefg']) |
||||
|
t.equal(bl.indexOf('ef'), 4) |
||||
|
t.equal(bl.indexOf('ef', 5), 11) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf multiple byte needles across buffer boundaries', t => { |
||||
|
const bl = new BufferList(['abcdefg', 'abcdefg']) |
||||
|
t.equal(bl.indexOf('fgabc'), 5) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf takes a buffer list search', t => { |
||||
|
const bl = new BufferList(['abcdefg', 'abcdefg']) |
||||
|
const search = new BufferList('fgabc') |
||||
|
t.equal(bl.indexOf(search), 5) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf a zero byte needle', t => { |
||||
|
const b = new BufferList('abcdef') |
||||
|
const buf_empty = Buffer.from('') |
||||
|
t.equal(b.indexOf(''), 0) |
||||
|
t.equal(b.indexOf('', 1), 1) |
||||
|
t.equal(b.indexOf('', b.length + 1), b.length) |
||||
|
t.equal(b.indexOf('', Infinity), b.length) |
||||
|
t.equal(b.indexOf(buf_empty), 0) |
||||
|
t.equal(b.indexOf(buf_empty, 1), 1) |
||||
|
t.equal(b.indexOf(buf_empty, b.length + 1), b.length) |
||||
|
t.equal(b.indexOf(buf_empty, Infinity), b.length) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf buffers smaller and larger than the needle', t => { |
||||
|
const bl = new BufferList(['abcdefg', 'a', 'bcdefg', 'a', 'bcfgab']) |
||||
|
t.equal(bl.indexOf('fgabc'), 5) |
||||
|
t.equal(bl.indexOf('fgabc', 6), 12) |
||||
|
t.equal(bl.indexOf('fgabc', 13), -1) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
// only present in node 6+
|
||||
|
;(process.version.substr(1).split('.')[0] >= 6) && tape('indexOf latin1 and binary encoding', t => { |
||||
|
const b = new BufferList('abcdef') |
||||
|
|
||||
|
// test latin1 encoding
|
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) |
||||
|
.indexOf('d', 0, 'latin1'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from(b.toString('latin1'), 'latin1')) |
||||
|
.indexOf(Buffer.from('d', 'latin1'), 0, 'latin1'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('aa\u00e8aa', 'latin1')) |
||||
|
.indexOf('\u00e8', 'latin1'), |
||||
|
2 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('\u00e8', 'latin1')) |
||||
|
.indexOf('\u00e8', 'latin1'), |
||||
|
0 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('\u00e8', 'latin1')) |
||||
|
.indexOf(Buffer.from('\u00e8', 'latin1'), 'latin1'), |
||||
|
0 |
||||
|
) |
||||
|
|
||||
|
// test binary encoding
|
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from(b.toString('binary'), 'binary')) |
||||
|
.indexOf('d', 0, 'binary'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from(b.toString('binary'), 'binary')) |
||||
|
.indexOf(Buffer.from('d', 'binary'), 0, 'binary'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('aa\u00e8aa', 'binary')) |
||||
|
.indexOf('\u00e8', 'binary'), |
||||
|
2 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('\u00e8', 'binary')) |
||||
|
.indexOf('\u00e8', 'binary'), |
||||
|
0 |
||||
|
) |
||||
|
t.equal( |
||||
|
new BufferList(Buffer.from('\u00e8', 'binary')) |
||||
|
.indexOf(Buffer.from('\u00e8', 'binary'), 'binary'), |
||||
|
0 |
||||
|
) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('indexOf the entire nodejs10 buffer test suite', t => { |
||||
|
const b = new BufferList('abcdef') |
||||
|
const buf_a = Buffer.from('a') |
||||
|
const buf_bc = Buffer.from('bc') |
||||
|
const buf_f = Buffer.from('f') |
||||
|
const buf_z = Buffer.from('z') |
||||
|
|
||||
|
const stringComparison = 'abcdef' |
||||
|
|
||||
|
t.equal(b.indexOf('a'), 0) |
||||
|
t.equal(b.indexOf('a', 1), -1) |
||||
|
t.equal(b.indexOf('a', -1), -1) |
||||
|
t.equal(b.indexOf('a', -4), -1) |
||||
|
t.equal(b.indexOf('a', -b.length), 0) |
||||
|
t.equal(b.indexOf('a', NaN), 0) |
||||
|
t.equal(b.indexOf('a', -Infinity), 0) |
||||
|
t.equal(b.indexOf('a', Infinity), -1) |
||||
|
t.equal(b.indexOf('bc'), 1) |
||||
|
t.equal(b.indexOf('bc', 2), -1) |
||||
|
t.equal(b.indexOf('bc', -1), -1) |
||||
|
t.equal(b.indexOf('bc', -3), -1) |
||||
|
t.equal(b.indexOf('bc', -5), 1) |
||||
|
t.equal(b.indexOf('bc', NaN), 1) |
||||
|
t.equal(b.indexOf('bc', -Infinity), 1) |
||||
|
t.equal(b.indexOf('bc', Infinity), -1) |
||||
|
t.equal(b.indexOf('f'), b.length - 1) |
||||
|
t.equal(b.indexOf('z'), -1) |
||||
|
// empty search tests
|
||||
|
t.equal(b.indexOf(buf_a), 0) |
||||
|
t.equal(b.indexOf(buf_a, 1), -1) |
||||
|
t.equal(b.indexOf(buf_a, -1), -1) |
||||
|
t.equal(b.indexOf(buf_a, -4), -1) |
||||
|
t.equal(b.indexOf(buf_a, -b.length), 0) |
||||
|
t.equal(b.indexOf(buf_a, NaN), 0) |
||||
|
t.equal(b.indexOf(buf_a, -Infinity), 0) |
||||
|
t.equal(b.indexOf(buf_a, Infinity), -1) |
||||
|
t.equal(b.indexOf(buf_bc), 1) |
||||
|
t.equal(b.indexOf(buf_bc, 2), -1) |
||||
|
t.equal(b.indexOf(buf_bc, -1), -1) |
||||
|
t.equal(b.indexOf(buf_bc, -3), -1) |
||||
|
t.equal(b.indexOf(buf_bc, -5), 1) |
||||
|
t.equal(b.indexOf(buf_bc, NaN), 1) |
||||
|
t.equal(b.indexOf(buf_bc, -Infinity), 1) |
||||
|
t.equal(b.indexOf(buf_bc, Infinity), -1) |
||||
|
t.equal(b.indexOf(buf_f), b.length - 1) |
||||
|
t.equal(b.indexOf(buf_z), -1) |
||||
|
t.equal(b.indexOf(0x61), 0) |
||||
|
t.equal(b.indexOf(0x61, 1), -1) |
||||
|
t.equal(b.indexOf(0x61, -1), -1) |
||||
|
t.equal(b.indexOf(0x61, -4), -1) |
||||
|
t.equal(b.indexOf(0x61, -b.length), 0) |
||||
|
t.equal(b.indexOf(0x61, NaN), 0) |
||||
|
t.equal(b.indexOf(0x61, -Infinity), 0) |
||||
|
t.equal(b.indexOf(0x61, Infinity), -1) |
||||
|
t.equal(b.indexOf(0x0), -1) |
||||
|
|
||||
|
// test offsets
|
||||
|
t.equal(b.indexOf('d', 2), 3) |
||||
|
t.equal(b.indexOf('f', 5), 5) |
||||
|
t.equal(b.indexOf('f', -1), 5) |
||||
|
t.equal(b.indexOf('f', 6), -1) |
||||
|
|
||||
|
t.equal(b.indexOf(Buffer.from('d'), 2), 3) |
||||
|
t.equal(b.indexOf(Buffer.from('f'), 5), 5) |
||||
|
t.equal(b.indexOf(Buffer.from('f'), -1), 5) |
||||
|
t.equal(b.indexOf(Buffer.from('f'), 6), -1) |
||||
|
|
||||
|
t.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1) |
||||
|
|
||||
|
// test invalid and uppercase encoding
|
||||
|
t.equal(b.indexOf('b', 'utf8'), 1) |
||||
|
t.equal(b.indexOf('b', 'UTF8'), 1) |
||||
|
t.equal(b.indexOf('62', 'HEX'), 1) |
||||
|
t.throws(() => b.indexOf('bad', 'enc'), TypeError) |
||||
|
|
||||
|
// test hex encoding
|
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('hex'), 'hex') |
||||
|
.indexOf('64', 0, 'hex'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('hex'), 'hex') |
||||
|
.indexOf(Buffer.from('64', 'hex'), 0, 'hex'), |
||||
|
3 |
||||
|
) |
||||
|
|
||||
|
// test base64 encoding
|
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('base64'), 'base64') |
||||
|
.indexOf('ZA==', 0, 'base64'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('base64'), 'base64') |
||||
|
.indexOf(Buffer.from('ZA==', 'base64'), 0, 'base64'), |
||||
|
3 |
||||
|
) |
||||
|
|
||||
|
// test ascii encoding
|
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('ascii'), 'ascii') |
||||
|
.indexOf('d', 0, 'ascii'), |
||||
|
3 |
||||
|
) |
||||
|
t.equal( |
||||
|
Buffer.from(b.toString('ascii'), 'ascii') |
||||
|
.indexOf(Buffer.from('d', 'ascii'), 0, 'ascii'), |
||||
|
3 |
||||
|
) |
||||
|
|
||||
|
// test optional offset with passed encoding
|
||||
|
t.equal(Buffer.from('aaaa0').indexOf('30', 'hex'), 4) |
||||
|
t.equal(Buffer.from('aaaa00a').indexOf('3030', 'hex'), 4) |
||||
|
|
||||
|
{ |
||||
|
// test usc2 encoding
|
||||
|
const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') |
||||
|
|
||||
|
t.equal(8, twoByteString.indexOf('\u0395', 4, 'ucs2')) |
||||
|
t.equal(6, twoByteString.indexOf('\u03a3', -4, 'ucs2')) |
||||
|
t.equal(4, twoByteString.indexOf('\u03a3', -6, 'ucs2')) |
||||
|
t.equal(4, twoByteString.indexOf( |
||||
|
Buffer.from('\u03a3', 'ucs2'), -6, 'ucs2')) |
||||
|
t.equal(-1, twoByteString.indexOf('\u03a3', -2, 'ucs2')) |
||||
|
} |
||||
|
|
||||
|
const mixedByteStringUcs2 = |
||||
|
Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395', 'ucs2') |
||||
|
t.equal(6, mixedByteStringUcs2.indexOf('bc', 0, 'ucs2')) |
||||
|
t.equal(10, mixedByteStringUcs2.indexOf('\u03a3', 0, 'ucs2')) |
||||
|
t.equal(-1, mixedByteStringUcs2.indexOf('\u0396', 0, 'ucs2')) |
||||
|
|
||||
|
t.equal( |
||||
|
6, mixedByteStringUcs2.indexOf(Buffer.from('bc', 'ucs2'), 0, 'ucs2')) |
||||
|
t.equal( |
||||
|
10, mixedByteStringUcs2.indexOf(Buffer.from('\u03a3', 'ucs2'), 0, 'ucs2')) |
||||
|
t.equal( |
||||
|
-1, mixedByteStringUcs2.indexOf(Buffer.from('\u0396', 'ucs2'), 0, 'ucs2')) |
||||
|
|
||||
|
{ |
||||
|
const twoByteString = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2') |
||||
|
|
||||
|
// Test single char pattern
|
||||
|
t.equal(0, twoByteString.indexOf('\u039a', 0, 'ucs2')) |
||||
|
let index = twoByteString.indexOf('\u0391', 0, 'ucs2') |
||||
|
t.equal(2, index, `Alpha - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u03a3', 0, 'ucs2') |
||||
|
t.equal(4, index, `First Sigma - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u03a3', 6, 'ucs2') |
||||
|
t.equal(6, index, `Second Sigma - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u0395', 0, 'ucs2') |
||||
|
t.equal(8, index, `Epsilon - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u0392', 0, 'ucs2') |
||||
|
t.equal(-1, index, `Not beta - at index ${index}`) |
||||
|
|
||||
|
// Test multi-char pattern
|
||||
|
index = twoByteString.indexOf('\u039a\u0391', 0, 'ucs2') |
||||
|
t.equal(0, index, `Lambda Alpha - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u0391\u03a3', 0, 'ucs2') |
||||
|
t.equal(2, index, `Alpha Sigma - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u03a3\u03a3', 0, 'ucs2') |
||||
|
t.equal(4, index, `Sigma Sigma - at index ${index}`) |
||||
|
index = twoByteString.indexOf('\u03a3\u0395', 0, 'ucs2') |
||||
|
t.equal(6, index, `Sigma Epsilon - at index ${index}`) |
||||
|
} |
||||
|
|
||||
|
const mixedByteStringUtf8 = Buffer.from('\u039a\u0391abc\u03a3\u03a3\u0395') |
||||
|
t.equal(5, mixedByteStringUtf8.indexOf('bc')) |
||||
|
t.equal(5, mixedByteStringUtf8.indexOf('bc', 5)) |
||||
|
t.equal(5, mixedByteStringUtf8.indexOf('bc', -8)) |
||||
|
t.equal(7, mixedByteStringUtf8.indexOf('\u03a3')) |
||||
|
t.equal(-1, mixedByteStringUtf8.indexOf('\u0396')) |
||||
|
|
||||
|
|
||||
|
// Test complex string indexOf algorithms. Only trigger for long strings.
|
||||
|
// Long string that isn't a simple repeat of a shorter string.
|
||||
|
let longString = 'A' |
||||
|
for (let i = 66; i < 76; i++) { // from 'B' to 'K'
|
||||
|
longString = longString + String.fromCharCode(i) + longString |
||||
|
} |
||||
|
|
||||
|
const longBufferString = Buffer.from(longString) |
||||
|
|
||||
|
// pattern of 15 chars, repeated every 16 chars in long
|
||||
|
let pattern = 'ABACABADABACABA' |
||||
|
for (let i = 0; i < longBufferString.length - pattern.length; i += 7) { |
||||
|
const index = longBufferString.indexOf(pattern, i) |
||||
|
t.equal((i + 15) & ~0xf, index, |
||||
|
`Long ABACABA...-string at index ${i}`) |
||||
|
} |
||||
|
|
||||
|
let index = longBufferString.indexOf('AJABACA') |
||||
|
t.equal(510, index, `Long AJABACA, First J - at index ${index}`) |
||||
|
index = longBufferString.indexOf('AJABACA', 511) |
||||
|
t.equal(1534, index, `Long AJABACA, Second J - at index ${index}`) |
||||
|
|
||||
|
pattern = 'JABACABADABACABA' |
||||
|
index = longBufferString.indexOf(pattern) |
||||
|
t.equal(511, index, `Long JABACABA..., First J - at index ${index}`) |
||||
|
index = longBufferString.indexOf(pattern, 512) |
||||
|
t.equal( |
||||
|
1535, index, `Long JABACABA..., Second J - at index ${index}`) |
||||
|
|
||||
|
// Search for a non-ASCII string in a pure ASCII string.
|
||||
|
const asciiString = Buffer.from( |
||||
|
'arglebargleglopglyfarglebargleglopglyfarglebargleglopglyf') |
||||
|
t.equal(-1, asciiString.indexOf('\x2061')) |
||||
|
t.equal(3, asciiString.indexOf('leb', 0)) |
||||
|
|
||||
|
// Search in string containing many non-ASCII chars.
|
||||
|
const allCodePoints = [] |
||||
|
for (let i = 0; i < 65536; i++) allCodePoints[i] = i |
||||
|
const allCharsString = String.fromCharCode.apply(String, allCodePoints) |
||||
|
const allCharsBufferUtf8 = Buffer.from(allCharsString) |
||||
|
const allCharsBufferUcs2 = Buffer.from(allCharsString, 'ucs2') |
||||
|
|
||||
|
// Search for string long enough to trigger complex search with ASCII pattern
|
||||
|
// and UC16 subject.
|
||||
|
t.equal(-1, allCharsBufferUtf8.indexOf('notfound')) |
||||
|
t.equal(-1, allCharsBufferUcs2.indexOf('notfound')) |
||||
|
|
||||
|
// Needle is longer than haystack, but only because it's encoded as UTF-16
|
||||
|
t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'ucs2'), -1) |
||||
|
|
||||
|
t.equal(Buffer.from('aaaa').indexOf('a'.repeat(4), 'utf8'), 0) |
||||
|
t.equal(Buffer.from('aaaa').indexOf('你好', 'ucs2'), -1) |
||||
|
|
||||
|
// Haystack has odd length, but the needle is UCS2.
|
||||
|
t.equal(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1) |
||||
|
|
||||
|
{ |
||||
|
// Find substrings in Utf8.
|
||||
|
const lengths = [1, 3, 15]; // Single char, simple and complex.
|
||||
|
const indices = [0x5, 0x60, 0x400, 0x680, 0x7ee, 0xFF02, 0x16610, 0x2f77b] |
||||
|
for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { |
||||
|
for (let i = 0; i < indices.length; i++) { |
||||
|
const index = indices[i] |
||||
|
let length = lengths[lengthIndex] |
||||
|
|
||||
|
if (index + length > 0x7F) { |
||||
|
length = 2 * length |
||||
|
} |
||||
|
|
||||
|
if (index + length > 0x7FF) { |
||||
|
length = 3 * length |
||||
|
} |
||||
|
|
||||
|
if (index + length > 0xFFFF) { |
||||
|
length = 4 * length |
||||
|
} |
||||
|
|
||||
|
const patternBufferUtf8 = allCharsBufferUtf8.slice(index, index + length) |
||||
|
t.equal(index, allCharsBufferUtf8.indexOf(patternBufferUtf8)) |
||||
|
|
||||
|
const patternStringUtf8 = patternBufferUtf8.toString() |
||||
|
t.equal(index, allCharsBufferUtf8.indexOf(patternStringUtf8)) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
{ |
||||
|
// Find substrings in Usc2.
|
||||
|
const lengths = [2, 4, 16]; // Single char, simple and complex.
|
||||
|
const indices = [0x5, 0x65, 0x105, 0x205, 0x285, 0x2005, 0x2085, 0xfff0] |
||||
|
for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) { |
||||
|
for (let i = 0; i < indices.length; i++) { |
||||
|
const index = indices[i] * 2 |
||||
|
const length = lengths[lengthIndex] |
||||
|
|
||||
|
const patternBufferUcs2 = |
||||
|
allCharsBufferUcs2.slice(index, index + length) |
||||
|
t.equal( |
||||
|
index, allCharsBufferUcs2.indexOf(patternBufferUcs2, 0, 'ucs2')) |
||||
|
|
||||
|
const patternStringUcs2 = patternBufferUcs2.toString('ucs2') |
||||
|
t.equal( |
||||
|
index, allCharsBufferUcs2.indexOf(patternStringUcs2, 0, 'ucs2')) |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
[ |
||||
|
() => {}, |
||||
|
{}, |
||||
|
[] |
||||
|
].forEach(val => { |
||||
|
debugger |
||||
|
t.throws(() => b.indexOf(val), TypeError, `"${JSON.stringify(val)}" should throw`) |
||||
|
}) |
||||
|
|
||||
|
// Test weird offset arguments.
|
||||
|
// The following offsets coerce to NaN or 0, searching the whole Buffer
|
||||
|
t.equal(b.indexOf('b', undefined), 1) |
||||
|
t.equal(b.indexOf('b', {}), 1) |
||||
|
t.equal(b.indexOf('b', 0), 1) |
||||
|
t.equal(b.indexOf('b', null), 1) |
||||
|
t.equal(b.indexOf('b', []), 1) |
||||
|
|
||||
|
// The following offset coerces to 2, in other words +[2] === 2
|
||||
|
t.equal(b.indexOf('b', [2]), -1) |
||||
|
|
||||
|
// Behavior should match String.indexOf()
|
||||
|
t.equal( |
||||
|
b.indexOf('b', undefined), |
||||
|
stringComparison.indexOf('b', undefined)) |
||||
|
t.equal( |
||||
|
b.indexOf('b', {}), |
||||
|
stringComparison.indexOf('b', {})) |
||||
|
t.equal( |
||||
|
b.indexOf('b', 0), |
||||
|
stringComparison.indexOf('b', 0)) |
||||
|
t.equal( |
||||
|
b.indexOf('b', null), |
||||
|
stringComparison.indexOf('b', null)) |
||||
|
t.equal( |
||||
|
b.indexOf('b', []), |
||||
|
stringComparison.indexOf('b', [])) |
||||
|
t.equal( |
||||
|
b.indexOf('b', [2]), |
||||
|
stringComparison.indexOf('b', [2])) |
||||
|
|
||||
|
// test truncation of Number arguments to uint8
|
||||
|
{ |
||||
|
const buf = Buffer.from('this is a test') |
||||
|
t.equal(buf.indexOf(0x6973), 3) |
||||
|
t.equal(buf.indexOf(0x697320), 4) |
||||
|
t.equal(buf.indexOf(0x69732069), 2) |
||||
|
t.equal(buf.indexOf(0x697374657374), 0) |
||||
|
t.equal(buf.indexOf(0x69737374), 0) |
||||
|
t.equal(buf.indexOf(0x69737465), 11) |
||||
|
t.equal(buf.indexOf(0x69737465), 11) |
||||
|
t.equal(buf.indexOf(-140), 0) |
||||
|
t.equal(buf.indexOf(-152), 1) |
||||
|
t.equal(buf.indexOf(0xff), -1) |
||||
|
t.equal(buf.indexOf(0xffff), -1) |
||||
|
} |
||||
|
|
||||
|
// Test that Uint8Array arguments are okay.
|
||||
|
{ |
||||
|
const needle = new Uint8Array([ 0x66, 0x6f, 0x6f ]) |
||||
|
const haystack = new BufferList(Buffer.from('a foo b foo')) |
||||
|
t.equal(haystack.indexOf(needle), 2) |
||||
|
} |
||||
|
t.end() |
||||
|
}) |
@ -0,0 +1,766 @@ |
|||||
|
'use strict' |
||||
|
|
||||
|
var tape = require('tape') |
||||
|
, crypto = require('crypto') |
||||
|
, fs = require('fs') |
||||
|
, hash = require('hash_file') |
||||
|
, BufferList = require('../') |
||||
|
, Buffer = require('safe-buffer').Buffer |
||||
|
|
||||
|
, encodings = |
||||
|
('hex utf8 utf-8 ascii binary base64' |
||||
|
+ (process.browser ? '' : ' ucs2 ucs-2 utf16le utf-16le')).split(' ') |
||||
|
|
||||
|
// run the indexOf tests
|
||||
|
require('./indexOf') |
||||
|
|
||||
|
tape('single bytes from single buffer', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
|
||||
|
t.equal(bl.length, 4) |
||||
|
t.equal(bl.get(-1), undefined) |
||||
|
t.equal(bl.get(0), 97) |
||||
|
t.equal(bl.get(1), 98) |
||||
|
t.equal(bl.get(2), 99) |
||||
|
t.equal(bl.get(3), 100) |
||||
|
t.equal(bl.get(4), undefined) |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('single bytes from multiple buffers', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
|
||||
|
t.equal(bl.length, 10) |
||||
|
|
||||
|
t.equal(bl.get(0), 97) |
||||
|
t.equal(bl.get(1), 98) |
||||
|
t.equal(bl.get(2), 99) |
||||
|
t.equal(bl.get(3), 100) |
||||
|
t.equal(bl.get(4), 101) |
||||
|
t.equal(bl.get(5), 102) |
||||
|
t.equal(bl.get(6), 103) |
||||
|
t.equal(bl.get(7), 104) |
||||
|
t.equal(bl.get(8), 105) |
||||
|
t.equal(bl.get(9), 106) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('multi bytes from single buffer', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
|
||||
|
t.equal(bl.length, 4) |
||||
|
|
||||
|
t.equal(bl.slice(0, 4).toString('ascii'), 'abcd') |
||||
|
t.equal(bl.slice(0, 3).toString('ascii'), 'abc') |
||||
|
t.equal(bl.slice(1, 4).toString('ascii'), 'bcd') |
||||
|
t.equal(bl.slice(-4, -1).toString('ascii'), 'abc') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('multi bytes from single buffer (negative indexes)', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('buffer')) |
||||
|
|
||||
|
t.equal(bl.length, 6) |
||||
|
|
||||
|
t.equal(bl.slice(-6, -1).toString('ascii'), 'buffe') |
||||
|
t.equal(bl.slice(-6, -2).toString('ascii'), 'buff') |
||||
|
t.equal(bl.slice(-5, -2).toString('ascii'), 'uff') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('multiple bytes from multiple buffers', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
|
||||
|
t.equal(bl.length, 10) |
||||
|
|
||||
|
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') |
||||
|
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') |
||||
|
t.equal(bl.slice(3, 6).toString('ascii'), 'def') |
||||
|
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') |
||||
|
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') |
||||
|
t.equal(bl.slice(-7, -4).toString('ascii'), 'def') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('multiple bytes from multiple buffer lists', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(new BufferList([ Buffer.from('abcd'), Buffer.from('efg') ])) |
||||
|
bl.append(new BufferList([ Buffer.from('hi'), Buffer.from('j') ])) |
||||
|
|
||||
|
t.equal(bl.length, 10) |
||||
|
|
||||
|
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') |
||||
|
|
||||
|
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') |
||||
|
t.equal(bl.slice(3, 6).toString('ascii'), 'def') |
||||
|
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') |
||||
|
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
// same data as previous test, just using nested constructors
|
||||
|
tape('multiple bytes from crazy nested buffer lists', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(new BufferList([ |
||||
|
new BufferList([ |
||||
|
new BufferList(Buffer.from('abc')) |
||||
|
, Buffer.from('d') |
||||
|
, new BufferList(Buffer.from('efg')) |
||||
|
]) |
||||
|
, new BufferList([ Buffer.from('hi') ]) |
||||
|
, new BufferList(Buffer.from('j')) |
||||
|
])) |
||||
|
|
||||
|
t.equal(bl.length, 10) |
||||
|
|
||||
|
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') |
||||
|
|
||||
|
t.equal(bl.slice(3, 10).toString('ascii'), 'defghij') |
||||
|
t.equal(bl.slice(3, 6).toString('ascii'), 'def') |
||||
|
t.equal(bl.slice(3, 8).toString('ascii'), 'defgh') |
||||
|
t.equal(bl.slice(5, 10).toString('ascii'), 'fghij') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('append accepts arrays of Buffers', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abc')) |
||||
|
bl.append([ Buffer.from('def') ]) |
||||
|
bl.append([ Buffer.from('ghi'), Buffer.from('jkl') ]) |
||||
|
bl.append([ Buffer.from('mnop'), Buffer.from('qrstu'), Buffer.from('vwxyz') ]) |
||||
|
t.equal(bl.length, 26) |
||||
|
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('append accepts arrays of BufferLists', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
bl.append(Buffer.from('abc')) |
||||
|
bl.append([ new BufferList('def') ]) |
||||
|
bl.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) |
||||
|
bl.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) |
||||
|
t.equal(bl.length, 26) |
||||
|
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('append chainable', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
t.ok(bl.append(Buffer.from('abcd')) === bl) |
||||
|
t.ok(bl.append([ Buffer.from('abcd') ]) === bl) |
||||
|
t.ok(bl.append(new BufferList(Buffer.from('abcd'))) === bl) |
||||
|
t.ok(bl.append([ new BufferList(Buffer.from('abcd')) ]) === bl) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('append chainable (test results)', function (t) { |
||||
|
var bl = new BufferList('abc') |
||||
|
.append([ new BufferList('def') ]) |
||||
|
.append(new BufferList([ Buffer.from('ghi'), new BufferList('jkl') ])) |
||||
|
.append([ Buffer.from('mnop'), new BufferList([ Buffer.from('qrstu'), Buffer.from('vwxyz') ]) ]) |
||||
|
|
||||
|
t.equal(bl.length, 26) |
||||
|
t.equal(bl.slice().toString('ascii'), 'abcdefghijklmnopqrstuvwxyz') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('consuming from multiple buffers', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
|
||||
|
t.equal(bl.length, 10) |
||||
|
|
||||
|
t.equal(bl.slice(0, 10).toString('ascii'), 'abcdefghij') |
||||
|
|
||||
|
bl.consume(3) |
||||
|
t.equal(bl.length, 7) |
||||
|
t.equal(bl.slice(0, 7).toString('ascii'), 'defghij') |
||||
|
|
||||
|
bl.consume(2) |
||||
|
t.equal(bl.length, 5) |
||||
|
t.equal(bl.slice(0, 5).toString('ascii'), 'fghij') |
||||
|
|
||||
|
bl.consume(1) |
||||
|
t.equal(bl.length, 4) |
||||
|
t.equal(bl.slice(0, 4).toString('ascii'), 'ghij') |
||||
|
|
||||
|
bl.consume(1) |
||||
|
t.equal(bl.length, 3) |
||||
|
t.equal(bl.slice(0, 3).toString('ascii'), 'hij') |
||||
|
|
||||
|
bl.consume(2) |
||||
|
t.equal(bl.length, 1) |
||||
|
t.equal(bl.slice(0, 1).toString('ascii'), 'j') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('complete consumption', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(Buffer.from('a')) |
||||
|
bl.append(Buffer.from('b')) |
||||
|
|
||||
|
bl.consume(2) |
||||
|
|
||||
|
t.equal(bl.length, 0) |
||||
|
t.equal(bl._bufs.length, 0) |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readUInt8 / readInt8', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(3) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[1] = 0x3 |
||||
|
buf2[2] = 0x4 |
||||
|
buf3[0] = 0x23 |
||||
|
buf3[1] = 0x42 |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readUInt8(2), 0x3) |
||||
|
t.equal(bl.readInt8(2), 0x3) |
||||
|
t.equal(bl.readUInt8(3), 0x4) |
||||
|
t.equal(bl.readInt8(3), 0x4) |
||||
|
t.equal(bl.readUInt8(4), 0x23) |
||||
|
t.equal(bl.readInt8(4), 0x23) |
||||
|
t.equal(bl.readUInt8(5), 0x42) |
||||
|
t.equal(bl.readInt8(5), 0x42) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readUInt16LE / readUInt16BE / readInt16LE / readInt16BE', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(3) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[1] = 0x3 |
||||
|
buf2[2] = 0x4 |
||||
|
buf3[0] = 0x23 |
||||
|
buf3[1] = 0x42 |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readUInt16BE(2), 0x0304) |
||||
|
t.equal(bl.readUInt16LE(2), 0x0403) |
||||
|
t.equal(bl.readInt16BE(2), 0x0304) |
||||
|
t.equal(bl.readInt16LE(2), 0x0403) |
||||
|
t.equal(bl.readUInt16BE(3), 0x0423) |
||||
|
t.equal(bl.readUInt16LE(3), 0x2304) |
||||
|
t.equal(bl.readInt16BE(3), 0x0423) |
||||
|
t.equal(bl.readInt16LE(3), 0x2304) |
||||
|
t.equal(bl.readUInt16BE(4), 0x2342) |
||||
|
t.equal(bl.readUInt16LE(4), 0x4223) |
||||
|
t.equal(bl.readInt16BE(4), 0x2342) |
||||
|
t.equal(bl.readInt16LE(4), 0x4223) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readUInt32LE / readUInt32BE / readInt32LE / readInt32BE', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(3) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[1] = 0x3 |
||||
|
buf2[2] = 0x4 |
||||
|
buf3[0] = 0x23 |
||||
|
buf3[1] = 0x42 |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readUInt32BE(2), 0x03042342) |
||||
|
t.equal(bl.readUInt32LE(2), 0x42230403) |
||||
|
t.equal(bl.readInt32BE(2), 0x03042342) |
||||
|
t.equal(bl.readInt32LE(2), 0x42230403) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readUIntLE / readUIntBE / readIntLE / readIntBE', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(3) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[0] = 0x2 |
||||
|
buf2[1] = 0x3 |
||||
|
buf2[2] = 0x4 |
||||
|
buf3[0] = 0x23 |
||||
|
buf3[1] = 0x42 |
||||
|
buf3[2] = 0x61 |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readUIntBE(1, 1), 0x02) |
||||
|
t.equal(bl.readUIntBE(1, 2), 0x0203) |
||||
|
t.equal(bl.readUIntBE(1, 3), 0x020304) |
||||
|
t.equal(bl.readUIntBE(1, 4), 0x02030423) |
||||
|
t.equal(bl.readUIntBE(1, 5), 0x0203042342) |
||||
|
t.equal(bl.readUIntBE(1, 6), 0x020304234261) |
||||
|
t.equal(bl.readUIntLE(1, 1), 0x02) |
||||
|
t.equal(bl.readUIntLE(1, 2), 0x0302) |
||||
|
t.equal(bl.readUIntLE(1, 3), 0x040302) |
||||
|
t.equal(bl.readUIntLE(1, 4), 0x23040302) |
||||
|
t.equal(bl.readUIntLE(1, 5), 0x4223040302) |
||||
|
t.equal(bl.readUIntLE(1, 6), 0x614223040302) |
||||
|
t.equal(bl.readIntBE(1, 1), 0x02) |
||||
|
t.equal(bl.readIntBE(1, 2), 0x0203) |
||||
|
t.equal(bl.readIntBE(1, 3), 0x020304) |
||||
|
t.equal(bl.readIntBE(1, 4), 0x02030423) |
||||
|
t.equal(bl.readIntBE(1, 5), 0x0203042342) |
||||
|
t.equal(bl.readIntBE(1, 6), 0x020304234261) |
||||
|
t.equal(bl.readIntLE(1, 1), 0x02) |
||||
|
t.equal(bl.readIntLE(1, 2), 0x0302) |
||||
|
t.equal(bl.readIntLE(1, 3), 0x040302) |
||||
|
t.equal(bl.readIntLE(1, 4), 0x23040302) |
||||
|
t.equal(bl.readIntLE(1, 5), 0x4223040302) |
||||
|
t.equal(bl.readIntLE(1, 6), 0x614223040302) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readFloatLE / readFloatBE', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(3) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[1] = 0x00 |
||||
|
buf2[2] = 0x00 |
||||
|
buf3[0] = 0x80 |
||||
|
buf3[1] = 0x3f |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readFloatLE(2), 0x01) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test readDoubleLE / readDoubleBE', function (t) { |
||||
|
var buf1 = Buffer.alloc(1) |
||||
|
, buf2 = Buffer.alloc(3) |
||||
|
, buf3 = Buffer.alloc(10) |
||||
|
, bl = new BufferList() |
||||
|
|
||||
|
buf2[1] = 0x55 |
||||
|
buf2[2] = 0x55 |
||||
|
buf3[0] = 0x55 |
||||
|
buf3[1] = 0x55 |
||||
|
buf3[2] = 0x55 |
||||
|
buf3[3] = 0x55 |
||||
|
buf3[4] = 0xd5 |
||||
|
buf3[5] = 0x3f |
||||
|
|
||||
|
bl.append(buf1) |
||||
|
bl.append(buf2) |
||||
|
bl.append(buf3) |
||||
|
|
||||
|
t.equal(bl.readDoubleLE(2), 0.3333333333333333) |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test toString', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
|
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
|
||||
|
t.equal(bl.toString('ascii', 0, 10), 'abcdefghij') |
||||
|
t.equal(bl.toString('ascii', 3, 10), 'defghij') |
||||
|
t.equal(bl.toString('ascii', 3, 6), 'def') |
||||
|
t.equal(bl.toString('ascii', 3, 8), 'defgh') |
||||
|
t.equal(bl.toString('ascii', 5, 10), 'fghij') |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test toString encoding', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
, b = Buffer.from('abcdefghij\xff\x00') |
||||
|
|
||||
|
bl.append(Buffer.from('abcd')) |
||||
|
bl.append(Buffer.from('efg')) |
||||
|
bl.append(Buffer.from('hi')) |
||||
|
bl.append(Buffer.from('j')) |
||||
|
bl.append(Buffer.from('\xff\x00')) |
||||
|
|
||||
|
encodings.forEach(function (enc) { |
||||
|
t.equal(bl.toString(enc), b.toString(enc), enc) |
||||
|
}) |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('test stream', function (t) { |
||||
|
var random = crypto.randomBytes(65534) |
||||
|
, rndhash = hash(random, 'md5') |
||||
|
, md5sum = crypto.createHash('md5') |
||||
|
, bl = new BufferList(function (err, buf) { |
||||
|
t.ok(Buffer.isBuffer(buf)) |
||||
|
t.ok(err === null) |
||||
|
t.equal(rndhash, hash(bl.slice(), 'md5')) |
||||
|
t.equal(rndhash, hash(buf, 'md5')) |
||||
|
|
||||
|
bl.pipe(fs.createWriteStream('/tmp/bl_test_rnd_out.dat')) |
||||
|
.on('close', function () { |
||||
|
var s = fs.createReadStream('/tmp/bl_test_rnd_out.dat') |
||||
|
s.on('data', md5sum.update.bind(md5sum)) |
||||
|
s.on('end', function() { |
||||
|
t.equal(rndhash, md5sum.digest('hex'), 'woohoo! correct hash!') |
||||
|
t.end() |
||||
|
}) |
||||
|
}) |
||||
|
|
||||
|
}) |
||||
|
|
||||
|
fs.writeFileSync('/tmp/bl_test_rnd.dat', random) |
||||
|
fs.createReadStream('/tmp/bl_test_rnd.dat').pipe(bl) |
||||
|
}) |
||||
|
|
||||
|
tape('instantiation with Buffer', function (t) { |
||||
|
var buf = crypto.randomBytes(1024) |
||||
|
, buf2 = crypto.randomBytes(1024) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
t.equal(buf.toString('hex'), b.slice().toString('hex'), 'same buffer') |
||||
|
b = BufferList([ buf, buf2 ]) |
||||
|
t.equal(b.slice().toString('hex'), Buffer.concat([ buf, buf2 ]).toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test String appendage', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
, b = Buffer.from('abcdefghij\xff\x00') |
||||
|
|
||||
|
bl.append('abcd') |
||||
|
bl.append('efg') |
||||
|
bl.append('hi') |
||||
|
bl.append('j') |
||||
|
bl.append('\xff\x00') |
||||
|
|
||||
|
encodings.forEach(function (enc) { |
||||
|
t.equal(bl.toString(enc), b.toString(enc)) |
||||
|
}) |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('test Number appendage', function (t) { |
||||
|
var bl = new BufferList() |
||||
|
, b = Buffer.from('1234567890') |
||||
|
|
||||
|
bl.append(1234) |
||||
|
bl.append(567) |
||||
|
bl.append(89) |
||||
|
bl.append(0) |
||||
|
|
||||
|
encodings.forEach(function (enc) { |
||||
|
t.equal(bl.toString(enc), b.toString(enc)) |
||||
|
}) |
||||
|
|
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('write nothing, should get empty buffer', function (t) { |
||||
|
t.plan(3) |
||||
|
BufferList(function (err, data) { |
||||
|
t.notOk(err, 'no error') |
||||
|
t.ok(Buffer.isBuffer(data), 'got a buffer') |
||||
|
t.equal(0, data.length, 'got a zero-length buffer') |
||||
|
t.end() |
||||
|
}).end() |
||||
|
}) |
||||
|
|
||||
|
tape('unicode string', function (t) { |
||||
|
t.plan(2) |
||||
|
var inp1 = '\u2600' |
||||
|
, inp2 = '\u2603' |
||||
|
, exp = inp1 + ' and ' + inp2 |
||||
|
, bl = BufferList() |
||||
|
bl.write(inp1) |
||||
|
bl.write(' and ') |
||||
|
bl.write(inp2) |
||||
|
t.equal(exp, bl.toString()) |
||||
|
t.equal(Buffer.from(exp).toString('hex'), bl.toString('hex')) |
||||
|
}) |
||||
|
|
||||
|
tape('should emit finish', function (t) { |
||||
|
var source = BufferList() |
||||
|
, dest = BufferList() |
||||
|
|
||||
|
source.write('hello') |
||||
|
source.pipe(dest) |
||||
|
|
||||
|
dest.on('finish', function () { |
||||
|
t.equal(dest.toString('utf8'), 'hello') |
||||
|
t.end() |
||||
|
}) |
||||
|
}) |
||||
|
|
||||
|
tape('basic copy', function (t) { |
||||
|
var buf = crypto.randomBytes(1024) |
||||
|
, buf2 = Buffer.alloc(1024) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
b.copy(buf2) |
||||
|
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('copy after many appends', function (t) { |
||||
|
var buf = crypto.randomBytes(512) |
||||
|
, buf2 = Buffer.alloc(1024) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
b.append(buf) |
||||
|
b.copy(buf2) |
||||
|
t.equal(b.slice().toString('hex'), buf2.toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('copy at a precise position', function (t) { |
||||
|
var buf = crypto.randomBytes(1004) |
||||
|
, buf2 = Buffer.alloc(1024) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
b.copy(buf2, 20) |
||||
|
t.equal(b.slice().toString('hex'), buf2.slice(20).toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('copy starting from a precise location', function (t) { |
||||
|
var buf = crypto.randomBytes(10) |
||||
|
, buf2 = Buffer.alloc(5) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
b.copy(buf2, 0, 5) |
||||
|
t.equal(b.slice(5).toString('hex'), buf2.toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('copy in an interval', function (t) { |
||||
|
var rnd = crypto.randomBytes(10) |
||||
|
, b = BufferList(rnd) // put the random bytes there
|
||||
|
, actual = Buffer.alloc(3) |
||||
|
, expected = Buffer.alloc(3) |
||||
|
|
||||
|
rnd.copy(expected, 0, 5, 8) |
||||
|
b.copy(actual, 0, 5, 8) |
||||
|
|
||||
|
t.equal(actual.toString('hex'), expected.toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('copy an interval between two buffers', function (t) { |
||||
|
var buf = crypto.randomBytes(10) |
||||
|
, buf2 = Buffer.alloc(10) |
||||
|
, b = BufferList(buf) |
||||
|
|
||||
|
b.append(buf) |
||||
|
b.copy(buf2, 0, 5, 15) |
||||
|
|
||||
|
t.equal(b.slice(5, 15).toString('hex'), buf2.toString('hex'), 'same buffer') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice across buffer boundaries', function (t) { |
||||
|
var bl = new BufferList(['First', 'Second', 'Third']) |
||||
|
|
||||
|
t.equal(bl.shallowSlice(3, 13).toString(), 'stSecondTh') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice within single buffer', function (t) { |
||||
|
t.plan(2) |
||||
|
var bl = new BufferList(['First', 'Second', 'Third']) |
||||
|
|
||||
|
t.equal(bl.shallowSlice(5, 10).toString(), 'Secon') |
||||
|
t.equal(bl.shallowSlice(7, 10).toString(), 'con') |
||||
|
t.end() |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice single buffer', function (t) { |
||||
|
t.plan(3) |
||||
|
var bl = new BufferList(['First', 'Second', 'Third']) |
||||
|
|
||||
|
t.equal(bl.shallowSlice(0, 5).toString(), 'First') |
||||
|
t.equal(bl.shallowSlice(5, 11).toString(), 'Second') |
||||
|
t.equal(bl.shallowSlice(11, 16).toString(), 'Third') |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice with negative or omitted indices', function (t) { |
||||
|
t.plan(4) |
||||
|
var bl = new BufferList(['First', 'Second', 'Third']) |
||||
|
|
||||
|
t.equal(bl.shallowSlice().toString(), 'FirstSecondThird') |
||||
|
t.equal(bl.shallowSlice(5).toString(), 'SecondThird') |
||||
|
t.equal(bl.shallowSlice(5, -3).toString(), 'SecondTh') |
||||
|
t.equal(bl.shallowSlice(-8).toString(), 'ondThird') |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice does not make a copy', function (t) { |
||||
|
t.plan(1) |
||||
|
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] |
||||
|
var bl = (new BufferList(buffers)).shallowSlice(5, -3) |
||||
|
|
||||
|
buffers[1].fill('h') |
||||
|
buffers[2].fill('h') |
||||
|
|
||||
|
t.equal(bl.toString(), 'hhhhhhhh') |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice with 0 length', function (t) { |
||||
|
t.plan(1) |
||||
|
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] |
||||
|
var bl = (new BufferList(buffers)).shallowSlice(0, 0) |
||||
|
t.equal(bl.length, 0) |
||||
|
}) |
||||
|
|
||||
|
tape('shallow slice with 0 length from middle', function (t) { |
||||
|
t.plan(1) |
||||
|
var buffers = [Buffer.from('First'), Buffer.from('Second'), Buffer.from('Third')] |
||||
|
var bl = (new BufferList(buffers)).shallowSlice(10, 10) |
||||
|
t.equal(bl.length, 0) |
||||
|
}) |
||||
|
|
||||
|
tape('duplicate', function (t) { |
||||
|
t.plan(2) |
||||
|
|
||||
|
var bl = new BufferList('abcdefghij\xff\x00') |
||||
|
, dup = bl.duplicate() |
||||
|
|
||||
|
t.equal(bl.prototype, dup.prototype) |
||||
|
t.equal(bl.toString('hex'), dup.toString('hex')) |
||||
|
}) |
||||
|
|
||||
|
tape('destroy no pipe', function (t) { |
||||
|
t.plan(2) |
||||
|
|
||||
|
var bl = new BufferList('alsdkfja;lsdkfja;lsdk') |
||||
|
bl.destroy() |
||||
|
|
||||
|
t.equal(bl._bufs.length, 0) |
||||
|
t.equal(bl.length, 0) |
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('destroy with pipe before read end', function (t) { |
||||
|
t.plan(2) |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
fs.createReadStream(__dirname + '/test.js') |
||||
|
.pipe(bl) |
||||
|
|
||||
|
bl.destroy() |
||||
|
|
||||
|
t.equal(bl._bufs.length, 0) |
||||
|
t.equal(bl.length, 0) |
||||
|
|
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('destroy with pipe before read end with race', function (t) { |
||||
|
t.plan(2) |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
fs.createReadStream(__dirname + '/test.js') |
||||
|
.pipe(bl) |
||||
|
|
||||
|
setTimeout(function () { |
||||
|
bl.destroy() |
||||
|
setTimeout(function () { |
||||
|
t.equal(bl._bufs.length, 0) |
||||
|
t.equal(bl.length, 0) |
||||
|
}, 500) |
||||
|
}, 500) |
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('destroy with pipe after read end', function (t) { |
||||
|
t.plan(2) |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
fs.createReadStream(__dirname + '/test.js') |
||||
|
.on('end', onEnd) |
||||
|
.pipe(bl) |
||||
|
|
||||
|
function onEnd () { |
||||
|
bl.destroy() |
||||
|
|
||||
|
t.equal(bl._bufs.length, 0) |
||||
|
t.equal(bl.length, 0) |
||||
|
} |
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('destroy with pipe while writing to a destination', function (t) { |
||||
|
t.plan(4) |
||||
|
|
||||
|
var bl = new BufferList() |
||||
|
, ds = new BufferList() |
||||
|
|
||||
|
fs.createReadStream(__dirname + '/test.js') |
||||
|
.on('end', onEnd) |
||||
|
.pipe(bl) |
||||
|
|
||||
|
function onEnd () { |
||||
|
bl.pipe(ds) |
||||
|
|
||||
|
setTimeout(function () { |
||||
|
bl.destroy() |
||||
|
|
||||
|
t.equals(bl._bufs.length, 0) |
||||
|
t.equals(bl.length, 0) |
||||
|
|
||||
|
ds.destroy() |
||||
|
|
||||
|
t.equals(bl._bufs.length, 0) |
||||
|
t.equals(bl.length, 0) |
||||
|
|
||||
|
}, 100) |
||||
|
} |
||||
|
}) |
||||
|
|
||||
|
!process.browser && tape('handle error', function (t) { |
||||
|
t.plan(2) |
||||
|
fs.createReadStream('/does/not/exist').pipe(BufferList(function (err, data) { |
||||
|
t.ok(err instanceof Error, 'has error') |
||||
|
t.notOk(data, 'no data') |
||||
|
})) |
||||
|
}) |
@ -0,0 +1,21 @@ |
|||||
|
The MIT License (MIT) |
||||
|
|
||||
|
Copyright (c) 2013-2017 Petka Antonov |
||||
|
|
||||
|
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. |
@ -0,0 +1,52 @@ |
|||||
|
<a href="http://promisesaplus.com/"> |
||||
|
<img src="http://promisesaplus.com/assets/logo-small.png" alt="Promises/A+ logo" |
||||
|
title="Promises/A+ 1.1 compliant" align="right" /> |
||||
|
</a> |
||||
|
|
||||
|
[](https://travis-ci.org/petkaantonov/bluebird) |
||||
|
[](http://petkaantonov.github.io/bluebird/coverage/debug/index.html) |
||||
|
|
||||
|
**Got a question?** Join us on [stackoverflow](http://stackoverflow.com/questions/tagged/bluebird), the [mailing list](https://groups.google.com/forum/#!forum/bluebird-js) or chat on [IRC](https://webchat.freenode.net/?channels=#promises) |
||||
|
|
||||
|
# Introduction |
||||
|
|
||||
|
Bluebird is a fully featured promise library with focus on innovative features and performance |
||||
|
|
||||
|
See the [**bluebird website**](http://bluebirdjs.com/docs/getting-started.html) for further documentation, references and instructions. See the [**API reference**](http://bluebirdjs.com/docs/api-reference.html) here. |
||||
|
|
||||
|
For bluebird 2.x documentation and files, see the [2.x tree](https://github.com/petkaantonov/bluebird/tree/2.x). |
||||
|
|
||||
|
# Questions and issues |
||||
|
|
||||
|
The [github issue tracker](https://github.com/petkaantonov/bluebird/issues) is **_only_** for bug reports and feature requests. Anything else, such as questions for help in using the library, should be posted in [StackOverflow](http://stackoverflow.com/questions/tagged/bluebird) under tags `promise` and `bluebird`. |
||||
|
|
||||
|
|
||||
|
|
||||
|
## Thanks |
||||
|
|
||||
|
Thanks to BrowserStack for providing us with a free account which lets us support old browsers like IE8. |
||||
|
|
||||
|
# License |
||||
|
|
||||
|
The MIT License (MIT) |
||||
|
|
||||
|
Copyright (c) 2013-2017 Petka Antonov |
||||
|
|
||||
|
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. |
||||
|
|
@ -0,0 +1 @@ |
|||||
|
[http://bluebirdjs.com/docs/changelog.html](http://bluebirdjs.com/docs/changelog.html) |
File diff suppressed because it is too large
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
File diff suppressed because one or more lines are too long
@ -0,0 +1,21 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise) { |
||||
|
var SomePromiseArray = Promise._SomePromiseArray; |
||||
|
function any(promises) { |
||||
|
var ret = new SomePromiseArray(promises); |
||||
|
var promise = ret.promise(); |
||||
|
ret.setHowMany(1); |
||||
|
ret.setUnwrap(); |
||||
|
ret.init(); |
||||
|
return promise; |
||||
|
} |
||||
|
|
||||
|
Promise.any = function (promises) { |
||||
|
return any(promises); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.any = function () { |
||||
|
return any(this); |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,55 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = (function(){ |
||||
|
var AssertionError = (function() { |
||||
|
function AssertionError(a) { |
||||
|
this.constructor$(a); |
||||
|
this.message = a; |
||||
|
this.name = "AssertionError"; |
||||
|
} |
||||
|
AssertionError.prototype = new Error(); |
||||
|
AssertionError.prototype.constructor = AssertionError; |
||||
|
AssertionError.prototype.constructor$ = Error; |
||||
|
return AssertionError; |
||||
|
})(); |
||||
|
|
||||
|
function getParams(args) { |
||||
|
var params = []; |
||||
|
for (var i = 0; i < args.length; ++i) params.push("arg" + i); |
||||
|
return params; |
||||
|
} |
||||
|
|
||||
|
function nativeAssert(callName, args, expect) { |
||||
|
try { |
||||
|
var params = getParams(args); |
||||
|
var constructorArgs = params; |
||||
|
constructorArgs.push("return " + |
||||
|
callName + "("+ params.join(",") + ");"); |
||||
|
var fn = Function.apply(null, constructorArgs); |
||||
|
return fn.apply(null, args); |
||||
|
} catch (e) { |
||||
|
if (!(e instanceof SyntaxError)) { |
||||
|
throw e; |
||||
|
} else { |
||||
|
return expect; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return function assert(boolExpr, message) { |
||||
|
if (boolExpr === true) return; |
||||
|
|
||||
|
if (typeof boolExpr === "string" && |
||||
|
boolExpr.charAt(0) === "%") { |
||||
|
var nativeCallName = boolExpr; |
||||
|
var $_len = arguments.length;var args = new Array(Math.max($_len - 2, 0)); for(var $_i = 2; $_i < $_len; ++$_i) {args[$_i - 2] = arguments[$_i];}; |
||||
|
if (nativeAssert(nativeCallName, args, message) === message) return; |
||||
|
message = (nativeCallName + " !== " + message); |
||||
|
} |
||||
|
|
||||
|
var ret = new AssertionError(message); |
||||
|
if (Error.captureStackTrace) { |
||||
|
Error.captureStackTrace(ret, assert); |
||||
|
} |
||||
|
throw ret; |
||||
|
}; |
||||
|
})(); |
@ -0,0 +1,161 @@ |
|||||
|
"use strict"; |
||||
|
var firstLineError; |
||||
|
try {throw new Error(); } catch (e) {firstLineError = e;} |
||||
|
var schedule = require("./schedule"); |
||||
|
var Queue = require("./queue"); |
||||
|
var util = require("./util"); |
||||
|
|
||||
|
function Async() { |
||||
|
this._customScheduler = false; |
||||
|
this._isTickUsed = false; |
||||
|
this._lateQueue = new Queue(16); |
||||
|
this._normalQueue = new Queue(16); |
||||
|
this._haveDrainedQueues = false; |
||||
|
this._trampolineEnabled = true; |
||||
|
var self = this; |
||||
|
this.drainQueues = function () { |
||||
|
self._drainQueues(); |
||||
|
}; |
||||
|
this._schedule = schedule; |
||||
|
} |
||||
|
|
||||
|
Async.prototype.setScheduler = function(fn) { |
||||
|
var prev = this._schedule; |
||||
|
this._schedule = fn; |
||||
|
this._customScheduler = true; |
||||
|
return prev; |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.hasCustomScheduler = function() { |
||||
|
return this._customScheduler; |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.enableTrampoline = function() { |
||||
|
this._trampolineEnabled = true; |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.disableTrampolineIfNecessary = function() { |
||||
|
if (util.hasDevTools) { |
||||
|
this._trampolineEnabled = false; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.haveItemsQueued = function () { |
||||
|
return this._isTickUsed || this._haveDrainedQueues; |
||||
|
}; |
||||
|
|
||||
|
|
||||
|
Async.prototype.fatalError = function(e, isNode) { |
||||
|
if (isNode) { |
||||
|
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) + |
||||
|
"\n"); |
||||
|
process.exit(2); |
||||
|
} else { |
||||
|
this.throwLater(e); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.throwLater = function(fn, arg) { |
||||
|
if (arguments.length === 1) { |
||||
|
arg = fn; |
||||
|
fn = function () { throw arg; }; |
||||
|
} |
||||
|
if (typeof setTimeout !== "undefined") { |
||||
|
setTimeout(function() { |
||||
|
fn(arg); |
||||
|
}, 0); |
||||
|
} else try { |
||||
|
this._schedule(function() { |
||||
|
fn(arg); |
||||
|
}); |
||||
|
} catch (e) { |
||||
|
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
function AsyncInvokeLater(fn, receiver, arg) { |
||||
|
this._lateQueue.push(fn, receiver, arg); |
||||
|
this._queueTick(); |
||||
|
} |
||||
|
|
||||
|
function AsyncInvoke(fn, receiver, arg) { |
||||
|
this._normalQueue.push(fn, receiver, arg); |
||||
|
this._queueTick(); |
||||
|
} |
||||
|
|
||||
|
function AsyncSettlePromises(promise) { |
||||
|
this._normalQueue._pushOne(promise); |
||||
|
this._queueTick(); |
||||
|
} |
||||
|
|
||||
|
if (!util.hasDevTools) { |
||||
|
Async.prototype.invokeLater = AsyncInvokeLater; |
||||
|
Async.prototype.invoke = AsyncInvoke; |
||||
|
Async.prototype.settlePromises = AsyncSettlePromises; |
||||
|
} else { |
||||
|
Async.prototype.invokeLater = function (fn, receiver, arg) { |
||||
|
if (this._trampolineEnabled) { |
||||
|
AsyncInvokeLater.call(this, fn, receiver, arg); |
||||
|
} else { |
||||
|
this._schedule(function() { |
||||
|
setTimeout(function() { |
||||
|
fn.call(receiver, arg); |
||||
|
}, 100); |
||||
|
}); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.invoke = function (fn, receiver, arg) { |
||||
|
if (this._trampolineEnabled) { |
||||
|
AsyncInvoke.call(this, fn, receiver, arg); |
||||
|
} else { |
||||
|
this._schedule(function() { |
||||
|
fn.call(receiver, arg); |
||||
|
}); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype.settlePromises = function(promise) { |
||||
|
if (this._trampolineEnabled) { |
||||
|
AsyncSettlePromises.call(this, promise); |
||||
|
} else { |
||||
|
this._schedule(function() { |
||||
|
promise._settlePromises(); |
||||
|
}); |
||||
|
} |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
Async.prototype._drainQueue = function(queue) { |
||||
|
while (queue.length() > 0) { |
||||
|
var fn = queue.shift(); |
||||
|
if (typeof fn !== "function") { |
||||
|
fn._settlePromises(); |
||||
|
continue; |
||||
|
} |
||||
|
var receiver = queue.shift(); |
||||
|
var arg = queue.shift(); |
||||
|
fn.call(receiver, arg); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype._drainQueues = function () { |
||||
|
this._drainQueue(this._normalQueue); |
||||
|
this._reset(); |
||||
|
this._haveDrainedQueues = true; |
||||
|
this._drainQueue(this._lateQueue); |
||||
|
}; |
||||
|
|
||||
|
Async.prototype._queueTick = function () { |
||||
|
if (!this._isTickUsed) { |
||||
|
this._isTickUsed = true; |
||||
|
this._schedule(this.drainQueues); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Async.prototype._reset = function () { |
||||
|
this._isTickUsed = false; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Async; |
||||
|
module.exports.firstLineError = firstLineError; |
@ -0,0 +1,67 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) { |
||||
|
var calledBind = false; |
||||
|
var rejectThis = function(_, e) { |
||||
|
this._reject(e); |
||||
|
}; |
||||
|
|
||||
|
var targetRejected = function(e, context) { |
||||
|
context.promiseRejectionQueued = true; |
||||
|
context.bindingPromise._then(rejectThis, rejectThis, null, this, e); |
||||
|
}; |
||||
|
|
||||
|
var bindingResolved = function(thisArg, context) { |
||||
|
if (((this._bitField & 50397184) === 0)) { |
||||
|
this._resolveCallback(context.target); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
var bindingRejected = function(e, context) { |
||||
|
if (!context.promiseRejectionQueued) this._reject(e); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.bind = function (thisArg) { |
||||
|
if (!calledBind) { |
||||
|
calledBind = true; |
||||
|
Promise.prototype._propagateFrom = debug.propagateFromFunction(); |
||||
|
Promise.prototype._boundValue = debug.boundValueFunction(); |
||||
|
} |
||||
|
var maybePromise = tryConvertToPromise(thisArg); |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._propagateFrom(this, 1); |
||||
|
var target = this._target(); |
||||
|
ret._setBoundTo(maybePromise); |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
var context = { |
||||
|
promiseRejectionQueued: false, |
||||
|
promise: ret, |
||||
|
target: target, |
||||
|
bindingPromise: maybePromise |
||||
|
}; |
||||
|
target._then(INTERNAL, targetRejected, undefined, ret, context); |
||||
|
maybePromise._then( |
||||
|
bindingResolved, bindingRejected, undefined, ret, context); |
||||
|
ret._setOnCancel(maybePromise); |
||||
|
} else { |
||||
|
ret._resolveCallback(target); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setBoundTo = function (obj) { |
||||
|
if (obj !== undefined) { |
||||
|
this._bitField = this._bitField | 2097152; |
||||
|
this._boundTo = obj; |
||||
|
} else { |
||||
|
this._bitField = this._bitField & (~2097152); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isBound = function () { |
||||
|
return (this._bitField & 2097152) === 2097152; |
||||
|
}; |
||||
|
|
||||
|
Promise.bind = function (thisArg, value) { |
||||
|
return Promise.resolve(value).bind(thisArg); |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,11 @@ |
|||||
|
"use strict"; |
||||
|
var old; |
||||
|
if (typeof Promise !== "undefined") old = Promise; |
||||
|
function noConflict() { |
||||
|
try { if (Promise === bluebird) Promise = old; } |
||||
|
catch (e) {} |
||||
|
return bluebird; |
||||
|
} |
||||
|
var bluebird = require("./promise")(); |
||||
|
bluebird.noConflict = noConflict; |
||||
|
module.exports = bluebird; |
@ -0,0 +1,123 @@ |
|||||
|
"use strict"; |
||||
|
var cr = Object.create; |
||||
|
if (cr) { |
||||
|
var callerCache = cr(null); |
||||
|
var getterCache = cr(null); |
||||
|
callerCache[" size"] = getterCache[" size"] = 0; |
||||
|
} |
||||
|
|
||||
|
module.exports = function(Promise) { |
||||
|
var util = require("./util"); |
||||
|
var canEvaluate = util.canEvaluate; |
||||
|
var isIdentifier = util.isIdentifier; |
||||
|
|
||||
|
var getMethodCaller; |
||||
|
var getGetter; |
||||
|
if (!false) { |
||||
|
var makeMethodCaller = function (methodName) { |
||||
|
return new Function("ensureMethod", " \n\ |
||||
|
return function(obj) { \n\ |
||||
|
'use strict' \n\ |
||||
|
var len = this.length; \n\ |
||||
|
ensureMethod(obj, 'methodName'); \n\ |
||||
|
switch(len) { \n\ |
||||
|
case 1: return obj.methodName(this[0]); \n\ |
||||
|
case 2: return obj.methodName(this[0], this[1]); \n\ |
||||
|
case 3: return obj.methodName(this[0], this[1], this[2]); \n\ |
||||
|
case 0: return obj.methodName(); \n\ |
||||
|
default: \n\ |
||||
|
return obj.methodName.apply(obj, this); \n\ |
||||
|
} \n\ |
||||
|
}; \n\ |
||||
|
".replace(/methodName/g, methodName))(ensureMethod); |
||||
|
}; |
||||
|
|
||||
|
var makeGetter = function (propertyName) { |
||||
|
return new Function("obj", " \n\ |
||||
|
'use strict'; \n\ |
||||
|
return obj.propertyName; \n\ |
||||
|
".replace("propertyName", propertyName)); |
||||
|
}; |
||||
|
|
||||
|
var getCompiled = function(name, compiler, cache) { |
||||
|
var ret = cache[name]; |
||||
|
if (typeof ret !== "function") { |
||||
|
if (!isIdentifier(name)) { |
||||
|
return null; |
||||
|
} |
||||
|
ret = compiler(name); |
||||
|
cache[name] = ret; |
||||
|
cache[" size"]++; |
||||
|
if (cache[" size"] > 512) { |
||||
|
var keys = Object.keys(cache); |
||||
|
for (var i = 0; i < 256; ++i) delete cache[keys[i]]; |
||||
|
cache[" size"] = keys.length - 256; |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
getMethodCaller = function(name) { |
||||
|
return getCompiled(name, makeMethodCaller, callerCache); |
||||
|
}; |
||||
|
|
||||
|
getGetter = function(name) { |
||||
|
return getCompiled(name, makeGetter, getterCache); |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
function ensureMethod(obj, methodName) { |
||||
|
var fn; |
||||
|
if (obj != null) fn = obj[methodName]; |
||||
|
if (typeof fn !== "function") { |
||||
|
var message = "Object " + util.classString(obj) + " has no method '" + |
||||
|
util.toString(methodName) + "'"; |
||||
|
throw new Promise.TypeError(message); |
||||
|
} |
||||
|
return fn; |
||||
|
} |
||||
|
|
||||
|
function caller(obj) { |
||||
|
var methodName = this.pop(); |
||||
|
var fn = ensureMethod(obj, methodName); |
||||
|
return fn.apply(obj, this); |
||||
|
} |
||||
|
Promise.prototype.call = function (methodName) { |
||||
|
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; |
||||
|
if (!false) { |
||||
|
if (canEvaluate) { |
||||
|
var maybeCaller = getMethodCaller(methodName); |
||||
|
if (maybeCaller !== null) { |
||||
|
return this._then( |
||||
|
maybeCaller, undefined, undefined, args, undefined); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
args.push(methodName); |
||||
|
return this._then(caller, undefined, undefined, args, undefined); |
||||
|
}; |
||||
|
|
||||
|
function namedGetter(obj) { |
||||
|
return obj[this]; |
||||
|
} |
||||
|
function indexedGetter(obj) { |
||||
|
var index = +this; |
||||
|
if (index < 0) index = Math.max(0, index + obj.length); |
||||
|
return obj[index]; |
||||
|
} |
||||
|
Promise.prototype.get = function (propertyName) { |
||||
|
var isIndex = (typeof propertyName === "number"); |
||||
|
var getter; |
||||
|
if (!isIndex) { |
||||
|
if (canEvaluate) { |
||||
|
var maybeGetter = getGetter(propertyName); |
||||
|
getter = maybeGetter !== null ? maybeGetter : namedGetter; |
||||
|
} else { |
||||
|
getter = namedGetter; |
||||
|
} |
||||
|
} else { |
||||
|
getter = indexedGetter; |
||||
|
} |
||||
|
return this._then(getter, undefined, undefined, propertyName, undefined); |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,129 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, PromiseArray, apiRejection, debug) { |
||||
|
var util = require("./util"); |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var errorObj = util.errorObj; |
||||
|
var async = Promise._async; |
||||
|
|
||||
|
Promise.prototype["break"] = Promise.prototype.cancel = function() { |
||||
|
if (!debug.cancellation()) return this._warn("cancellation is disabled"); |
||||
|
|
||||
|
var promise = this; |
||||
|
var child = promise; |
||||
|
while (promise._isCancellable()) { |
||||
|
if (!promise._cancelBy(child)) { |
||||
|
if (child._isFollowing()) { |
||||
|
child._followee().cancel(); |
||||
|
} else { |
||||
|
child._cancelBranched(); |
||||
|
} |
||||
|
break; |
||||
|
} |
||||
|
|
||||
|
var parent = promise._cancellationParent; |
||||
|
if (parent == null || !parent._isCancellable()) { |
||||
|
if (promise._isFollowing()) { |
||||
|
promise._followee().cancel(); |
||||
|
} else { |
||||
|
promise._cancelBranched(); |
||||
|
} |
||||
|
break; |
||||
|
} else { |
||||
|
if (promise._isFollowing()) promise._followee().cancel(); |
||||
|
promise._setWillBeCancelled(); |
||||
|
child = promise; |
||||
|
promise = parent; |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._branchHasCancelled = function() { |
||||
|
this._branchesRemainingToCancel--; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._enoughBranchesHaveCancelled = function() { |
||||
|
return this._branchesRemainingToCancel === undefined || |
||||
|
this._branchesRemainingToCancel <= 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._cancelBy = function(canceller) { |
||||
|
if (canceller === this) { |
||||
|
this._branchesRemainingToCancel = 0; |
||||
|
this._invokeOnCancel(); |
||||
|
return true; |
||||
|
} else { |
||||
|
this._branchHasCancelled(); |
||||
|
if (this._enoughBranchesHaveCancelled()) { |
||||
|
this._invokeOnCancel(); |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._cancelBranched = function() { |
||||
|
if (this._enoughBranchesHaveCancelled()) { |
||||
|
this._cancel(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._cancel = function() { |
||||
|
if (!this._isCancellable()) return; |
||||
|
this._setCancelled(); |
||||
|
async.invoke(this._cancelPromises, this, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._cancelPromises = function() { |
||||
|
if (this._length() > 0) this._settlePromises(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._unsetOnCancel = function() { |
||||
|
this._onCancelField = undefined; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isCancellable = function() { |
||||
|
return this.isPending() && !this._isCancelled(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isCancellable = function() { |
||||
|
return this.isPending() && !this.isCancelled(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) { |
||||
|
if (util.isArray(onCancelCallback)) { |
||||
|
for (var i = 0; i < onCancelCallback.length; ++i) { |
||||
|
this._doInvokeOnCancel(onCancelCallback[i], internalOnly); |
||||
|
} |
||||
|
} else if (onCancelCallback !== undefined) { |
||||
|
if (typeof onCancelCallback === "function") { |
||||
|
if (!internalOnly) { |
||||
|
var e = tryCatch(onCancelCallback).call(this._boundValue()); |
||||
|
if (e === errorObj) { |
||||
|
this._attachExtraTrace(e.e); |
||||
|
async.throwLater(e.e); |
||||
|
} |
||||
|
} |
||||
|
} else { |
||||
|
onCancelCallback._resultCancelled(this); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._invokeOnCancel = function() { |
||||
|
var onCancelCallback = this._onCancel(); |
||||
|
this._unsetOnCancel(); |
||||
|
async.invoke(this._doInvokeOnCancel, this, onCancelCallback); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._invokeInternalOnCancel = function() { |
||||
|
if (this._isCancellable()) { |
||||
|
this._doInvokeOnCancel(this._onCancel(), true); |
||||
|
this._unsetOnCancel(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._resultCancelled = function() { |
||||
|
this.cancel(); |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,42 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(NEXT_FILTER) { |
||||
|
var util = require("./util"); |
||||
|
var getKeys = require("./es5").keys; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var errorObj = util.errorObj; |
||||
|
|
||||
|
function catchFilter(instances, cb, promise) { |
||||
|
return function(e) { |
||||
|
var boundTo = promise._boundValue(); |
||||
|
predicateLoop: for (var i = 0; i < instances.length; ++i) { |
||||
|
var item = instances[i]; |
||||
|
|
||||
|
if (item === Error || |
||||
|
(item != null && item.prototype instanceof Error)) { |
||||
|
if (e instanceof item) { |
||||
|
return tryCatch(cb).call(boundTo, e); |
||||
|
} |
||||
|
} else if (typeof item === "function") { |
||||
|
var matchesPredicate = tryCatch(item).call(boundTo, e); |
||||
|
if (matchesPredicate === errorObj) { |
||||
|
return matchesPredicate; |
||||
|
} else if (matchesPredicate) { |
||||
|
return tryCatch(cb).call(boundTo, e); |
||||
|
} |
||||
|
} else if (util.isObject(e)) { |
||||
|
var keys = getKeys(item); |
||||
|
for (var j = 0; j < keys.length; ++j) { |
||||
|
var key = keys[j]; |
||||
|
if (item[key] != e[key]) { |
||||
|
continue predicateLoop; |
||||
|
} |
||||
|
} |
||||
|
return tryCatch(cb).call(boundTo, e); |
||||
|
} |
||||
|
} |
||||
|
return NEXT_FILTER; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
return catchFilter; |
||||
|
}; |
@ -0,0 +1,69 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise) { |
||||
|
var longStackTraces = false; |
||||
|
var contextStack = []; |
||||
|
|
||||
|
Promise.prototype._promiseCreated = function() {}; |
||||
|
Promise.prototype._pushContext = function() {}; |
||||
|
Promise.prototype._popContext = function() {return null;}; |
||||
|
Promise._peekContext = Promise.prototype._peekContext = function() {}; |
||||
|
|
||||
|
function Context() { |
||||
|
this._trace = new Context.CapturedTrace(peekContext()); |
||||
|
} |
||||
|
Context.prototype._pushContext = function () { |
||||
|
if (this._trace !== undefined) { |
||||
|
this._trace._promiseCreated = null; |
||||
|
contextStack.push(this._trace); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Context.prototype._popContext = function () { |
||||
|
if (this._trace !== undefined) { |
||||
|
var trace = contextStack.pop(); |
||||
|
var ret = trace._promiseCreated; |
||||
|
trace._promiseCreated = null; |
||||
|
return ret; |
||||
|
} |
||||
|
return null; |
||||
|
}; |
||||
|
|
||||
|
function createContext() { |
||||
|
if (longStackTraces) return new Context(); |
||||
|
} |
||||
|
|
||||
|
function peekContext() { |
||||
|
var lastIndex = contextStack.length - 1; |
||||
|
if (lastIndex >= 0) { |
||||
|
return contextStack[lastIndex]; |
||||
|
} |
||||
|
return undefined; |
||||
|
} |
||||
|
Context.CapturedTrace = null; |
||||
|
Context.create = createContext; |
||||
|
Context.deactivateLongStackTraces = function() {}; |
||||
|
Context.activateLongStackTraces = function() { |
||||
|
var Promise_pushContext = Promise.prototype._pushContext; |
||||
|
var Promise_popContext = Promise.prototype._popContext; |
||||
|
var Promise_PeekContext = Promise._peekContext; |
||||
|
var Promise_peekContext = Promise.prototype._peekContext; |
||||
|
var Promise_promiseCreated = Promise.prototype._promiseCreated; |
||||
|
Context.deactivateLongStackTraces = function() { |
||||
|
Promise.prototype._pushContext = Promise_pushContext; |
||||
|
Promise.prototype._popContext = Promise_popContext; |
||||
|
Promise._peekContext = Promise_PeekContext; |
||||
|
Promise.prototype._peekContext = Promise_peekContext; |
||||
|
Promise.prototype._promiseCreated = Promise_promiseCreated; |
||||
|
longStackTraces = false; |
||||
|
}; |
||||
|
longStackTraces = true; |
||||
|
Promise.prototype._pushContext = Context.prototype._pushContext; |
||||
|
Promise.prototype._popContext = Context.prototype._popContext; |
||||
|
Promise._peekContext = Promise.prototype._peekContext = peekContext; |
||||
|
Promise.prototype._promiseCreated = function() { |
||||
|
var ctx = this._peekContext(); |
||||
|
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this; |
||||
|
}; |
||||
|
}; |
||||
|
return Context; |
||||
|
}; |
@ -0,0 +1,919 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, Context) { |
||||
|
var getDomain = Promise._getDomain; |
||||
|
var async = Promise._async; |
||||
|
var Warning = require("./errors").Warning; |
||||
|
var util = require("./util"); |
||||
|
var canAttachTrace = util.canAttachTrace; |
||||
|
var unhandledRejectionHandled; |
||||
|
var possiblyUnhandledRejection; |
||||
|
var bluebirdFramePattern = |
||||
|
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/; |
||||
|
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/; |
||||
|
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/; |
||||
|
var stackFramePattern = null; |
||||
|
var formatStack = null; |
||||
|
var indentStackFrames = false; |
||||
|
var printWarning; |
||||
|
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 && |
||||
|
(false || |
||||
|
util.env("BLUEBIRD_DEBUG") || |
||||
|
util.env("NODE_ENV") === "development")); |
||||
|
|
||||
|
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 && |
||||
|
(debugging || util.env("BLUEBIRD_WARNINGS"))); |
||||
|
|
||||
|
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 && |
||||
|
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES"))); |
||||
|
|
||||
|
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 && |
||||
|
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN")); |
||||
|
|
||||
|
Promise.prototype.suppressUnhandledRejections = function() { |
||||
|
var target = this._target(); |
||||
|
target._bitField = ((target._bitField & (~1048576)) | |
||||
|
524288); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._ensurePossibleRejectionHandled = function () { |
||||
|
if ((this._bitField & 524288) !== 0) return; |
||||
|
this._setRejectionIsUnhandled(); |
||||
|
var self = this; |
||||
|
setTimeout(function() { |
||||
|
self._notifyUnhandledRejection(); |
||||
|
}, 1); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._notifyUnhandledRejectionIsHandled = function () { |
||||
|
fireRejectionEvent("rejectionHandled", |
||||
|
unhandledRejectionHandled, undefined, this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setReturnedNonUndefined = function() { |
||||
|
this._bitField = this._bitField | 268435456; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._returnedNonUndefined = function() { |
||||
|
return (this._bitField & 268435456) !== 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._notifyUnhandledRejection = function () { |
||||
|
if (this._isRejectionUnhandled()) { |
||||
|
var reason = this._settledValue(); |
||||
|
this._setUnhandledRejectionIsNotified(); |
||||
|
fireRejectionEvent("unhandledRejection", |
||||
|
possiblyUnhandledRejection, reason, this); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setUnhandledRejectionIsNotified = function () { |
||||
|
this._bitField = this._bitField | 262144; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._unsetUnhandledRejectionIsNotified = function () { |
||||
|
this._bitField = this._bitField & (~262144); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isUnhandledRejectionNotified = function () { |
||||
|
return (this._bitField & 262144) > 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setRejectionIsUnhandled = function () { |
||||
|
this._bitField = this._bitField | 1048576; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._unsetRejectionIsUnhandled = function () { |
||||
|
this._bitField = this._bitField & (~1048576); |
||||
|
if (this._isUnhandledRejectionNotified()) { |
||||
|
this._unsetUnhandledRejectionIsNotified(); |
||||
|
this._notifyUnhandledRejectionIsHandled(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isRejectionUnhandled = function () { |
||||
|
return (this._bitField & 1048576) > 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) { |
||||
|
return warn(message, shouldUseOwnTrace, promise || this); |
||||
|
}; |
||||
|
|
||||
|
Promise.onPossiblyUnhandledRejection = function (fn) { |
||||
|
var domain = getDomain(); |
||||
|
possiblyUnhandledRejection = |
||||
|
typeof fn === "function" ? (domain === null ? |
||||
|
fn : util.domainBind(domain, fn)) |
||||
|
: undefined; |
||||
|
}; |
||||
|
|
||||
|
Promise.onUnhandledRejectionHandled = function (fn) { |
||||
|
var domain = getDomain(); |
||||
|
unhandledRejectionHandled = |
||||
|
typeof fn === "function" ? (domain === null ? |
||||
|
fn : util.domainBind(domain, fn)) |
||||
|
: undefined; |
||||
|
}; |
||||
|
|
||||
|
var disableLongStackTraces = function() {}; |
||||
|
Promise.longStackTraces = function () { |
||||
|
if (async.haveItemsQueued() && !config.longStackTraces) { |
||||
|
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
if (!config.longStackTraces && longStackTracesIsSupported()) { |
||||
|
var Promise_captureStackTrace = Promise.prototype._captureStackTrace; |
||||
|
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace; |
||||
|
config.longStackTraces = true; |
||||
|
disableLongStackTraces = function() { |
||||
|
if (async.haveItemsQueued() && !config.longStackTraces) { |
||||
|
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
Promise.prototype._captureStackTrace = Promise_captureStackTrace; |
||||
|
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace; |
||||
|
Context.deactivateLongStackTraces(); |
||||
|
async.enableTrampoline(); |
||||
|
config.longStackTraces = false; |
||||
|
}; |
||||
|
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace; |
||||
|
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace; |
||||
|
Context.activateLongStackTraces(); |
||||
|
async.disableTrampolineIfNecessary(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.hasLongStackTraces = function () { |
||||
|
return config.longStackTraces && longStackTracesIsSupported(); |
||||
|
}; |
||||
|
|
||||
|
var fireDomEvent = (function() { |
||||
|
try { |
||||
|
if (typeof CustomEvent === "function") { |
||||
|
var event = new CustomEvent("CustomEvent"); |
||||
|
util.global.dispatchEvent(event); |
||||
|
return function(name, event) { |
||||
|
var domEvent = new CustomEvent(name.toLowerCase(), { |
||||
|
detail: event, |
||||
|
cancelable: true |
||||
|
}); |
||||
|
return !util.global.dispatchEvent(domEvent); |
||||
|
}; |
||||
|
} else if (typeof Event === "function") { |
||||
|
var event = new Event("CustomEvent"); |
||||
|
util.global.dispatchEvent(event); |
||||
|
return function(name, event) { |
||||
|
var domEvent = new Event(name.toLowerCase(), { |
||||
|
cancelable: true |
||||
|
}); |
||||
|
domEvent.detail = event; |
||||
|
return !util.global.dispatchEvent(domEvent); |
||||
|
}; |
||||
|
} else { |
||||
|
var event = document.createEvent("CustomEvent"); |
||||
|
event.initCustomEvent("testingtheevent", false, true, {}); |
||||
|
util.global.dispatchEvent(event); |
||||
|
return function(name, event) { |
||||
|
var domEvent = document.createEvent("CustomEvent"); |
||||
|
domEvent.initCustomEvent(name.toLowerCase(), false, true, |
||||
|
event); |
||||
|
return !util.global.dispatchEvent(domEvent); |
||||
|
}; |
||||
|
} |
||||
|
} catch (e) {} |
||||
|
return function() { |
||||
|
return false; |
||||
|
}; |
||||
|
})(); |
||||
|
|
||||
|
var fireGlobalEvent = (function() { |
||||
|
if (util.isNode) { |
||||
|
return function() { |
||||
|
return process.emit.apply(process, arguments); |
||||
|
}; |
||||
|
} else { |
||||
|
if (!util.global) { |
||||
|
return function() { |
||||
|
return false; |
||||
|
}; |
||||
|
} |
||||
|
return function(name) { |
||||
|
var methodName = "on" + name.toLowerCase(); |
||||
|
var method = util.global[methodName]; |
||||
|
if (!method) return false; |
||||
|
method.apply(util.global, [].slice.call(arguments, 1)); |
||||
|
return true; |
||||
|
}; |
||||
|
} |
||||
|
})(); |
||||
|
|
||||
|
function generatePromiseLifecycleEventObject(name, promise) { |
||||
|
return {promise: promise}; |
||||
|
} |
||||
|
|
||||
|
var eventToObjectGenerator = { |
||||
|
promiseCreated: generatePromiseLifecycleEventObject, |
||||
|
promiseFulfilled: generatePromiseLifecycleEventObject, |
||||
|
promiseRejected: generatePromiseLifecycleEventObject, |
||||
|
promiseResolved: generatePromiseLifecycleEventObject, |
||||
|
promiseCancelled: generatePromiseLifecycleEventObject, |
||||
|
promiseChained: function(name, promise, child) { |
||||
|
return {promise: promise, child: child}; |
||||
|
}, |
||||
|
warning: function(name, warning) { |
||||
|
return {warning: warning}; |
||||
|
}, |
||||
|
unhandledRejection: function (name, reason, promise) { |
||||
|
return {reason: reason, promise: promise}; |
||||
|
}, |
||||
|
rejectionHandled: generatePromiseLifecycleEventObject |
||||
|
}; |
||||
|
|
||||
|
var activeFireEvent = function (name) { |
||||
|
var globalEventFired = false; |
||||
|
try { |
||||
|
globalEventFired = fireGlobalEvent.apply(null, arguments); |
||||
|
} catch (e) { |
||||
|
async.throwLater(e); |
||||
|
globalEventFired = true; |
||||
|
} |
||||
|
|
||||
|
var domEventFired = false; |
||||
|
try { |
||||
|
domEventFired = fireDomEvent(name, |
||||
|
eventToObjectGenerator[name].apply(null, arguments)); |
||||
|
} catch (e) { |
||||
|
async.throwLater(e); |
||||
|
domEventFired = true; |
||||
|
} |
||||
|
|
||||
|
return domEventFired || globalEventFired; |
||||
|
}; |
||||
|
|
||||
|
Promise.config = function(opts) { |
||||
|
opts = Object(opts); |
||||
|
if ("longStackTraces" in opts) { |
||||
|
if (opts.longStackTraces) { |
||||
|
Promise.longStackTraces(); |
||||
|
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) { |
||||
|
disableLongStackTraces(); |
||||
|
} |
||||
|
} |
||||
|
if ("warnings" in opts) { |
||||
|
var warningsOption = opts.warnings; |
||||
|
config.warnings = !!warningsOption; |
||||
|
wForgottenReturn = config.warnings; |
||||
|
|
||||
|
if (util.isObject(warningsOption)) { |
||||
|
if ("wForgottenReturn" in warningsOption) { |
||||
|
wForgottenReturn = !!warningsOption.wForgottenReturn; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
if ("cancellation" in opts && opts.cancellation && !config.cancellation) { |
||||
|
if (async.haveItemsQueued()) { |
||||
|
throw new Error( |
||||
|
"cannot enable cancellation after promises are in use"); |
||||
|
} |
||||
|
Promise.prototype._clearCancellationData = |
||||
|
cancellationClearCancellationData; |
||||
|
Promise.prototype._propagateFrom = cancellationPropagateFrom; |
||||
|
Promise.prototype._onCancel = cancellationOnCancel; |
||||
|
Promise.prototype._setOnCancel = cancellationSetOnCancel; |
||||
|
Promise.prototype._attachCancellationCallback = |
||||
|
cancellationAttachCancellationCallback; |
||||
|
Promise.prototype._execute = cancellationExecute; |
||||
|
propagateFromFunction = cancellationPropagateFrom; |
||||
|
config.cancellation = true; |
||||
|
} |
||||
|
if ("monitoring" in opts) { |
||||
|
if (opts.monitoring && !config.monitoring) { |
||||
|
config.monitoring = true; |
||||
|
Promise.prototype._fireEvent = activeFireEvent; |
||||
|
} else if (!opts.monitoring && config.monitoring) { |
||||
|
config.monitoring = false; |
||||
|
Promise.prototype._fireEvent = defaultFireEvent; |
||||
|
} |
||||
|
} |
||||
|
return Promise; |
||||
|
}; |
||||
|
|
||||
|
function defaultFireEvent() { return false; } |
||||
|
|
||||
|
Promise.prototype._fireEvent = defaultFireEvent; |
||||
|
Promise.prototype._execute = function(executor, resolve, reject) { |
||||
|
try { |
||||
|
executor(resolve, reject); |
||||
|
} catch (e) { |
||||
|
return e; |
||||
|
} |
||||
|
}; |
||||
|
Promise.prototype._onCancel = function () {}; |
||||
|
Promise.prototype._setOnCancel = function (handler) { ; }; |
||||
|
Promise.prototype._attachCancellationCallback = function(onCancel) { |
||||
|
; |
||||
|
}; |
||||
|
Promise.prototype._captureStackTrace = function () {}; |
||||
|
Promise.prototype._attachExtraTrace = function () {}; |
||||
|
Promise.prototype._clearCancellationData = function() {}; |
||||
|
Promise.prototype._propagateFrom = function (parent, flags) { |
||||
|
; |
||||
|
; |
||||
|
}; |
||||
|
|
||||
|
function cancellationExecute(executor, resolve, reject) { |
||||
|
var promise = this; |
||||
|
try { |
||||
|
executor(resolve, reject, function(onCancel) { |
||||
|
if (typeof onCancel !== "function") { |
||||
|
throw new TypeError("onCancel must be a function, got: " + |
||||
|
util.toString(onCancel)); |
||||
|
} |
||||
|
promise._attachCancellationCallback(onCancel); |
||||
|
}); |
||||
|
} catch (e) { |
||||
|
return e; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function cancellationAttachCancellationCallback(onCancel) { |
||||
|
if (!this._isCancellable()) return this; |
||||
|
|
||||
|
var previousOnCancel = this._onCancel(); |
||||
|
if (previousOnCancel !== undefined) { |
||||
|
if (util.isArray(previousOnCancel)) { |
||||
|
previousOnCancel.push(onCancel); |
||||
|
} else { |
||||
|
this._setOnCancel([previousOnCancel, onCancel]); |
||||
|
} |
||||
|
} else { |
||||
|
this._setOnCancel(onCancel); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function cancellationOnCancel() { |
||||
|
return this._onCancelField; |
||||
|
} |
||||
|
|
||||
|
function cancellationSetOnCancel(onCancel) { |
||||
|
this._onCancelField = onCancel; |
||||
|
} |
||||
|
|
||||
|
function cancellationClearCancellationData() { |
||||
|
this._cancellationParent = undefined; |
||||
|
this._onCancelField = undefined; |
||||
|
} |
||||
|
|
||||
|
function cancellationPropagateFrom(parent, flags) { |
||||
|
if ((flags & 1) !== 0) { |
||||
|
this._cancellationParent = parent; |
||||
|
var branchesRemainingToCancel = parent._branchesRemainingToCancel; |
||||
|
if (branchesRemainingToCancel === undefined) { |
||||
|
branchesRemainingToCancel = 0; |
||||
|
} |
||||
|
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1; |
||||
|
} |
||||
|
if ((flags & 2) !== 0 && parent._isBound()) { |
||||
|
this._setBoundTo(parent._boundTo); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function bindingPropagateFrom(parent, flags) { |
||||
|
if ((flags & 2) !== 0 && parent._isBound()) { |
||||
|
this._setBoundTo(parent._boundTo); |
||||
|
} |
||||
|
} |
||||
|
var propagateFromFunction = bindingPropagateFrom; |
||||
|
|
||||
|
function boundValueFunction() { |
||||
|
var ret = this._boundTo; |
||||
|
if (ret !== undefined) { |
||||
|
if (ret instanceof Promise) { |
||||
|
if (ret.isFulfilled()) { |
||||
|
return ret.value(); |
||||
|
} else { |
||||
|
return undefined; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
function longStackTracesCaptureStackTrace() { |
||||
|
this._trace = new CapturedTrace(this._peekContext()); |
||||
|
} |
||||
|
|
||||
|
function longStackTracesAttachExtraTrace(error, ignoreSelf) { |
||||
|
if (canAttachTrace(error)) { |
||||
|
var trace = this._trace; |
||||
|
if (trace !== undefined) { |
||||
|
if (ignoreSelf) trace = trace._parent; |
||||
|
} |
||||
|
if (trace !== undefined) { |
||||
|
trace.attachExtraTrace(error); |
||||
|
} else if (!error.__stackCleaned__) { |
||||
|
var parsed = parseStackAndMessage(error); |
||||
|
util.notEnumerableProp(error, "stack", |
||||
|
parsed.message + "\n" + parsed.stack.join("\n")); |
||||
|
util.notEnumerableProp(error, "__stackCleaned__", true); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function checkForgottenReturns(returnValue, promiseCreated, name, promise, |
||||
|
parent) { |
||||
|
if (returnValue === undefined && promiseCreated !== null && |
||||
|
wForgottenReturn) { |
||||
|
if (parent !== undefined && parent._returnedNonUndefined()) return; |
||||
|
if ((promise._bitField & 65535) === 0) return; |
||||
|
|
||||
|
if (name) name = name + " "; |
||||
|
var handlerLine = ""; |
||||
|
var creatorLine = ""; |
||||
|
if (promiseCreated._trace) { |
||||
|
var traceLines = promiseCreated._trace.stack.split("\n"); |
||||
|
var stack = cleanStack(traceLines); |
||||
|
for (var i = stack.length - 1; i >= 0; --i) { |
||||
|
var line = stack[i]; |
||||
|
if (!nodeFramePattern.test(line)) { |
||||
|
var lineMatches = line.match(parseLinePattern); |
||||
|
if (lineMatches) { |
||||
|
handlerLine = "at " + lineMatches[1] + |
||||
|
":" + lineMatches[2] + ":" + lineMatches[3] + " "; |
||||
|
} |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (stack.length > 0) { |
||||
|
var firstUserLine = stack[0]; |
||||
|
for (var i = 0; i < traceLines.length; ++i) { |
||||
|
|
||||
|
if (traceLines[i] === firstUserLine) { |
||||
|
if (i > 0) { |
||||
|
creatorLine = "\n" + traceLines[i - 1]; |
||||
|
} |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
} |
||||
|
var msg = "a promise was created in a " + name + |
||||
|
"handler " + handlerLine + "but was not returned from it, " + |
||||
|
"see http://goo.gl/rRqMUw" + |
||||
|
creatorLine; |
||||
|
promise._warn(msg, true, promiseCreated); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function deprecated(name, replacement) { |
||||
|
var message = name + |
||||
|
" is deprecated and will be removed in a future version."; |
||||
|
if (replacement) message += " Use " + replacement + " instead."; |
||||
|
return warn(message); |
||||
|
} |
||||
|
|
||||
|
function warn(message, shouldUseOwnTrace, promise) { |
||||
|
if (!config.warnings) return; |
||||
|
var warning = new Warning(message); |
||||
|
var ctx; |
||||
|
if (shouldUseOwnTrace) { |
||||
|
promise._attachExtraTrace(warning); |
||||
|
} else if (config.longStackTraces && (ctx = Promise._peekContext())) { |
||||
|
ctx.attachExtraTrace(warning); |
||||
|
} else { |
||||
|
var parsed = parseStackAndMessage(warning); |
||||
|
warning.stack = parsed.message + "\n" + parsed.stack.join("\n"); |
||||
|
} |
||||
|
|
||||
|
if (!activeFireEvent("warning", warning)) { |
||||
|
formatAndLogError(warning, "", true); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function reconstructStack(message, stacks) { |
||||
|
for (var i = 0; i < stacks.length - 1; ++i) { |
||||
|
stacks[i].push("From previous event:"); |
||||
|
stacks[i] = stacks[i].join("\n"); |
||||
|
} |
||||
|
if (i < stacks.length) { |
||||
|
stacks[i] = stacks[i].join("\n"); |
||||
|
} |
||||
|
return message + "\n" + stacks.join("\n"); |
||||
|
} |
||||
|
|
||||
|
function removeDuplicateOrEmptyJumps(stacks) { |
||||
|
for (var i = 0; i < stacks.length; ++i) { |
||||
|
if (stacks[i].length === 0 || |
||||
|
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) { |
||||
|
stacks.splice(i, 1); |
||||
|
i--; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function removeCommonRoots(stacks) { |
||||
|
var current = stacks[0]; |
||||
|
for (var i = 1; i < stacks.length; ++i) { |
||||
|
var prev = stacks[i]; |
||||
|
var currentLastIndex = current.length - 1; |
||||
|
var currentLastLine = current[currentLastIndex]; |
||||
|
var commonRootMeetPoint = -1; |
||||
|
|
||||
|
for (var j = prev.length - 1; j >= 0; --j) { |
||||
|
if (prev[j] === currentLastLine) { |
||||
|
commonRootMeetPoint = j; |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
for (var j = commonRootMeetPoint; j >= 0; --j) { |
||||
|
var line = prev[j]; |
||||
|
if (current[currentLastIndex] === line) { |
||||
|
current.pop(); |
||||
|
currentLastIndex--; |
||||
|
} else { |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
current = prev; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function cleanStack(stack) { |
||||
|
var ret = []; |
||||
|
for (var i = 0; i < stack.length; ++i) { |
||||
|
var line = stack[i]; |
||||
|
var isTraceLine = " (No stack trace)" === line || |
||||
|
stackFramePattern.test(line); |
||||
|
var isInternalFrame = isTraceLine && shouldIgnore(line); |
||||
|
if (isTraceLine && !isInternalFrame) { |
||||
|
if (indentStackFrames && line.charAt(0) !== " ") { |
||||
|
line = " " + line; |
||||
|
} |
||||
|
ret.push(line); |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
function stackFramesAsArray(error) { |
||||
|
var stack = error.stack.replace(/\s+$/g, "").split("\n"); |
||||
|
for (var i = 0; i < stack.length; ++i) { |
||||
|
var line = stack[i]; |
||||
|
if (" (No stack trace)" === line || stackFramePattern.test(line)) { |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
if (i > 0 && error.name != "SyntaxError") { |
||||
|
stack = stack.slice(i); |
||||
|
} |
||||
|
return stack; |
||||
|
} |
||||
|
|
||||
|
function parseStackAndMessage(error) { |
||||
|
var stack = error.stack; |
||||
|
var message = error.toString(); |
||||
|
stack = typeof stack === "string" && stack.length > 0 |
||||
|
? stackFramesAsArray(error) : [" (No stack trace)"]; |
||||
|
return { |
||||
|
message: message, |
||||
|
stack: error.name == "SyntaxError" ? stack : cleanStack(stack) |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
function formatAndLogError(error, title, isSoft) { |
||||
|
if (typeof console !== "undefined") { |
||||
|
var message; |
||||
|
if (util.isObject(error)) { |
||||
|
var stack = error.stack; |
||||
|
message = title + formatStack(stack, error); |
||||
|
} else { |
||||
|
message = title + String(error); |
||||
|
} |
||||
|
if (typeof printWarning === "function") { |
||||
|
printWarning(message, isSoft); |
||||
|
} else if (typeof console.log === "function" || |
||||
|
typeof console.log === "object") { |
||||
|
console.log(message); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function fireRejectionEvent(name, localHandler, reason, promise) { |
||||
|
var localEventFired = false; |
||||
|
try { |
||||
|
if (typeof localHandler === "function") { |
||||
|
localEventFired = true; |
||||
|
if (name === "rejectionHandled") { |
||||
|
localHandler(promise); |
||||
|
} else { |
||||
|
localHandler(reason, promise); |
||||
|
} |
||||
|
} |
||||
|
} catch (e) { |
||||
|
async.throwLater(e); |
||||
|
} |
||||
|
|
||||
|
if (name === "unhandledRejection") { |
||||
|
if (!activeFireEvent(name, reason, promise) && !localEventFired) { |
||||
|
formatAndLogError(reason, "Unhandled rejection "); |
||||
|
} |
||||
|
} else { |
||||
|
activeFireEvent(name, promise); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function formatNonError(obj) { |
||||
|
var str; |
||||
|
if (typeof obj === "function") { |
||||
|
str = "[function " + |
||||
|
(obj.name || "anonymous") + |
||||
|
"]"; |
||||
|
} else { |
||||
|
str = obj && typeof obj.toString === "function" |
||||
|
? obj.toString() : util.toString(obj); |
||||
|
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/; |
||||
|
if (ruselessToString.test(str)) { |
||||
|
try { |
||||
|
var newStr = JSON.stringify(obj); |
||||
|
str = newStr; |
||||
|
} |
||||
|
catch(e) { |
||||
|
|
||||
|
} |
||||
|
} |
||||
|
if (str.length === 0) { |
||||
|
str = "(empty array)"; |
||||
|
} |
||||
|
} |
||||
|
return ("(<" + snip(str) + ">, no stack trace)"); |
||||
|
} |
||||
|
|
||||
|
function snip(str) { |
||||
|
var maxChars = 41; |
||||
|
if (str.length < maxChars) { |
||||
|
return str; |
||||
|
} |
||||
|
return str.substr(0, maxChars - 3) + "..."; |
||||
|
} |
||||
|
|
||||
|
function longStackTracesIsSupported() { |
||||
|
return typeof captureStackTrace === "function"; |
||||
|
} |
||||
|
|
||||
|
var shouldIgnore = function() { return false; }; |
||||
|
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/; |
||||
|
function parseLineInfo(line) { |
||||
|
var matches = line.match(parseLineInfoRegex); |
||||
|
if (matches) { |
||||
|
return { |
||||
|
fileName: matches[1], |
||||
|
line: parseInt(matches[2], 10) |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function setBounds(firstLineError, lastLineError) { |
||||
|
if (!longStackTracesIsSupported()) return; |
||||
|
var firstStackLines = firstLineError.stack.split("\n"); |
||||
|
var lastStackLines = lastLineError.stack.split("\n"); |
||||
|
var firstIndex = -1; |
||||
|
var lastIndex = -1; |
||||
|
var firstFileName; |
||||
|
var lastFileName; |
||||
|
for (var i = 0; i < firstStackLines.length; ++i) { |
||||
|
var result = parseLineInfo(firstStackLines[i]); |
||||
|
if (result) { |
||||
|
firstFileName = result.fileName; |
||||
|
firstIndex = result.line; |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
for (var i = 0; i < lastStackLines.length; ++i) { |
||||
|
var result = parseLineInfo(lastStackLines[i]); |
||||
|
if (result) { |
||||
|
lastFileName = result.fileName; |
||||
|
lastIndex = result.line; |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName || |
||||
|
firstFileName !== lastFileName || firstIndex >= lastIndex) { |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
shouldIgnore = function(line) { |
||||
|
if (bluebirdFramePattern.test(line)) return true; |
||||
|
var info = parseLineInfo(line); |
||||
|
if (info) { |
||||
|
if (info.fileName === firstFileName && |
||||
|
(firstIndex <= info.line && info.line <= lastIndex)) { |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
function CapturedTrace(parent) { |
||||
|
this._parent = parent; |
||||
|
this._promisesCreated = 0; |
||||
|
var length = this._length = 1 + (parent === undefined ? 0 : parent._length); |
||||
|
captureStackTrace(this, CapturedTrace); |
||||
|
if (length > 32) this.uncycle(); |
||||
|
} |
||||
|
util.inherits(CapturedTrace, Error); |
||||
|
Context.CapturedTrace = CapturedTrace; |
||||
|
|
||||
|
CapturedTrace.prototype.uncycle = function() { |
||||
|
var length = this._length; |
||||
|
if (length < 2) return; |
||||
|
var nodes = []; |
||||
|
var stackToIndex = {}; |
||||
|
|
||||
|
for (var i = 0, node = this; node !== undefined; ++i) { |
||||
|
nodes.push(node); |
||||
|
node = node._parent; |
||||
|
} |
||||
|
length = this._length = i; |
||||
|
for (var i = length - 1; i >= 0; --i) { |
||||
|
var stack = nodes[i].stack; |
||||
|
if (stackToIndex[stack] === undefined) { |
||||
|
stackToIndex[stack] = i; |
||||
|
} |
||||
|
} |
||||
|
for (var i = 0; i < length; ++i) { |
||||
|
var currentStack = nodes[i].stack; |
||||
|
var index = stackToIndex[currentStack]; |
||||
|
if (index !== undefined && index !== i) { |
||||
|
if (index > 0) { |
||||
|
nodes[index - 1]._parent = undefined; |
||||
|
nodes[index - 1]._length = 1; |
||||
|
} |
||||
|
nodes[i]._parent = undefined; |
||||
|
nodes[i]._length = 1; |
||||
|
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this; |
||||
|
|
||||
|
if (index < length - 1) { |
||||
|
cycleEdgeNode._parent = nodes[index + 1]; |
||||
|
cycleEdgeNode._parent.uncycle(); |
||||
|
cycleEdgeNode._length = |
||||
|
cycleEdgeNode._parent._length + 1; |
||||
|
} else { |
||||
|
cycleEdgeNode._parent = undefined; |
||||
|
cycleEdgeNode._length = 1; |
||||
|
} |
||||
|
var currentChildLength = cycleEdgeNode._length + 1; |
||||
|
for (var j = i - 2; j >= 0; --j) { |
||||
|
nodes[j]._length = currentChildLength; |
||||
|
currentChildLength++; |
||||
|
} |
||||
|
return; |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
CapturedTrace.prototype.attachExtraTrace = function(error) { |
||||
|
if (error.__stackCleaned__) return; |
||||
|
this.uncycle(); |
||||
|
var parsed = parseStackAndMessage(error); |
||||
|
var message = parsed.message; |
||||
|
var stacks = [parsed.stack]; |
||||
|
|
||||
|
var trace = this; |
||||
|
while (trace !== undefined) { |
||||
|
stacks.push(cleanStack(trace.stack.split("\n"))); |
||||
|
trace = trace._parent; |
||||
|
} |
||||
|
removeCommonRoots(stacks); |
||||
|
removeDuplicateOrEmptyJumps(stacks); |
||||
|
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks)); |
||||
|
util.notEnumerableProp(error, "__stackCleaned__", true); |
||||
|
}; |
||||
|
|
||||
|
var captureStackTrace = (function stackDetection() { |
||||
|
var v8stackFramePattern = /^\s*at\s*/; |
||||
|
var v8stackFormatter = function(stack, error) { |
||||
|
if (typeof stack === "string") return stack; |
||||
|
|
||||
|
if (error.name !== undefined && |
||||
|
error.message !== undefined) { |
||||
|
return error.toString(); |
||||
|
} |
||||
|
return formatNonError(error); |
||||
|
}; |
||||
|
|
||||
|
if (typeof Error.stackTraceLimit === "number" && |
||||
|
typeof Error.captureStackTrace === "function") { |
||||
|
Error.stackTraceLimit += 6; |
||||
|
stackFramePattern = v8stackFramePattern; |
||||
|
formatStack = v8stackFormatter; |
||||
|
var captureStackTrace = Error.captureStackTrace; |
||||
|
|
||||
|
shouldIgnore = function(line) { |
||||
|
return bluebirdFramePattern.test(line); |
||||
|
}; |
||||
|
return function(receiver, ignoreUntil) { |
||||
|
Error.stackTraceLimit += 6; |
||||
|
captureStackTrace(receiver, ignoreUntil); |
||||
|
Error.stackTraceLimit -= 6; |
||||
|
}; |
||||
|
} |
||||
|
var err = new Error(); |
||||
|
|
||||
|
if (typeof err.stack === "string" && |
||||
|
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) { |
||||
|
stackFramePattern = /@/; |
||||
|
formatStack = v8stackFormatter; |
||||
|
indentStackFrames = true; |
||||
|
return function captureStackTrace(o) { |
||||
|
o.stack = new Error().stack; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
var hasStackAfterThrow; |
||||
|
try { throw new Error(); } |
||||
|
catch(e) { |
||||
|
hasStackAfterThrow = ("stack" in e); |
||||
|
} |
||||
|
if (!("stack" in err) && hasStackAfterThrow && |
||||
|
typeof Error.stackTraceLimit === "number") { |
||||
|
stackFramePattern = v8stackFramePattern; |
||||
|
formatStack = v8stackFormatter; |
||||
|
return function captureStackTrace(o) { |
||||
|
Error.stackTraceLimit += 6; |
||||
|
try { throw new Error(); } |
||||
|
catch(e) { o.stack = e.stack; } |
||||
|
Error.stackTraceLimit -= 6; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
formatStack = function(stack, error) { |
||||
|
if (typeof stack === "string") return stack; |
||||
|
|
||||
|
if ((typeof error === "object" || |
||||
|
typeof error === "function") && |
||||
|
error.name !== undefined && |
||||
|
error.message !== undefined) { |
||||
|
return error.toString(); |
||||
|
} |
||||
|
return formatNonError(error); |
||||
|
}; |
||||
|
|
||||
|
return null; |
||||
|
|
||||
|
})([]); |
||||
|
|
||||
|
if (typeof console !== "undefined" && typeof console.warn !== "undefined") { |
||||
|
printWarning = function (message) { |
||||
|
console.warn(message); |
||||
|
}; |
||||
|
if (util.isNode && process.stderr.isTTY) { |
||||
|
printWarning = function(message, isSoft) { |
||||
|
var color = isSoft ? "\u001b[33m" : "\u001b[31m"; |
||||
|
console.warn(color + message + "\u001b[0m\n"); |
||||
|
}; |
||||
|
} else if (!util.isNode && typeof (new Error().stack) === "string") { |
||||
|
printWarning = function(message, isSoft) { |
||||
|
console.warn("%c" + message, |
||||
|
isSoft ? "color: darkorange" : "color: red"); |
||||
|
}; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var config = { |
||||
|
warnings: warnings, |
||||
|
longStackTraces: false, |
||||
|
cancellation: false, |
||||
|
monitoring: false |
||||
|
}; |
||||
|
|
||||
|
if (longStackTraces) Promise.longStackTraces(); |
||||
|
|
||||
|
return { |
||||
|
longStackTraces: function() { |
||||
|
return config.longStackTraces; |
||||
|
}, |
||||
|
warnings: function() { |
||||
|
return config.warnings; |
||||
|
}, |
||||
|
cancellation: function() { |
||||
|
return config.cancellation; |
||||
|
}, |
||||
|
monitoring: function() { |
||||
|
return config.monitoring; |
||||
|
}, |
||||
|
propagateFromFunction: function() { |
||||
|
return propagateFromFunction; |
||||
|
}, |
||||
|
boundValueFunction: function() { |
||||
|
return boundValueFunction; |
||||
|
}, |
||||
|
checkForgottenReturns: checkForgottenReturns, |
||||
|
setBounds: setBounds, |
||||
|
warn: warn, |
||||
|
deprecated: deprecated, |
||||
|
CapturedTrace: CapturedTrace, |
||||
|
fireDomEvent: fireDomEvent, |
||||
|
fireGlobalEvent: fireGlobalEvent |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,46 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise) { |
||||
|
function returner() { |
||||
|
return this.value; |
||||
|
} |
||||
|
function thrower() { |
||||
|
throw this.reason; |
||||
|
} |
||||
|
|
||||
|
Promise.prototype["return"] = |
||||
|
Promise.prototype.thenReturn = function (value) { |
||||
|
if (value instanceof Promise) value.suppressUnhandledRejections(); |
||||
|
return this._then( |
||||
|
returner, undefined, undefined, {value: value}, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype["throw"] = |
||||
|
Promise.prototype.thenThrow = function (reason) { |
||||
|
return this._then( |
||||
|
thrower, undefined, undefined, {reason: reason}, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.catchThrow = function (reason) { |
||||
|
if (arguments.length <= 1) { |
||||
|
return this._then( |
||||
|
undefined, thrower, undefined, {reason: reason}, undefined); |
||||
|
} else { |
||||
|
var _reason = arguments[1]; |
||||
|
var handler = function() {throw _reason;}; |
||||
|
return this.caught(reason, handler); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.catchReturn = function (value) { |
||||
|
if (arguments.length <= 1) { |
||||
|
if (value instanceof Promise) value.suppressUnhandledRejections(); |
||||
|
return this._then( |
||||
|
undefined, returner, undefined, {value: value}, undefined); |
||||
|
} else { |
||||
|
var _value = arguments[1]; |
||||
|
if (_value instanceof Promise) _value.suppressUnhandledRejections(); |
||||
|
var handler = function() {return _value;}; |
||||
|
return this.caught(value, handler); |
||||
|
} |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,30 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL) { |
||||
|
var PromiseReduce = Promise.reduce; |
||||
|
var PromiseAll = Promise.all; |
||||
|
|
||||
|
function promiseAllThis() { |
||||
|
return PromiseAll(this); |
||||
|
} |
||||
|
|
||||
|
function PromiseMapSeries(promises, fn) { |
||||
|
return PromiseReduce(promises, fn, INTERNAL, INTERNAL); |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.each = function (fn) { |
||||
|
return PromiseReduce(this, fn, INTERNAL, 0) |
||||
|
._then(promiseAllThis, undefined, undefined, this, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.mapSeries = function (fn) { |
||||
|
return PromiseReduce(this, fn, INTERNAL, INTERNAL); |
||||
|
}; |
||||
|
|
||||
|
Promise.each = function (promises, fn) { |
||||
|
return PromiseReduce(promises, fn, INTERNAL, 0) |
||||
|
._then(promiseAllThis, undefined, undefined, promises, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.mapSeries = PromiseMapSeries; |
||||
|
}; |
||||
|
|
@ -0,0 +1,116 @@ |
|||||
|
"use strict"; |
||||
|
var es5 = require("./es5"); |
||||
|
var Objectfreeze = es5.freeze; |
||||
|
var util = require("./util"); |
||||
|
var inherits = util.inherits; |
||||
|
var notEnumerableProp = util.notEnumerableProp; |
||||
|
|
||||
|
function subError(nameProperty, defaultMessage) { |
||||
|
function SubError(message) { |
||||
|
if (!(this instanceof SubError)) return new SubError(message); |
||||
|
notEnumerableProp(this, "message", |
||||
|
typeof message === "string" ? message : defaultMessage); |
||||
|
notEnumerableProp(this, "name", nameProperty); |
||||
|
if (Error.captureStackTrace) { |
||||
|
Error.captureStackTrace(this, this.constructor); |
||||
|
} else { |
||||
|
Error.call(this); |
||||
|
} |
||||
|
} |
||||
|
inherits(SubError, Error); |
||||
|
return SubError; |
||||
|
} |
||||
|
|
||||
|
var _TypeError, _RangeError; |
||||
|
var Warning = subError("Warning", "warning"); |
||||
|
var CancellationError = subError("CancellationError", "cancellation error"); |
||||
|
var TimeoutError = subError("TimeoutError", "timeout error"); |
||||
|
var AggregateError = subError("AggregateError", "aggregate error"); |
||||
|
try { |
||||
|
_TypeError = TypeError; |
||||
|
_RangeError = RangeError; |
||||
|
} catch(e) { |
||||
|
_TypeError = subError("TypeError", "type error"); |
||||
|
_RangeError = subError("RangeError", "range error"); |
||||
|
} |
||||
|
|
||||
|
var methods = ("join pop push shift unshift slice filter forEach some " + |
||||
|
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" "); |
||||
|
|
||||
|
for (var i = 0; i < methods.length; ++i) { |
||||
|
if (typeof Array.prototype[methods[i]] === "function") { |
||||
|
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]]; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
es5.defineProperty(AggregateError.prototype, "length", { |
||||
|
value: 0, |
||||
|
configurable: false, |
||||
|
writable: true, |
||||
|
enumerable: true |
||||
|
}); |
||||
|
AggregateError.prototype["isOperational"] = true; |
||||
|
var level = 0; |
||||
|
AggregateError.prototype.toString = function() { |
||||
|
var indent = Array(level * 4 + 1).join(" "); |
||||
|
var ret = "\n" + indent + "AggregateError of:" + "\n"; |
||||
|
level++; |
||||
|
indent = Array(level * 4 + 1).join(" "); |
||||
|
for (var i = 0; i < this.length; ++i) { |
||||
|
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + ""; |
||||
|
var lines = str.split("\n"); |
||||
|
for (var j = 0; j < lines.length; ++j) { |
||||
|
lines[j] = indent + lines[j]; |
||||
|
} |
||||
|
str = lines.join("\n"); |
||||
|
ret += str + "\n"; |
||||
|
} |
||||
|
level--; |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
function OperationalError(message) { |
||||
|
if (!(this instanceof OperationalError)) |
||||
|
return new OperationalError(message); |
||||
|
notEnumerableProp(this, "name", "OperationalError"); |
||||
|
notEnumerableProp(this, "message", message); |
||||
|
this.cause = message; |
||||
|
this["isOperational"] = true; |
||||
|
|
||||
|
if (message instanceof Error) { |
||||
|
notEnumerableProp(this, "message", message.message); |
||||
|
notEnumerableProp(this, "stack", message.stack); |
||||
|
} else if (Error.captureStackTrace) { |
||||
|
Error.captureStackTrace(this, this.constructor); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
inherits(OperationalError, Error); |
||||
|
|
||||
|
var errorTypes = Error["__BluebirdErrorTypes__"]; |
||||
|
if (!errorTypes) { |
||||
|
errorTypes = Objectfreeze({ |
||||
|
CancellationError: CancellationError, |
||||
|
TimeoutError: TimeoutError, |
||||
|
OperationalError: OperationalError, |
||||
|
RejectionError: OperationalError, |
||||
|
AggregateError: AggregateError |
||||
|
}); |
||||
|
es5.defineProperty(Error, "__BluebirdErrorTypes__", { |
||||
|
value: errorTypes, |
||||
|
writable: false, |
||||
|
enumerable: false, |
||||
|
configurable: false |
||||
|
}); |
||||
|
} |
||||
|
|
||||
|
module.exports = { |
||||
|
Error: Error, |
||||
|
TypeError: _TypeError, |
||||
|
RangeError: _RangeError, |
||||
|
CancellationError: errorTypes.CancellationError, |
||||
|
OperationalError: errorTypes.OperationalError, |
||||
|
TimeoutError: errorTypes.TimeoutError, |
||||
|
AggregateError: errorTypes.AggregateError, |
||||
|
Warning: Warning |
||||
|
}; |
@ -0,0 +1,80 @@ |
|||||
|
var isES5 = (function(){ |
||||
|
"use strict"; |
||||
|
return this === undefined; |
||||
|
})(); |
||||
|
|
||||
|
if (isES5) { |
||||
|
module.exports = { |
||||
|
freeze: Object.freeze, |
||||
|
defineProperty: Object.defineProperty, |
||||
|
getDescriptor: Object.getOwnPropertyDescriptor, |
||||
|
keys: Object.keys, |
||||
|
names: Object.getOwnPropertyNames, |
||||
|
getPrototypeOf: Object.getPrototypeOf, |
||||
|
isArray: Array.isArray, |
||||
|
isES5: isES5, |
||||
|
propertyIsWritable: function(obj, prop) { |
||||
|
var descriptor = Object.getOwnPropertyDescriptor(obj, prop); |
||||
|
return !!(!descriptor || descriptor.writable || descriptor.set); |
||||
|
} |
||||
|
}; |
||||
|
} else { |
||||
|
var has = {}.hasOwnProperty; |
||||
|
var str = {}.toString; |
||||
|
var proto = {}.constructor.prototype; |
||||
|
|
||||
|
var ObjectKeys = function (o) { |
||||
|
var ret = []; |
||||
|
for (var key in o) { |
||||
|
if (has.call(o, key)) { |
||||
|
ret.push(key); |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
var ObjectGetDescriptor = function(o, key) { |
||||
|
return {value: o[key]}; |
||||
|
}; |
||||
|
|
||||
|
var ObjectDefineProperty = function (o, key, desc) { |
||||
|
o[key] = desc.value; |
||||
|
return o; |
||||
|
}; |
||||
|
|
||||
|
var ObjectFreeze = function (obj) { |
||||
|
return obj; |
||||
|
}; |
||||
|
|
||||
|
var ObjectGetPrototypeOf = function (obj) { |
||||
|
try { |
||||
|
return Object(obj).constructor.prototype; |
||||
|
} |
||||
|
catch (e) { |
||||
|
return proto; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
var ArrayIsArray = function (obj) { |
||||
|
try { |
||||
|
return str.call(obj) === "[object Array]"; |
||||
|
} |
||||
|
catch(e) { |
||||
|
return false; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
module.exports = { |
||||
|
isArray: ArrayIsArray, |
||||
|
keys: ObjectKeys, |
||||
|
names: ObjectKeys, |
||||
|
defineProperty: ObjectDefineProperty, |
||||
|
getDescriptor: ObjectGetDescriptor, |
||||
|
freeze: ObjectFreeze, |
||||
|
getPrototypeOf: ObjectGetPrototypeOf, |
||||
|
isES5: isES5, |
||||
|
propertyIsWritable: function() { |
||||
|
return true; |
||||
|
} |
||||
|
}; |
||||
|
} |
@ -0,0 +1,12 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL) { |
||||
|
var PromiseMap = Promise.map; |
||||
|
|
||||
|
Promise.prototype.filter = function (fn, options) { |
||||
|
return PromiseMap(this, fn, options, INTERNAL); |
||||
|
}; |
||||
|
|
||||
|
Promise.filter = function (promises, fn, options) { |
||||
|
return PromiseMap(promises, fn, options, INTERNAL); |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,146 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) { |
||||
|
var util = require("./util"); |
||||
|
var CancellationError = Promise.CancellationError; |
||||
|
var errorObj = util.errorObj; |
||||
|
var catchFilter = require("./catch_filter")(NEXT_FILTER); |
||||
|
|
||||
|
function PassThroughHandlerContext(promise, type, handler) { |
||||
|
this.promise = promise; |
||||
|
this.type = type; |
||||
|
this.handler = handler; |
||||
|
this.called = false; |
||||
|
this.cancelPromise = null; |
||||
|
} |
||||
|
|
||||
|
PassThroughHandlerContext.prototype.isFinallyHandler = function() { |
||||
|
return this.type === 0; |
||||
|
}; |
||||
|
|
||||
|
function FinallyHandlerCancelReaction(finallyHandler) { |
||||
|
this.finallyHandler = finallyHandler; |
||||
|
} |
||||
|
|
||||
|
FinallyHandlerCancelReaction.prototype._resultCancelled = function() { |
||||
|
checkCancel(this.finallyHandler); |
||||
|
}; |
||||
|
|
||||
|
function checkCancel(ctx, reason) { |
||||
|
if (ctx.cancelPromise != null) { |
||||
|
if (arguments.length > 1) { |
||||
|
ctx.cancelPromise._reject(reason); |
||||
|
} else { |
||||
|
ctx.cancelPromise._cancel(); |
||||
|
} |
||||
|
ctx.cancelPromise = null; |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
} |
||||
|
|
||||
|
function succeed() { |
||||
|
return finallyHandler.call(this, this.promise._target()._settledValue()); |
||||
|
} |
||||
|
function fail(reason) { |
||||
|
if (checkCancel(this, reason)) return; |
||||
|
errorObj.e = reason; |
||||
|
return errorObj; |
||||
|
} |
||||
|
function finallyHandler(reasonOrValue) { |
||||
|
var promise = this.promise; |
||||
|
var handler = this.handler; |
||||
|
|
||||
|
if (!this.called) { |
||||
|
this.called = true; |
||||
|
var ret = this.isFinallyHandler() |
||||
|
? handler.call(promise._boundValue()) |
||||
|
: handler.call(promise._boundValue(), reasonOrValue); |
||||
|
if (ret === NEXT_FILTER) { |
||||
|
return ret; |
||||
|
} else if (ret !== undefined) { |
||||
|
promise._setReturnedNonUndefined(); |
||||
|
var maybePromise = tryConvertToPromise(ret, promise); |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
if (this.cancelPromise != null) { |
||||
|
if (maybePromise._isCancelled()) { |
||||
|
var reason = |
||||
|
new CancellationError("late cancellation observer"); |
||||
|
promise._attachExtraTrace(reason); |
||||
|
errorObj.e = reason; |
||||
|
return errorObj; |
||||
|
} else if (maybePromise.isPending()) { |
||||
|
maybePromise._attachCancellationCallback( |
||||
|
new FinallyHandlerCancelReaction(this)); |
||||
|
} |
||||
|
} |
||||
|
return maybePromise._then( |
||||
|
succeed, fail, undefined, this, undefined); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (promise.isRejected()) { |
||||
|
checkCancel(this); |
||||
|
errorObj.e = reasonOrValue; |
||||
|
return errorObj; |
||||
|
} else { |
||||
|
checkCancel(this); |
||||
|
return reasonOrValue; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
Promise.prototype._passThrough = function(handler, type, success, fail) { |
||||
|
if (typeof handler !== "function") return this.then(); |
||||
|
return this._then(success, |
||||
|
fail, |
||||
|
undefined, |
||||
|
new PassThroughHandlerContext(this, type, handler), |
||||
|
undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.lastly = |
||||
|
Promise.prototype["finally"] = function (handler) { |
||||
|
return this._passThrough(handler, |
||||
|
0, |
||||
|
finallyHandler, |
||||
|
finallyHandler); |
||||
|
}; |
||||
|
|
||||
|
|
||||
|
Promise.prototype.tap = function (handler) { |
||||
|
return this._passThrough(handler, 1, finallyHandler); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.tapCatch = function (handlerOrPredicate) { |
||||
|
var len = arguments.length; |
||||
|
if(len === 1) { |
||||
|
return this._passThrough(handlerOrPredicate, |
||||
|
1, |
||||
|
undefined, |
||||
|
finallyHandler); |
||||
|
} else { |
||||
|
var catchInstances = new Array(len - 1), |
||||
|
j = 0, i; |
||||
|
for (i = 0; i < len - 1; ++i) { |
||||
|
var item = arguments[i]; |
||||
|
if (util.isObject(item)) { |
||||
|
catchInstances[j++] = item; |
||||
|
} else { |
||||
|
return Promise.reject(new TypeError( |
||||
|
"tapCatch statement predicate: " |
||||
|
+ "expecting an object but got " + util.classString(item) |
||||
|
)); |
||||
|
} |
||||
|
} |
||||
|
catchInstances.length = j; |
||||
|
var handler = arguments[i]; |
||||
|
return this._passThrough(catchFilter(catchInstances, handler, this), |
||||
|
1, |
||||
|
undefined, |
||||
|
finallyHandler); |
||||
|
} |
||||
|
|
||||
|
}; |
||||
|
|
||||
|
return PassThroughHandlerContext; |
||||
|
}; |
@ -0,0 +1,223 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, |
||||
|
apiRejection, |
||||
|
INTERNAL, |
||||
|
tryConvertToPromise, |
||||
|
Proxyable, |
||||
|
debug) { |
||||
|
var errors = require("./errors"); |
||||
|
var TypeError = errors.TypeError; |
||||
|
var util = require("./util"); |
||||
|
var errorObj = util.errorObj; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var yieldHandlers = []; |
||||
|
|
||||
|
function promiseFromYieldHandler(value, yieldHandlers, traceParent) { |
||||
|
for (var i = 0; i < yieldHandlers.length; ++i) { |
||||
|
traceParent._pushContext(); |
||||
|
var result = tryCatch(yieldHandlers[i])(value); |
||||
|
traceParent._popContext(); |
||||
|
if (result === errorObj) { |
||||
|
traceParent._pushContext(); |
||||
|
var ret = Promise.reject(errorObj.e); |
||||
|
traceParent._popContext(); |
||||
|
return ret; |
||||
|
} |
||||
|
var maybePromise = tryConvertToPromise(result, traceParent); |
||||
|
if (maybePromise instanceof Promise) return maybePromise; |
||||
|
} |
||||
|
return null; |
||||
|
} |
||||
|
|
||||
|
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) { |
||||
|
if (debug.cancellation()) { |
||||
|
var internal = new Promise(INTERNAL); |
||||
|
var _finallyPromise = this._finallyPromise = new Promise(INTERNAL); |
||||
|
this._promise = internal.lastly(function() { |
||||
|
return _finallyPromise; |
||||
|
}); |
||||
|
internal._captureStackTrace(); |
||||
|
internal._setOnCancel(this); |
||||
|
} else { |
||||
|
var promise = this._promise = new Promise(INTERNAL); |
||||
|
promise._captureStackTrace(); |
||||
|
} |
||||
|
this._stack = stack; |
||||
|
this._generatorFunction = generatorFunction; |
||||
|
this._receiver = receiver; |
||||
|
this._generator = undefined; |
||||
|
this._yieldHandlers = typeof yieldHandler === "function" |
||||
|
? [yieldHandler].concat(yieldHandlers) |
||||
|
: yieldHandlers; |
||||
|
this._yieldedPromise = null; |
||||
|
this._cancellationPhase = false; |
||||
|
} |
||||
|
util.inherits(PromiseSpawn, Proxyable); |
||||
|
|
||||
|
PromiseSpawn.prototype._isResolved = function() { |
||||
|
return this._promise === null; |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._cleanup = function() { |
||||
|
this._promise = this._generator = null; |
||||
|
if (debug.cancellation() && this._finallyPromise !== null) { |
||||
|
this._finallyPromise._fulfill(); |
||||
|
this._finallyPromise = null; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._promiseCancelled = function() { |
||||
|
if (this._isResolved()) return; |
||||
|
var implementsReturn = typeof this._generator["return"] !== "undefined"; |
||||
|
|
||||
|
var result; |
||||
|
if (!implementsReturn) { |
||||
|
var reason = new Promise.CancellationError( |
||||
|
"generator .return() sentinel"); |
||||
|
Promise.coroutine.returnSentinel = reason; |
||||
|
this._promise._attachExtraTrace(reason); |
||||
|
this._promise._pushContext(); |
||||
|
result = tryCatch(this._generator["throw"]).call(this._generator, |
||||
|
reason); |
||||
|
this._promise._popContext(); |
||||
|
} else { |
||||
|
this._promise._pushContext(); |
||||
|
result = tryCatch(this._generator["return"]).call(this._generator, |
||||
|
undefined); |
||||
|
this._promise._popContext(); |
||||
|
} |
||||
|
this._cancellationPhase = true; |
||||
|
this._yieldedPromise = null; |
||||
|
this._continue(result); |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._promiseFulfilled = function(value) { |
||||
|
this._yieldedPromise = null; |
||||
|
this._promise._pushContext(); |
||||
|
var result = tryCatch(this._generator.next).call(this._generator, value); |
||||
|
this._promise._popContext(); |
||||
|
this._continue(result); |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._promiseRejected = function(reason) { |
||||
|
this._yieldedPromise = null; |
||||
|
this._promise._attachExtraTrace(reason); |
||||
|
this._promise._pushContext(); |
||||
|
var result = tryCatch(this._generator["throw"]) |
||||
|
.call(this._generator, reason); |
||||
|
this._promise._popContext(); |
||||
|
this._continue(result); |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._resultCancelled = function() { |
||||
|
if (this._yieldedPromise instanceof Promise) { |
||||
|
var promise = this._yieldedPromise; |
||||
|
this._yieldedPromise = null; |
||||
|
promise.cancel(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype.promise = function () { |
||||
|
return this._promise; |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._run = function () { |
||||
|
this._generator = this._generatorFunction.call(this._receiver); |
||||
|
this._receiver = |
||||
|
this._generatorFunction = undefined; |
||||
|
this._promiseFulfilled(undefined); |
||||
|
}; |
||||
|
|
||||
|
PromiseSpawn.prototype._continue = function (result) { |
||||
|
var promise = this._promise; |
||||
|
if (result === errorObj) { |
||||
|
this._cleanup(); |
||||
|
if (this._cancellationPhase) { |
||||
|
return promise.cancel(); |
||||
|
} else { |
||||
|
return promise._rejectCallback(result.e, false); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var value = result.value; |
||||
|
if (result.done === true) { |
||||
|
this._cleanup(); |
||||
|
if (this._cancellationPhase) { |
||||
|
return promise.cancel(); |
||||
|
} else { |
||||
|
return promise._resolveCallback(value); |
||||
|
} |
||||
|
} else { |
||||
|
var maybePromise = tryConvertToPromise(value, this._promise); |
||||
|
if (!(maybePromise instanceof Promise)) { |
||||
|
maybePromise = |
||||
|
promiseFromYieldHandler(maybePromise, |
||||
|
this._yieldHandlers, |
||||
|
this._promise); |
||||
|
if (maybePromise === null) { |
||||
|
this._promiseRejected( |
||||
|
new TypeError( |
||||
|
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/MqrFmX\u000a\u000a".replace("%s", String(value)) + |
||||
|
"From coroutine:\u000a" + |
||||
|
this._stack.split("\n").slice(1, -7).join("\n") |
||||
|
) |
||||
|
); |
||||
|
return; |
||||
|
} |
||||
|
} |
||||
|
maybePromise = maybePromise._target(); |
||||
|
var bitField = maybePromise._bitField; |
||||
|
; |
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
this._yieldedPromise = maybePromise; |
||||
|
maybePromise._proxy(this, null); |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
Promise._async.invoke( |
||||
|
this._promiseFulfilled, this, maybePromise._value() |
||||
|
); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
Promise._async.invoke( |
||||
|
this._promiseRejected, this, maybePromise._reason() |
||||
|
); |
||||
|
} else { |
||||
|
this._promiseCancelled(); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.coroutine = function (generatorFunction, options) { |
||||
|
if (typeof generatorFunction !== "function") { |
||||
|
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
var yieldHandler = Object(options).yieldHandler; |
||||
|
var PromiseSpawn$ = PromiseSpawn; |
||||
|
var stack = new Error().stack; |
||||
|
return function () { |
||||
|
var generator = generatorFunction.apply(this, arguments); |
||||
|
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler, |
||||
|
stack); |
||||
|
var ret = spawn.promise(); |
||||
|
spawn._generator = generator; |
||||
|
spawn._promiseFulfilled(undefined); |
||||
|
return ret; |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
Promise.coroutine.addYieldHandler = function(fn) { |
||||
|
if (typeof fn !== "function") { |
||||
|
throw new TypeError("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
yieldHandlers.push(fn); |
||||
|
}; |
||||
|
|
||||
|
Promise.spawn = function (generatorFunction) { |
||||
|
debug.deprecated("Promise.spawn()", "Promise.coroutine()"); |
||||
|
if (typeof generatorFunction !== "function") { |
||||
|
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
var spawn = new PromiseSpawn(generatorFunction, this); |
||||
|
var ret = spawn.promise(); |
||||
|
spawn._run(Promise.spawn); |
||||
|
return ret; |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,168 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = |
||||
|
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, |
||||
|
getDomain) { |
||||
|
var util = require("./util"); |
||||
|
var canEvaluate = util.canEvaluate; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var errorObj = util.errorObj; |
||||
|
var reject; |
||||
|
|
||||
|
if (!false) { |
||||
|
if (canEvaluate) { |
||||
|
var thenCallback = function(i) { |
||||
|
return new Function("value", "holder", " \n\ |
||||
|
'use strict'; \n\ |
||||
|
holder.pIndex = value; \n\ |
||||
|
holder.checkFulfillment(this); \n\ |
||||
|
".replace(/Index/g, i)); |
||||
|
}; |
||||
|
|
||||
|
var promiseSetter = function(i) { |
||||
|
return new Function("promise", "holder", " \n\ |
||||
|
'use strict'; \n\ |
||||
|
holder.pIndex = promise; \n\ |
||||
|
".replace(/Index/g, i)); |
||||
|
}; |
||||
|
|
||||
|
var generateHolderClass = function(total) { |
||||
|
var props = new Array(total); |
||||
|
for (var i = 0; i < props.length; ++i) { |
||||
|
props[i] = "this.p" + (i+1); |
||||
|
} |
||||
|
var assignment = props.join(" = ") + " = null;"; |
||||
|
var cancellationCode= "var promise;\n" + props.map(function(prop) { |
||||
|
return " \n\ |
||||
|
promise = " + prop + "; \n\ |
||||
|
if (promise instanceof Promise) { \n\ |
||||
|
promise.cancel(); \n\ |
||||
|
} \n\ |
||||
|
"; |
||||
|
}).join("\n"); |
||||
|
var passedArguments = props.join(", "); |
||||
|
var name = "Holder$" + total; |
||||
|
|
||||
|
|
||||
|
var code = "return function(tryCatch, errorObj, Promise, async) { \n\ |
||||
|
'use strict'; \n\ |
||||
|
function [TheName](fn) { \n\ |
||||
|
[TheProperties] \n\ |
||||
|
this.fn = fn; \n\ |
||||
|
this.asyncNeeded = true; \n\ |
||||
|
this.now = 0; \n\ |
||||
|
} \n\ |
||||
|
\n\ |
||||
|
[TheName].prototype._callFunction = function(promise) { \n\ |
||||
|
promise._pushContext(); \n\ |
||||
|
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\ |
||||
|
promise._popContext(); \n\ |
||||
|
if (ret === errorObj) { \n\ |
||||
|
promise._rejectCallback(ret.e, false); \n\ |
||||
|
} else { \n\ |
||||
|
promise._resolveCallback(ret); \n\ |
||||
|
} \n\ |
||||
|
}; \n\ |
||||
|
\n\ |
||||
|
[TheName].prototype.checkFulfillment = function(promise) { \n\ |
||||
|
var now = ++this.now; \n\ |
||||
|
if (now === [TheTotal]) { \n\ |
||||
|
if (this.asyncNeeded) { \n\ |
||||
|
async.invoke(this._callFunction, this, promise); \n\ |
||||
|
} else { \n\ |
||||
|
this._callFunction(promise); \n\ |
||||
|
} \n\ |
||||
|
\n\ |
||||
|
} \n\ |
||||
|
}; \n\ |
||||
|
\n\ |
||||
|
[TheName].prototype._resultCancelled = function() { \n\ |
||||
|
[CancellationCode] \n\ |
||||
|
}; \n\ |
||||
|
\n\ |
||||
|
return [TheName]; \n\ |
||||
|
}(tryCatch, errorObj, Promise, async); \n\ |
||||
|
"; |
||||
|
|
||||
|
code = code.replace(/\[TheName\]/g, name) |
||||
|
.replace(/\[TheTotal\]/g, total) |
||||
|
.replace(/\[ThePassedArguments\]/g, passedArguments) |
||||
|
.replace(/\[TheProperties\]/g, assignment) |
||||
|
.replace(/\[CancellationCode\]/g, cancellationCode); |
||||
|
|
||||
|
return new Function("tryCatch", "errorObj", "Promise", "async", code) |
||||
|
(tryCatch, errorObj, Promise, async); |
||||
|
}; |
||||
|
|
||||
|
var holderClasses = []; |
||||
|
var thenCallbacks = []; |
||||
|
var promiseSetters = []; |
||||
|
|
||||
|
for (var i = 0; i < 8; ++i) { |
||||
|
holderClasses.push(generateHolderClass(i + 1)); |
||||
|
thenCallbacks.push(thenCallback(i + 1)); |
||||
|
promiseSetters.push(promiseSetter(i + 1)); |
||||
|
} |
||||
|
|
||||
|
reject = function (reason) { |
||||
|
this._reject(reason); |
||||
|
}; |
||||
|
}} |
||||
|
|
||||
|
Promise.join = function () { |
||||
|
var last = arguments.length - 1; |
||||
|
var fn; |
||||
|
if (last > 0 && typeof arguments[last] === "function") { |
||||
|
fn = arguments[last]; |
||||
|
if (!false) { |
||||
|
if (last <= 8 && canEvaluate) { |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
var HolderClass = holderClasses[last - 1]; |
||||
|
var holder = new HolderClass(fn); |
||||
|
var callbacks = thenCallbacks; |
||||
|
|
||||
|
for (var i = 0; i < last; ++i) { |
||||
|
var maybePromise = tryConvertToPromise(arguments[i], ret); |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
maybePromise = maybePromise._target(); |
||||
|
var bitField = maybePromise._bitField; |
||||
|
; |
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
maybePromise._then(callbacks[i], reject, |
||||
|
undefined, ret, holder); |
||||
|
promiseSetters[i](maybePromise, holder); |
||||
|
holder.asyncNeeded = false; |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
callbacks[i].call(ret, |
||||
|
maybePromise._value(), holder); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
ret._reject(maybePromise._reason()); |
||||
|
} else { |
||||
|
ret._cancel(); |
||||
|
} |
||||
|
} else { |
||||
|
callbacks[i].call(ret, maybePromise, holder); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (!ret._isFateSealed()) { |
||||
|
if (holder.asyncNeeded) { |
||||
|
var domain = getDomain(); |
||||
|
if (domain !== null) { |
||||
|
holder.fn = util.domainBind(domain, holder.fn); |
||||
|
} |
||||
|
} |
||||
|
ret._setAsyncGuaranteed(); |
||||
|
ret._setOnCancel(holder); |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}; |
||||
|
if (fn) args.pop(); |
||||
|
var ret = new PromiseArray(args).promise(); |
||||
|
return fn !== undefined ? ret.spread(fn) : ret; |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,168 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, |
||||
|
PromiseArray, |
||||
|
apiRejection, |
||||
|
tryConvertToPromise, |
||||
|
INTERNAL, |
||||
|
debug) { |
||||
|
var getDomain = Promise._getDomain; |
||||
|
var util = require("./util"); |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var errorObj = util.errorObj; |
||||
|
var async = Promise._async; |
||||
|
|
||||
|
function MappingPromiseArray(promises, fn, limit, _filter) { |
||||
|
this.constructor$(promises); |
||||
|
this._promise._captureStackTrace(); |
||||
|
var domain = getDomain(); |
||||
|
this._callback = domain === null ? fn : util.domainBind(domain, fn); |
||||
|
this._preservedValues = _filter === INTERNAL |
||||
|
? new Array(this.length()) |
||||
|
: null; |
||||
|
this._limit = limit; |
||||
|
this._inFlight = 0; |
||||
|
this._queue = []; |
||||
|
async.invoke(this._asyncInit, this, undefined); |
||||
|
} |
||||
|
util.inherits(MappingPromiseArray, PromiseArray); |
||||
|
|
||||
|
MappingPromiseArray.prototype._asyncInit = function() { |
||||
|
this._init$(undefined, -2); |
||||
|
}; |
||||
|
|
||||
|
MappingPromiseArray.prototype._init = function () {}; |
||||
|
|
||||
|
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) { |
||||
|
var values = this._values; |
||||
|
var length = this.length(); |
||||
|
var preservedValues = this._preservedValues; |
||||
|
var limit = this._limit; |
||||
|
|
||||
|
if (index < 0) { |
||||
|
index = (index * -1) - 1; |
||||
|
values[index] = value; |
||||
|
if (limit >= 1) { |
||||
|
this._inFlight--; |
||||
|
this._drainQueue(); |
||||
|
if (this._isResolved()) return true; |
||||
|
} |
||||
|
} else { |
||||
|
if (limit >= 1 && this._inFlight >= limit) { |
||||
|
values[index] = value; |
||||
|
this._queue.push(index); |
||||
|
return false; |
||||
|
} |
||||
|
if (preservedValues !== null) preservedValues[index] = value; |
||||
|
|
||||
|
var promise = this._promise; |
||||
|
var callback = this._callback; |
||||
|
var receiver = promise._boundValue(); |
||||
|
promise._pushContext(); |
||||
|
var ret = tryCatch(callback).call(receiver, value, index, length); |
||||
|
var promiseCreated = promise._popContext(); |
||||
|
debug.checkForgottenReturns( |
||||
|
ret, |
||||
|
promiseCreated, |
||||
|
preservedValues !== null ? "Promise.filter" : "Promise.map", |
||||
|
promise |
||||
|
); |
||||
|
if (ret === errorObj) { |
||||
|
this._reject(ret.e); |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
var maybePromise = tryConvertToPromise(ret, this._promise); |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
maybePromise = maybePromise._target(); |
||||
|
var bitField = maybePromise._bitField; |
||||
|
; |
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
if (limit >= 1) this._inFlight++; |
||||
|
values[index] = maybePromise; |
||||
|
maybePromise._proxy(this, (index + 1) * -1); |
||||
|
return false; |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
ret = maybePromise._value(); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
this._reject(maybePromise._reason()); |
||||
|
return true; |
||||
|
} else { |
||||
|
this._cancel(); |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
values[index] = ret; |
||||
|
} |
||||
|
var totalResolved = ++this._totalResolved; |
||||
|
if (totalResolved >= length) { |
||||
|
if (preservedValues !== null) { |
||||
|
this._filter(values, preservedValues); |
||||
|
} else { |
||||
|
this._resolve(values); |
||||
|
} |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
MappingPromiseArray.prototype._drainQueue = function () { |
||||
|
var queue = this._queue; |
||||
|
var limit = this._limit; |
||||
|
var values = this._values; |
||||
|
while (queue.length > 0 && this._inFlight < limit) { |
||||
|
if (this._isResolved()) return; |
||||
|
var index = queue.pop(); |
||||
|
this._promiseFulfilled(values[index], index); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
MappingPromiseArray.prototype._filter = function (booleans, values) { |
||||
|
var len = values.length; |
||||
|
var ret = new Array(len); |
||||
|
var j = 0; |
||||
|
for (var i = 0; i < len; ++i) { |
||||
|
if (booleans[i]) ret[j++] = values[i]; |
||||
|
} |
||||
|
ret.length = j; |
||||
|
this._resolve(ret); |
||||
|
}; |
||||
|
|
||||
|
MappingPromiseArray.prototype.preservedValues = function () { |
||||
|
return this._preservedValues; |
||||
|
}; |
||||
|
|
||||
|
function map(promises, fn, options, _filter) { |
||||
|
if (typeof fn !== "function") { |
||||
|
return apiRejection("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
|
||||
|
var limit = 0; |
||||
|
if (options !== undefined) { |
||||
|
if (typeof options === "object" && options !== null) { |
||||
|
if (typeof options.concurrency !== "number") { |
||||
|
return Promise.reject( |
||||
|
new TypeError("'concurrency' must be a number but it is " + |
||||
|
util.classString(options.concurrency))); |
||||
|
} |
||||
|
limit = options.concurrency; |
||||
|
} else { |
||||
|
return Promise.reject(new TypeError( |
||||
|
"options argument must be an object but it is " + |
||||
|
util.classString(options))); |
||||
|
} |
||||
|
} |
||||
|
limit = typeof limit === "number" && |
||||
|
isFinite(limit) && limit >= 1 ? limit : 0; |
||||
|
return new MappingPromiseArray(promises, fn, limit, _filter).promise(); |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.map = function (fn, options) { |
||||
|
return map(this, fn, options, null); |
||||
|
}; |
||||
|
|
||||
|
Promise.map = function (promises, fn, options, _filter) { |
||||
|
return map(promises, fn, options, _filter); |
||||
|
}; |
||||
|
|
||||
|
|
||||
|
}; |
@ -0,0 +1,55 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = |
||||
|
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) { |
||||
|
var util = require("./util"); |
||||
|
var tryCatch = util.tryCatch; |
||||
|
|
||||
|
Promise.method = function (fn) { |
||||
|
if (typeof fn !== "function") { |
||||
|
throw new Promise.TypeError("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
return function () { |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
ret._pushContext(); |
||||
|
var value = tryCatch(fn).apply(this, arguments); |
||||
|
var promiseCreated = ret._popContext(); |
||||
|
debug.checkForgottenReturns( |
||||
|
value, promiseCreated, "Promise.method", ret); |
||||
|
ret._resolveFromSyncValue(value); |
||||
|
return ret; |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
Promise.attempt = Promise["try"] = function (fn) { |
||||
|
if (typeof fn !== "function") { |
||||
|
return apiRejection("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
ret._pushContext(); |
||||
|
var value; |
||||
|
if (arguments.length > 1) { |
||||
|
debug.deprecated("calling Promise.try with more than 1 argument"); |
||||
|
var arg = arguments[1]; |
||||
|
var ctx = arguments[2]; |
||||
|
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg) |
||||
|
: tryCatch(fn).call(ctx, arg); |
||||
|
} else { |
||||
|
value = tryCatch(fn)(); |
||||
|
} |
||||
|
var promiseCreated = ret._popContext(); |
||||
|
debug.checkForgottenReturns( |
||||
|
value, promiseCreated, "Promise.try", ret); |
||||
|
ret._resolveFromSyncValue(value); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._resolveFromSyncValue = function (value) { |
||||
|
if (value === util.errorObj) { |
||||
|
this._rejectCallback(value.e, false); |
||||
|
} else { |
||||
|
this._resolveCallback(value, true); |
||||
|
} |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,51 @@ |
|||||
|
"use strict"; |
||||
|
var util = require("./util"); |
||||
|
var maybeWrapAsError = util.maybeWrapAsError; |
||||
|
var errors = require("./errors"); |
||||
|
var OperationalError = errors.OperationalError; |
||||
|
var es5 = require("./es5"); |
||||
|
|
||||
|
function isUntypedError(obj) { |
||||
|
return obj instanceof Error && |
||||
|
es5.getPrototypeOf(obj) === Error.prototype; |
||||
|
} |
||||
|
|
||||
|
var rErrorKey = /^(?:name|message|stack|cause)$/; |
||||
|
function wrapAsOperationalError(obj) { |
||||
|
var ret; |
||||
|
if (isUntypedError(obj)) { |
||||
|
ret = new OperationalError(obj); |
||||
|
ret.name = obj.name; |
||||
|
ret.message = obj.message; |
||||
|
ret.stack = obj.stack; |
||||
|
var keys = es5.keys(obj); |
||||
|
for (var i = 0; i < keys.length; ++i) { |
||||
|
var key = keys[i]; |
||||
|
if (!rErrorKey.test(key)) { |
||||
|
ret[key] = obj[key]; |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
util.markAsOriginatingFromRejection(obj); |
||||
|
return obj; |
||||
|
} |
||||
|
|
||||
|
function nodebackForPromise(promise, multiArgs) { |
||||
|
return function(err, value) { |
||||
|
if (promise === null) return; |
||||
|
if (err) { |
||||
|
var wrapped = wrapAsOperationalError(maybeWrapAsError(err)); |
||||
|
promise._attachExtraTrace(wrapped); |
||||
|
promise._reject(wrapped); |
||||
|
} else if (!multiArgs) { |
||||
|
promise._fulfill(value); |
||||
|
} else { |
||||
|
var $_len = arguments.length;var args = new Array(Math.max($_len - 1, 0)); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}; |
||||
|
promise._fulfill(args); |
||||
|
} |
||||
|
promise = null; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
module.exports = nodebackForPromise; |
@ -0,0 +1,58 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise) { |
||||
|
var util = require("./util"); |
||||
|
var async = Promise._async; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var errorObj = util.errorObj; |
||||
|
|
||||
|
function spreadAdapter(val, nodeback) { |
||||
|
var promise = this; |
||||
|
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback); |
||||
|
var ret = |
||||
|
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val)); |
||||
|
if (ret === errorObj) { |
||||
|
async.throwLater(ret.e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function successAdapter(val, nodeback) { |
||||
|
var promise = this; |
||||
|
var receiver = promise._boundValue(); |
||||
|
var ret = val === undefined |
||||
|
? tryCatch(nodeback).call(receiver, null) |
||||
|
: tryCatch(nodeback).call(receiver, null, val); |
||||
|
if (ret === errorObj) { |
||||
|
async.throwLater(ret.e); |
||||
|
} |
||||
|
} |
||||
|
function errorAdapter(reason, nodeback) { |
||||
|
var promise = this; |
||||
|
if (!reason) { |
||||
|
var newReason = new Error(reason + ""); |
||||
|
newReason.cause = reason; |
||||
|
reason = newReason; |
||||
|
} |
||||
|
var ret = tryCatch(nodeback).call(promise._boundValue(), reason); |
||||
|
if (ret === errorObj) { |
||||
|
async.throwLater(ret.e); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback, |
||||
|
options) { |
||||
|
if (typeof nodeback == "function") { |
||||
|
var adapter = successAdapter; |
||||
|
if (options !== undefined && Object(options).spread) { |
||||
|
adapter = spreadAdapter; |
||||
|
} |
||||
|
this._then( |
||||
|
adapter, |
||||
|
errorAdapter, |
||||
|
undefined, |
||||
|
this, |
||||
|
nodeback |
||||
|
); |
||||
|
} |
||||
|
return this; |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,775 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function() { |
||||
|
var makeSelfResolutionError = function () { |
||||
|
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
}; |
||||
|
var reflectHandler = function() { |
||||
|
return new Promise.PromiseInspection(this._target()); |
||||
|
}; |
||||
|
var apiRejection = function(msg) { |
||||
|
return Promise.reject(new TypeError(msg)); |
||||
|
}; |
||||
|
function Proxyable() {} |
||||
|
var UNDEFINED_BINDING = {}; |
||||
|
var util = require("./util"); |
||||
|
|
||||
|
var getDomain; |
||||
|
if (util.isNode) { |
||||
|
getDomain = function() { |
||||
|
var ret = process.domain; |
||||
|
if (ret === undefined) ret = null; |
||||
|
return ret; |
||||
|
}; |
||||
|
} else { |
||||
|
getDomain = function() { |
||||
|
return null; |
||||
|
}; |
||||
|
} |
||||
|
util.notEnumerableProp(Promise, "_getDomain", getDomain); |
||||
|
|
||||
|
var es5 = require("./es5"); |
||||
|
var Async = require("./async"); |
||||
|
var async = new Async(); |
||||
|
es5.defineProperty(Promise, "_async", {value: async}); |
||||
|
var errors = require("./errors"); |
||||
|
var TypeError = Promise.TypeError = errors.TypeError; |
||||
|
Promise.RangeError = errors.RangeError; |
||||
|
var CancellationError = Promise.CancellationError = errors.CancellationError; |
||||
|
Promise.TimeoutError = errors.TimeoutError; |
||||
|
Promise.OperationalError = errors.OperationalError; |
||||
|
Promise.RejectionError = errors.OperationalError; |
||||
|
Promise.AggregateError = errors.AggregateError; |
||||
|
var INTERNAL = function(){}; |
||||
|
var APPLY = {}; |
||||
|
var NEXT_FILTER = {}; |
||||
|
var tryConvertToPromise = require("./thenables")(Promise, INTERNAL); |
||||
|
var PromiseArray = |
||||
|
require("./promise_array")(Promise, INTERNAL, |
||||
|
tryConvertToPromise, apiRejection, Proxyable); |
||||
|
var Context = require("./context")(Promise); |
||||
|
/*jshint unused:false*/ |
||||
|
var createContext = Context.create; |
||||
|
var debug = require("./debuggability")(Promise, Context); |
||||
|
var CapturedTrace = debug.CapturedTrace; |
||||
|
var PassThroughHandlerContext = |
||||
|
require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); |
||||
|
var catchFilter = require("./catch_filter")(NEXT_FILTER); |
||||
|
var nodebackForPromise = require("./nodeback"); |
||||
|
var errorObj = util.errorObj; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
function check(self, executor) { |
||||
|
if (self == null || self.constructor !== Promise) { |
||||
|
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
if (typeof executor !== "function") { |
||||
|
throw new TypeError("expecting a function but got " + util.classString(executor)); |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
function Promise(executor) { |
||||
|
if (executor !== INTERNAL) { |
||||
|
check(this, executor); |
||||
|
} |
||||
|
this._bitField = 0; |
||||
|
this._fulfillmentHandler0 = undefined; |
||||
|
this._rejectionHandler0 = undefined; |
||||
|
this._promise0 = undefined; |
||||
|
this._receiver0 = undefined; |
||||
|
this._resolveFromExecutor(executor); |
||||
|
this._promiseCreated(); |
||||
|
this._fireEvent("promiseCreated", this); |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.toString = function () { |
||||
|
return "[object Promise]"; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { |
||||
|
var len = arguments.length; |
||||
|
if (len > 1) { |
||||
|
var catchInstances = new Array(len - 1), |
||||
|
j = 0, i; |
||||
|
for (i = 0; i < len - 1; ++i) { |
||||
|
var item = arguments[i]; |
||||
|
if (util.isObject(item)) { |
||||
|
catchInstances[j++] = item; |
||||
|
} else { |
||||
|
return apiRejection("Catch statement predicate: " + |
||||
|
"expecting an object but got " + util.classString(item)); |
||||
|
} |
||||
|
} |
||||
|
catchInstances.length = j; |
||||
|
fn = arguments[i]; |
||||
|
return this.then(undefined, catchFilter(catchInstances, fn, this)); |
||||
|
} |
||||
|
return this.then(undefined, fn); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.reflect = function () { |
||||
|
return this._then(reflectHandler, |
||||
|
reflectHandler, undefined, this, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.then = function (didFulfill, didReject) { |
||||
|
if (debug.warnings() && arguments.length > 0 && |
||||
|
typeof didFulfill !== "function" && |
||||
|
typeof didReject !== "function") { |
||||
|
var msg = ".then() only accepts functions but was passed: " + |
||||
|
util.classString(didFulfill); |
||||
|
if (arguments.length > 1) { |
||||
|
msg += ", " + util.classString(didReject); |
||||
|
} |
||||
|
this._warn(msg); |
||||
|
} |
||||
|
return this._then(didFulfill, didReject, undefined, undefined, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.done = function (didFulfill, didReject) { |
||||
|
var promise = |
||||
|
this._then(didFulfill, didReject, undefined, undefined, undefined); |
||||
|
promise._setIsFinal(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.spread = function (fn) { |
||||
|
if (typeof fn !== "function") { |
||||
|
return apiRejection("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
return this.all()._then(fn, undefined, undefined, APPLY, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.toJSON = function () { |
||||
|
var ret = { |
||||
|
isFulfilled: false, |
||||
|
isRejected: false, |
||||
|
fulfillmentValue: undefined, |
||||
|
rejectionReason: undefined |
||||
|
}; |
||||
|
if (this.isFulfilled()) { |
||||
|
ret.fulfillmentValue = this.value(); |
||||
|
ret.isFulfilled = true; |
||||
|
} else if (this.isRejected()) { |
||||
|
ret.rejectionReason = this.reason(); |
||||
|
ret.isRejected = true; |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.all = function () { |
||||
|
if (arguments.length > 0) { |
||||
|
this._warn(".all() was passed arguments but it does not take any"); |
||||
|
} |
||||
|
return new PromiseArray(this).promise(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.error = function (fn) { |
||||
|
return this.caught(util.originatesFromRejection, fn); |
||||
|
}; |
||||
|
|
||||
|
Promise.getNewLibraryCopy = module.exports; |
||||
|
|
||||
|
Promise.is = function (val) { |
||||
|
return val instanceof Promise; |
||||
|
}; |
||||
|
|
||||
|
Promise.fromNode = Promise.fromCallback = function(fn) { |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs |
||||
|
: false; |
||||
|
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); |
||||
|
if (result === errorObj) { |
||||
|
ret._rejectCallback(result.e, true); |
||||
|
} |
||||
|
if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.all = function (promises) { |
||||
|
return new PromiseArray(promises).promise(); |
||||
|
}; |
||||
|
|
||||
|
Promise.cast = function (obj) { |
||||
|
var ret = tryConvertToPromise(obj); |
||||
|
if (!(ret instanceof Promise)) { |
||||
|
ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
ret._setFulfilled(); |
||||
|
ret._rejectionHandler0 = obj; |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.resolve = Promise.fulfilled = Promise.cast; |
||||
|
|
||||
|
Promise.reject = Promise.rejected = function (reason) { |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
ret._captureStackTrace(); |
||||
|
ret._rejectCallback(reason, true); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.setScheduler = function(fn) { |
||||
|
if (typeof fn !== "function") { |
||||
|
throw new TypeError("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
return async.setScheduler(fn); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._then = function ( |
||||
|
didFulfill, |
||||
|
didReject, |
||||
|
_, receiver, |
||||
|
internalData |
||||
|
) { |
||||
|
var haveInternalData = internalData !== undefined; |
||||
|
var promise = haveInternalData ? internalData : new Promise(INTERNAL); |
||||
|
var target = this._target(); |
||||
|
var bitField = target._bitField; |
||||
|
|
||||
|
if (!haveInternalData) { |
||||
|
promise._propagateFrom(this, 3); |
||||
|
promise._captureStackTrace(); |
||||
|
if (receiver === undefined && |
||||
|
((this._bitField & 2097152) !== 0)) { |
||||
|
if (!((bitField & 50397184) === 0)) { |
||||
|
receiver = this._boundValue(); |
||||
|
} else { |
||||
|
receiver = target === this ? undefined : this._boundTo; |
||||
|
} |
||||
|
} |
||||
|
this._fireEvent("promiseChained", this, promise); |
||||
|
} |
||||
|
|
||||
|
var domain = getDomain(); |
||||
|
if (!((bitField & 50397184) === 0)) { |
||||
|
var handler, value, settler = target._settlePromiseCtx; |
||||
|
if (((bitField & 33554432) !== 0)) { |
||||
|
value = target._rejectionHandler0; |
||||
|
handler = didFulfill; |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
value = target._fulfillmentHandler0; |
||||
|
handler = didReject; |
||||
|
target._unsetRejectionIsUnhandled(); |
||||
|
} else { |
||||
|
settler = target._settlePromiseLateCancellationObserver; |
||||
|
value = new CancellationError("late cancellation observer"); |
||||
|
target._attachExtraTrace(value); |
||||
|
handler = didReject; |
||||
|
} |
||||
|
|
||||
|
async.invoke(settler, target, { |
||||
|
handler: domain === null ? handler |
||||
|
: (typeof handler === "function" && |
||||
|
util.domainBind(domain, handler)), |
||||
|
promise: promise, |
||||
|
receiver: receiver, |
||||
|
value: value |
||||
|
}); |
||||
|
} else { |
||||
|
target._addCallbacks(didFulfill, didReject, promise, receiver, domain); |
||||
|
} |
||||
|
|
||||
|
return promise; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._length = function () { |
||||
|
return this._bitField & 65535; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isFateSealed = function () { |
||||
|
return (this._bitField & 117506048) !== 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isFollowing = function () { |
||||
|
return (this._bitField & 67108864) === 67108864; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setLength = function (len) { |
||||
|
this._bitField = (this._bitField & -65536) | |
||||
|
(len & 65535); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setFulfilled = function () { |
||||
|
this._bitField = this._bitField | 33554432; |
||||
|
this._fireEvent("promiseFulfilled", this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setRejected = function () { |
||||
|
this._bitField = this._bitField | 16777216; |
||||
|
this._fireEvent("promiseRejected", this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setFollowing = function () { |
||||
|
this._bitField = this._bitField | 67108864; |
||||
|
this._fireEvent("promiseResolved", this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setIsFinal = function () { |
||||
|
this._bitField = this._bitField | 4194304; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isFinal = function () { |
||||
|
return (this._bitField & 4194304) > 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._unsetCancelled = function() { |
||||
|
this._bitField = this._bitField & (~65536); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setCancelled = function() { |
||||
|
this._bitField = this._bitField | 65536; |
||||
|
this._fireEvent("promiseCancelled", this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setWillBeCancelled = function() { |
||||
|
this._bitField = this._bitField | 8388608; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setAsyncGuaranteed = function() { |
||||
|
if (async.hasCustomScheduler()) return; |
||||
|
this._bitField = this._bitField | 134217728; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._receiverAt = function (index) { |
||||
|
var ret = index === 0 ? this._receiver0 : this[ |
||||
|
index * 4 - 4 + 3]; |
||||
|
if (ret === UNDEFINED_BINDING) { |
||||
|
return undefined; |
||||
|
} else if (ret === undefined && this._isBound()) { |
||||
|
return this._boundValue(); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._promiseAt = function (index) { |
||||
|
return this[ |
||||
|
index * 4 - 4 + 2]; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._fulfillmentHandlerAt = function (index) { |
||||
|
return this[ |
||||
|
index * 4 - 4 + 0]; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._rejectionHandlerAt = function (index) { |
||||
|
return this[ |
||||
|
index * 4 - 4 + 1]; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._boundValue = function() {}; |
||||
|
|
||||
|
Promise.prototype._migrateCallback0 = function (follower) { |
||||
|
var bitField = follower._bitField; |
||||
|
var fulfill = follower._fulfillmentHandler0; |
||||
|
var reject = follower._rejectionHandler0; |
||||
|
var promise = follower._promise0; |
||||
|
var receiver = follower._receiverAt(0); |
||||
|
if (receiver === undefined) receiver = UNDEFINED_BINDING; |
||||
|
this._addCallbacks(fulfill, reject, promise, receiver, null); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._migrateCallbackAt = function (follower, index) { |
||||
|
var fulfill = follower._fulfillmentHandlerAt(index); |
||||
|
var reject = follower._rejectionHandlerAt(index); |
||||
|
var promise = follower._promiseAt(index); |
||||
|
var receiver = follower._receiverAt(index); |
||||
|
if (receiver === undefined) receiver = UNDEFINED_BINDING; |
||||
|
this._addCallbacks(fulfill, reject, promise, receiver, null); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._addCallbacks = function ( |
||||
|
fulfill, |
||||
|
reject, |
||||
|
promise, |
||||
|
receiver, |
||||
|
domain |
||||
|
) { |
||||
|
var index = this._length(); |
||||
|
|
||||
|
if (index >= 65535 - 4) { |
||||
|
index = 0; |
||||
|
this._setLength(0); |
||||
|
} |
||||
|
|
||||
|
if (index === 0) { |
||||
|
this._promise0 = promise; |
||||
|
this._receiver0 = receiver; |
||||
|
if (typeof fulfill === "function") { |
||||
|
this._fulfillmentHandler0 = |
||||
|
domain === null ? fulfill : util.domainBind(domain, fulfill); |
||||
|
} |
||||
|
if (typeof reject === "function") { |
||||
|
this._rejectionHandler0 = |
||||
|
domain === null ? reject : util.domainBind(domain, reject); |
||||
|
} |
||||
|
} else { |
||||
|
var base = index * 4 - 4; |
||||
|
this[base + 2] = promise; |
||||
|
this[base + 3] = receiver; |
||||
|
if (typeof fulfill === "function") { |
||||
|
this[base + 0] = |
||||
|
domain === null ? fulfill : util.domainBind(domain, fulfill); |
||||
|
} |
||||
|
if (typeof reject === "function") { |
||||
|
this[base + 1] = |
||||
|
domain === null ? reject : util.domainBind(domain, reject); |
||||
|
} |
||||
|
} |
||||
|
this._setLength(index + 1); |
||||
|
return index; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._proxy = function (proxyable, arg) { |
||||
|
this._addCallbacks(undefined, undefined, arg, proxyable, null); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._resolveCallback = function(value, shouldBind) { |
||||
|
if (((this._bitField & 117506048) !== 0)) return; |
||||
|
if (value === this) |
||||
|
return this._rejectCallback(makeSelfResolutionError(), false); |
||||
|
var maybePromise = tryConvertToPromise(value, this); |
||||
|
if (!(maybePromise instanceof Promise)) return this._fulfill(value); |
||||
|
|
||||
|
if (shouldBind) this._propagateFrom(maybePromise, 2); |
||||
|
|
||||
|
var promise = maybePromise._target(); |
||||
|
|
||||
|
if (promise === this) { |
||||
|
this._reject(makeSelfResolutionError()); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
var bitField = promise._bitField; |
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
var len = this._length(); |
||||
|
if (len > 0) promise._migrateCallback0(this); |
||||
|
for (var i = 1; i < len; ++i) { |
||||
|
promise._migrateCallbackAt(this, i); |
||||
|
} |
||||
|
this._setFollowing(); |
||||
|
this._setLength(0); |
||||
|
this._setFollowee(promise); |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
this._fulfill(promise._value()); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
this._reject(promise._reason()); |
||||
|
} else { |
||||
|
var reason = new CancellationError("late cancellation observer"); |
||||
|
promise._attachExtraTrace(reason); |
||||
|
this._reject(reason); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._rejectCallback = |
||||
|
function(reason, synchronous, ignoreNonErrorWarnings) { |
||||
|
var trace = util.ensureErrorObject(reason); |
||||
|
var hasStack = trace === reason; |
||||
|
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { |
||||
|
var message = "a promise was rejected with a non-error: " + |
||||
|
util.classString(reason); |
||||
|
this._warn(message, true); |
||||
|
} |
||||
|
this._attachExtraTrace(trace, synchronous ? hasStack : false); |
||||
|
this._reject(reason); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._resolveFromExecutor = function (executor) { |
||||
|
if (executor === INTERNAL) return; |
||||
|
var promise = this; |
||||
|
this._captureStackTrace(); |
||||
|
this._pushContext(); |
||||
|
var synchronous = true; |
||||
|
var r = this._execute(executor, function(value) { |
||||
|
promise._resolveCallback(value); |
||||
|
}, function (reason) { |
||||
|
promise._rejectCallback(reason, synchronous); |
||||
|
}); |
||||
|
synchronous = false; |
||||
|
this._popContext(); |
||||
|
|
||||
|
if (r !== undefined) { |
||||
|
promise._rejectCallback(r, true); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromiseFromHandler = function ( |
||||
|
handler, receiver, value, promise |
||||
|
) { |
||||
|
var bitField = promise._bitField; |
||||
|
if (((bitField & 65536) !== 0)) return; |
||||
|
promise._pushContext(); |
||||
|
var x; |
||||
|
if (receiver === APPLY) { |
||||
|
if (!value || typeof value.length !== "number") { |
||||
|
x = errorObj; |
||||
|
x.e = new TypeError("cannot .spread() a non-array: " + |
||||
|
util.classString(value)); |
||||
|
} else { |
||||
|
x = tryCatch(handler).apply(this._boundValue(), value); |
||||
|
} |
||||
|
} else { |
||||
|
x = tryCatch(handler).call(receiver, value); |
||||
|
} |
||||
|
var promiseCreated = promise._popContext(); |
||||
|
bitField = promise._bitField; |
||||
|
if (((bitField & 65536) !== 0)) return; |
||||
|
|
||||
|
if (x === NEXT_FILTER) { |
||||
|
promise._reject(value); |
||||
|
} else if (x === errorObj) { |
||||
|
promise._rejectCallback(x.e, false); |
||||
|
} else { |
||||
|
debug.checkForgottenReturns(x, promiseCreated, "", promise, this); |
||||
|
promise._resolveCallback(x); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._target = function() { |
||||
|
var ret = this; |
||||
|
while (ret._isFollowing()) ret = ret._followee(); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._followee = function() { |
||||
|
return this._rejectionHandler0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setFollowee = function(promise) { |
||||
|
this._rejectionHandler0 = promise; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromise = function(promise, handler, receiver, value) { |
||||
|
var isPromise = promise instanceof Promise; |
||||
|
var bitField = this._bitField; |
||||
|
var asyncGuaranteed = ((bitField & 134217728) !== 0); |
||||
|
if (((bitField & 65536) !== 0)) { |
||||
|
if (isPromise) promise._invokeInternalOnCancel(); |
||||
|
|
||||
|
if (receiver instanceof PassThroughHandlerContext && |
||||
|
receiver.isFinallyHandler()) { |
||||
|
receiver.cancelPromise = promise; |
||||
|
if (tryCatch(handler).call(receiver, value) === errorObj) { |
||||
|
promise._reject(errorObj.e); |
||||
|
} |
||||
|
} else if (handler === reflectHandler) { |
||||
|
promise._fulfill(reflectHandler.call(receiver)); |
||||
|
} else if (receiver instanceof Proxyable) { |
||||
|
receiver._promiseCancelled(promise); |
||||
|
} else if (isPromise || promise instanceof PromiseArray) { |
||||
|
promise._cancel(); |
||||
|
} else { |
||||
|
receiver.cancel(); |
||||
|
} |
||||
|
} else if (typeof handler === "function") { |
||||
|
if (!isPromise) { |
||||
|
handler.call(receiver, value, promise); |
||||
|
} else { |
||||
|
if (asyncGuaranteed) promise._setAsyncGuaranteed(); |
||||
|
this._settlePromiseFromHandler(handler, receiver, value, promise); |
||||
|
} |
||||
|
} else if (receiver instanceof Proxyable) { |
||||
|
if (!receiver._isResolved()) { |
||||
|
if (((bitField & 33554432) !== 0)) { |
||||
|
receiver._promiseFulfilled(value, promise); |
||||
|
} else { |
||||
|
receiver._promiseRejected(value, promise); |
||||
|
} |
||||
|
} |
||||
|
} else if (isPromise) { |
||||
|
if (asyncGuaranteed) promise._setAsyncGuaranteed(); |
||||
|
if (((bitField & 33554432) !== 0)) { |
||||
|
promise._fulfill(value); |
||||
|
} else { |
||||
|
promise._reject(value); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { |
||||
|
var handler = ctx.handler; |
||||
|
var promise = ctx.promise; |
||||
|
var receiver = ctx.receiver; |
||||
|
var value = ctx.value; |
||||
|
if (typeof handler === "function") { |
||||
|
if (!(promise instanceof Promise)) { |
||||
|
handler.call(receiver, value, promise); |
||||
|
} else { |
||||
|
this._settlePromiseFromHandler(handler, receiver, value, promise); |
||||
|
} |
||||
|
} else if (promise instanceof Promise) { |
||||
|
promise._reject(value); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromiseCtx = function(ctx) { |
||||
|
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromise0 = function(handler, value, bitField) { |
||||
|
var promise = this._promise0; |
||||
|
var receiver = this._receiverAt(0); |
||||
|
this._promise0 = undefined; |
||||
|
this._receiver0 = undefined; |
||||
|
this._settlePromise(promise, handler, receiver, value); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._clearCallbackDataAtIndex = function(index) { |
||||
|
var base = index * 4 - 4; |
||||
|
this[base + 2] = |
||||
|
this[base + 3] = |
||||
|
this[base + 0] = |
||||
|
this[base + 1] = undefined; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._fulfill = function (value) { |
||||
|
var bitField = this._bitField; |
||||
|
if (((bitField & 117506048) >>> 16)) return; |
||||
|
if (value === this) { |
||||
|
var err = makeSelfResolutionError(); |
||||
|
this._attachExtraTrace(err); |
||||
|
return this._reject(err); |
||||
|
} |
||||
|
this._setFulfilled(); |
||||
|
this._rejectionHandler0 = value; |
||||
|
|
||||
|
if ((bitField & 65535) > 0) { |
||||
|
if (((bitField & 134217728) !== 0)) { |
||||
|
this._settlePromises(); |
||||
|
} else { |
||||
|
async.settlePromises(this); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._reject = function (reason) { |
||||
|
var bitField = this._bitField; |
||||
|
if (((bitField & 117506048) >>> 16)) return; |
||||
|
this._setRejected(); |
||||
|
this._fulfillmentHandler0 = reason; |
||||
|
|
||||
|
if (this._isFinal()) { |
||||
|
return async.fatalError(reason, util.isNode); |
||||
|
} |
||||
|
|
||||
|
if ((bitField & 65535) > 0) { |
||||
|
async.settlePromises(this); |
||||
|
} else { |
||||
|
this._ensurePossibleRejectionHandled(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._fulfillPromises = function (len, value) { |
||||
|
for (var i = 1; i < len; i++) { |
||||
|
var handler = this._fulfillmentHandlerAt(i); |
||||
|
var promise = this._promiseAt(i); |
||||
|
var receiver = this._receiverAt(i); |
||||
|
this._clearCallbackDataAtIndex(i); |
||||
|
this._settlePromise(promise, handler, receiver, value); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._rejectPromises = function (len, reason) { |
||||
|
for (var i = 1; i < len; i++) { |
||||
|
var handler = this._rejectionHandlerAt(i); |
||||
|
var promise = this._promiseAt(i); |
||||
|
var receiver = this._receiverAt(i); |
||||
|
this._clearCallbackDataAtIndex(i); |
||||
|
this._settlePromise(promise, handler, receiver, reason); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settlePromises = function () { |
||||
|
var bitField = this._bitField; |
||||
|
var len = (bitField & 65535); |
||||
|
|
||||
|
if (len > 0) { |
||||
|
if (((bitField & 16842752) !== 0)) { |
||||
|
var reason = this._fulfillmentHandler0; |
||||
|
this._settlePromise0(this._rejectionHandler0, reason, bitField); |
||||
|
this._rejectPromises(len, reason); |
||||
|
} else { |
||||
|
var value = this._rejectionHandler0; |
||||
|
this._settlePromise0(this._fulfillmentHandler0, value, bitField); |
||||
|
this._fulfillPromises(len, value); |
||||
|
} |
||||
|
this._setLength(0); |
||||
|
} |
||||
|
this._clearCancellationData(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._settledValue = function() { |
||||
|
var bitField = this._bitField; |
||||
|
if (((bitField & 33554432) !== 0)) { |
||||
|
return this._rejectionHandler0; |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
return this._fulfillmentHandler0; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
function deferResolve(v) {this.promise._resolveCallback(v);} |
||||
|
function deferReject(v) {this.promise._rejectCallback(v, false);} |
||||
|
|
||||
|
Promise.defer = Promise.pending = function() { |
||||
|
debug.deprecated("Promise.defer", "new Promise"); |
||||
|
var promise = new Promise(INTERNAL); |
||||
|
return { |
||||
|
promise: promise, |
||||
|
resolve: deferResolve, |
||||
|
reject: deferReject |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
util.notEnumerableProp(Promise, |
||||
|
"_makeSelfResolutionError", |
||||
|
makeSelfResolutionError); |
||||
|
|
||||
|
require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, |
||||
|
debug); |
||||
|
require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); |
||||
|
require("./cancel")(Promise, PromiseArray, apiRejection, debug); |
||||
|
require("./direct_resolve")(Promise); |
||||
|
require("./synchronous_inspection")(Promise); |
||||
|
require("./join")( |
||||
|
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); |
||||
|
Promise.Promise = Promise; |
||||
|
Promise.version = "3.5.1"; |
||||
|
require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); |
||||
|
require('./call_get.js')(Promise); |
||||
|
require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); |
||||
|
require('./timers.js')(Promise, INTERNAL, debug); |
||||
|
require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); |
||||
|
require('./nodeify.js')(Promise); |
||||
|
require('./promisify.js')(Promise, INTERNAL); |
||||
|
require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); |
||||
|
require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); |
||||
|
require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); |
||||
|
require('./settle.js')(Promise, PromiseArray, debug); |
||||
|
require('./some.js')(Promise, PromiseArray, apiRejection); |
||||
|
require('./filter.js')(Promise, INTERNAL); |
||||
|
require('./each.js')(Promise, INTERNAL); |
||||
|
require('./any.js')(Promise); |
||||
|
|
||||
|
util.toFastProperties(Promise); |
||||
|
util.toFastProperties(Promise.prototype); |
||||
|
function fillTypes(value) { |
||||
|
var p = new Promise(INTERNAL); |
||||
|
p._fulfillmentHandler0 = value; |
||||
|
p._rejectionHandler0 = value; |
||||
|
p._promise0 = value; |
||||
|
p._receiver0 = value; |
||||
|
} |
||||
|
// Complete slack tracking, opt out of field-type tracking and
|
||||
|
// stabilize map
|
||||
|
fillTypes({a: 1}); |
||||
|
fillTypes({b: 2}); |
||||
|
fillTypes({c: 3}); |
||||
|
fillTypes(1); |
||||
|
fillTypes(function(){}); |
||||
|
fillTypes(undefined); |
||||
|
fillTypes(false); |
||||
|
fillTypes(new Promise(INTERNAL)); |
||||
|
debug.setBounds(Async.firstLineError, util.lastLineError); |
||||
|
return Promise; |
||||
|
|
||||
|
}; |
@ -0,0 +1,185 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL, tryConvertToPromise, |
||||
|
apiRejection, Proxyable) { |
||||
|
var util = require("./util"); |
||||
|
var isArray = util.isArray; |
||||
|
|
||||
|
function toResolutionValue(val) { |
||||
|
switch(val) { |
||||
|
case -2: return []; |
||||
|
case -3: return {}; |
||||
|
case -6: return new Map(); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function PromiseArray(values) { |
||||
|
var promise = this._promise = new Promise(INTERNAL); |
||||
|
if (values instanceof Promise) { |
||||
|
promise._propagateFrom(values, 3); |
||||
|
} |
||||
|
promise._setOnCancel(this); |
||||
|
this._values = values; |
||||
|
this._length = 0; |
||||
|
this._totalResolved = 0; |
||||
|
this._init(undefined, -2); |
||||
|
} |
||||
|
util.inherits(PromiseArray, Proxyable); |
||||
|
|
||||
|
PromiseArray.prototype.length = function () { |
||||
|
return this._length; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype.promise = function () { |
||||
|
return this._promise; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) { |
||||
|
var values = tryConvertToPromise(this._values, this._promise); |
||||
|
if (values instanceof Promise) { |
||||
|
values = values._target(); |
||||
|
var bitField = values._bitField; |
||||
|
; |
||||
|
this._values = values; |
||||
|
|
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
this._promise._setAsyncGuaranteed(); |
||||
|
return values._then( |
||||
|
init, |
||||
|
this._reject, |
||||
|
undefined, |
||||
|
this, |
||||
|
resolveValueIfEmpty |
||||
|
); |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
values = values._value(); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
return this._reject(values._reason()); |
||||
|
} else { |
||||
|
return this._cancel(); |
||||
|
} |
||||
|
} |
||||
|
values = util.asArray(values); |
||||
|
if (values === null) { |
||||
|
var err = apiRejection( |
||||
|
"expecting an array or an iterable object but got " + util.classString(values)).reason(); |
||||
|
this._promise._rejectCallback(err, false); |
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
if (values.length === 0) { |
||||
|
if (resolveValueIfEmpty === -5) { |
||||
|
this._resolveEmptyArray(); |
||||
|
} |
||||
|
else { |
||||
|
this._resolve(toResolutionValue(resolveValueIfEmpty)); |
||||
|
} |
||||
|
return; |
||||
|
} |
||||
|
this._iterate(values); |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._iterate = function(values) { |
||||
|
var len = this.getActualLength(values.length); |
||||
|
this._length = len; |
||||
|
this._values = this.shouldCopyValues() ? new Array(len) : this._values; |
||||
|
var result = this._promise; |
||||
|
var isResolved = false; |
||||
|
var bitField = null; |
||||
|
for (var i = 0; i < len; ++i) { |
||||
|
var maybePromise = tryConvertToPromise(values[i], result); |
||||
|
|
||||
|
if (maybePromise instanceof Promise) { |
||||
|
maybePromise = maybePromise._target(); |
||||
|
bitField = maybePromise._bitField; |
||||
|
} else { |
||||
|
bitField = null; |
||||
|
} |
||||
|
|
||||
|
if (isResolved) { |
||||
|
if (bitField !== null) { |
||||
|
maybePromise.suppressUnhandledRejections(); |
||||
|
} |
||||
|
} else if (bitField !== null) { |
||||
|
if (((bitField & 50397184) === 0)) { |
||||
|
maybePromise._proxy(this, i); |
||||
|
this._values[i] = maybePromise; |
||||
|
} else if (((bitField & 33554432) !== 0)) { |
||||
|
isResolved = this._promiseFulfilled(maybePromise._value(), i); |
||||
|
} else if (((bitField & 16777216) !== 0)) { |
||||
|
isResolved = this._promiseRejected(maybePromise._reason(), i); |
||||
|
} else { |
||||
|
isResolved = this._promiseCancelled(i); |
||||
|
} |
||||
|
} else { |
||||
|
isResolved = this._promiseFulfilled(maybePromise, i); |
||||
|
} |
||||
|
} |
||||
|
if (!isResolved) result._setAsyncGuaranteed(); |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._isResolved = function () { |
||||
|
return this._values === null; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._resolve = function (value) { |
||||
|
this._values = null; |
||||
|
this._promise._fulfill(value); |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._cancel = function() { |
||||
|
if (this._isResolved() || !this._promise._isCancellable()) return; |
||||
|
this._values = null; |
||||
|
this._promise._cancel(); |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._reject = function (reason) { |
||||
|
this._values = null; |
||||
|
this._promise._rejectCallback(reason, false); |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._promiseFulfilled = function (value, index) { |
||||
|
this._values[index] = value; |
||||
|
var totalResolved = ++this._totalResolved; |
||||
|
if (totalResolved >= this._length) { |
||||
|
this._resolve(this._values); |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._promiseCancelled = function() { |
||||
|
this._cancel(); |
||||
|
return true; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._promiseRejected = function (reason) { |
||||
|
this._totalResolved++; |
||||
|
this._reject(reason); |
||||
|
return true; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype._resultCancelled = function() { |
||||
|
if (this._isResolved()) return; |
||||
|
var values = this._values; |
||||
|
this._cancel(); |
||||
|
if (values instanceof Promise) { |
||||
|
values.cancel(); |
||||
|
} else { |
||||
|
for (var i = 0; i < values.length; ++i) { |
||||
|
if (values[i] instanceof Promise) { |
||||
|
values[i].cancel(); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype.shouldCopyValues = function () { |
||||
|
return true; |
||||
|
}; |
||||
|
|
||||
|
PromiseArray.prototype.getActualLength = function (len) { |
||||
|
return len; |
||||
|
}; |
||||
|
|
||||
|
return PromiseArray; |
||||
|
}; |
@ -0,0 +1,314 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL) { |
||||
|
var THIS = {}; |
||||
|
var util = require("./util"); |
||||
|
var nodebackForPromise = require("./nodeback"); |
||||
|
var withAppended = util.withAppended; |
||||
|
var maybeWrapAsError = util.maybeWrapAsError; |
||||
|
var canEvaluate = util.canEvaluate; |
||||
|
var TypeError = require("./errors").TypeError; |
||||
|
var defaultSuffix = "Async"; |
||||
|
var defaultPromisified = {__isPromisified__: true}; |
||||
|
var noCopyProps = [ |
||||
|
"arity", "length", |
||||
|
"name", |
||||
|
"arguments", |
||||
|
"caller", |
||||
|
"callee", |
||||
|
"prototype", |
||||
|
"__isPromisified__" |
||||
|
]; |
||||
|
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$"); |
||||
|
|
||||
|
var defaultFilter = function(name) { |
||||
|
return util.isIdentifier(name) && |
||||
|
name.charAt(0) !== "_" && |
||||
|
name !== "constructor"; |
||||
|
}; |
||||
|
|
||||
|
function propsFilter(key) { |
||||
|
return !noCopyPropsPattern.test(key); |
||||
|
} |
||||
|
|
||||
|
function isPromisified(fn) { |
||||
|
try { |
||||
|
return fn.__isPromisified__ === true; |
||||
|
} |
||||
|
catch (e) { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function hasPromisified(obj, key, suffix) { |
||||
|
var val = util.getDataPropertyOrDefault(obj, key + suffix, |
||||
|
defaultPromisified); |
||||
|
return val ? isPromisified(val) : false; |
||||
|
} |
||||
|
function checkValid(ret, suffix, suffixRegexp) { |
||||
|
for (var i = 0; i < ret.length; i += 2) { |
||||
|
var key = ret[i]; |
||||
|
if (suffixRegexp.test(key)) { |
||||
|
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, ""); |
||||
|
for (var j = 0; j < ret.length; j += 2) { |
||||
|
if (ret[j] === keyWithoutAsyncSuffix) { |
||||
|
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a" |
||||
|
.replace("%s", suffix)); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function promisifiableMethods(obj, suffix, suffixRegexp, filter) { |
||||
|
var keys = util.inheritedDataKeys(obj); |
||||
|
var ret = []; |
||||
|
for (var i = 0; i < keys.length; ++i) { |
||||
|
var key = keys[i]; |
||||
|
var value = obj[key]; |
||||
|
var passesDefaultFilter = filter === defaultFilter |
||||
|
? true : defaultFilter(key, value, obj); |
||||
|
if (typeof value === "function" && |
||||
|
!isPromisified(value) && |
||||
|
!hasPromisified(obj, key, suffix) && |
||||
|
filter(key, value, obj, passesDefaultFilter)) { |
||||
|
ret.push(key, value); |
||||
|
} |
||||
|
} |
||||
|
checkValid(ret, suffix, suffixRegexp); |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
var escapeIdentRegex = function(str) { |
||||
|
return str.replace(/([$])/, "\\$"); |
||||
|
}; |
||||
|
|
||||
|
var makeNodePromisifiedEval; |
||||
|
if (!false) { |
||||
|
var switchCaseArgumentOrder = function(likelyArgumentCount) { |
||||
|
var ret = [likelyArgumentCount]; |
||||
|
var min = Math.max(0, likelyArgumentCount - 1 - 3); |
||||
|
for(var i = likelyArgumentCount - 1; i >= min; --i) { |
||||
|
ret.push(i); |
||||
|
} |
||||
|
for(var i = likelyArgumentCount + 1; i <= 3; ++i) { |
||||
|
ret.push(i); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
var argumentSequence = function(argumentCount) { |
||||
|
return util.filledRange(argumentCount, "_arg", ""); |
||||
|
}; |
||||
|
|
||||
|
var parameterDeclaration = function(parameterCount) { |
||||
|
return util.filledRange( |
||||
|
Math.max(parameterCount, 3), "_arg", ""); |
||||
|
}; |
||||
|
|
||||
|
var parameterCount = function(fn) { |
||||
|
if (typeof fn.length === "number") { |
||||
|
return Math.max(Math.min(fn.length, 1023 + 1), 0); |
||||
|
} |
||||
|
return 0; |
||||
|
}; |
||||
|
|
||||
|
makeNodePromisifiedEval = |
||||
|
function(callback, receiver, originalName, fn, _, multiArgs) { |
||||
|
var newParameterCount = Math.max(0, parameterCount(fn) - 1); |
||||
|
var argumentOrder = switchCaseArgumentOrder(newParameterCount); |
||||
|
var shouldProxyThis = typeof callback === "string" || receiver === THIS; |
||||
|
|
||||
|
function generateCallForArgumentCount(count) { |
||||
|
var args = argumentSequence(count).join(", "); |
||||
|
var comma = count > 0 ? ", " : ""; |
||||
|
var ret; |
||||
|
if (shouldProxyThis) { |
||||
|
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n"; |
||||
|
} else { |
||||
|
ret = receiver === undefined |
||||
|
? "ret = callback({{args}}, nodeback); break;\n" |
||||
|
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n"; |
||||
|
} |
||||
|
return ret.replace("{{args}}", args).replace(", ", comma); |
||||
|
} |
||||
|
|
||||
|
function generateArgumentSwitchCase() { |
||||
|
var ret = ""; |
||||
|
for (var i = 0; i < argumentOrder.length; ++i) { |
||||
|
ret += "case " + argumentOrder[i] +":" + |
||||
|
generateCallForArgumentCount(argumentOrder[i]); |
||||
|
} |
||||
|
|
||||
|
ret += " \n\ |
||||
|
default: \n\ |
||||
|
var args = new Array(len + 1); \n\ |
||||
|
var i = 0; \n\ |
||||
|
for (var i = 0; i < len; ++i) { \n\ |
||||
|
args[i] = arguments[i]; \n\ |
||||
|
} \n\ |
||||
|
args[i] = nodeback; \n\ |
||||
|
[CodeForCall] \n\ |
||||
|
break; \n\ |
||||
|
".replace("[CodeForCall]", (shouldProxyThis |
||||
|
? "ret = callback.apply(this, args);\n" |
||||
|
: "ret = callback.apply(receiver, args);\n")); |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
var getFunctionCode = typeof callback === "string" |
||||
|
? ("this != null ? this['"+callback+"'] : fn") |
||||
|
: "fn"; |
||||
|
var body = "'use strict'; \n\ |
||||
|
var ret = function (Parameters) { \n\ |
||||
|
'use strict'; \n\ |
||||
|
var len = arguments.length; \n\ |
||||
|
var promise = new Promise(INTERNAL); \n\ |
||||
|
promise._captureStackTrace(); \n\ |
||||
|
var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\ |
||||
|
var ret; \n\ |
||||
|
var callback = tryCatch([GetFunctionCode]); \n\ |
||||
|
switch(len) { \n\ |
||||
|
[CodeForSwitchCase] \n\ |
||||
|
} \n\ |
||||
|
if (ret === errorObj) { \n\ |
||||
|
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\ |
||||
|
} \n\ |
||||
|
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\ |
||||
|
return promise; \n\ |
||||
|
}; \n\ |
||||
|
notEnumerableProp(ret, '__isPromisified__', true); \n\ |
||||
|
return ret; \n\ |
||||
|
".replace("[CodeForSwitchCase]", generateArgumentSwitchCase()) |
||||
|
.replace("[GetFunctionCode]", getFunctionCode); |
||||
|
body = body.replace("Parameters", parameterDeclaration(newParameterCount)); |
||||
|
return new Function("Promise", |
||||
|
"fn", |
||||
|
"receiver", |
||||
|
"withAppended", |
||||
|
"maybeWrapAsError", |
||||
|
"nodebackForPromise", |
||||
|
"tryCatch", |
||||
|
"errorObj", |
||||
|
"notEnumerableProp", |
||||
|
"INTERNAL", |
||||
|
body)( |
||||
|
Promise, |
||||
|
fn, |
||||
|
receiver, |
||||
|
withAppended, |
||||
|
maybeWrapAsError, |
||||
|
nodebackForPromise, |
||||
|
util.tryCatch, |
||||
|
util.errorObj, |
||||
|
util.notEnumerableProp, |
||||
|
INTERNAL); |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) { |
||||
|
var defaultThis = (function() {return this;})(); |
||||
|
var method = callback; |
||||
|
if (typeof method === "string") { |
||||
|
callback = fn; |
||||
|
} |
||||
|
function promisified() { |
||||
|
var _receiver = receiver; |
||||
|
if (receiver === THIS) _receiver = this; |
||||
|
var promise = new Promise(INTERNAL); |
||||
|
promise._captureStackTrace(); |
||||
|
var cb = typeof method === "string" && this !== defaultThis |
||||
|
? this[method] : callback; |
||||
|
var fn = nodebackForPromise(promise, multiArgs); |
||||
|
try { |
||||
|
cb.apply(_receiver, withAppended(arguments, fn)); |
||||
|
} catch(e) { |
||||
|
promise._rejectCallback(maybeWrapAsError(e), true, true); |
||||
|
} |
||||
|
if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); |
||||
|
return promise; |
||||
|
} |
||||
|
util.notEnumerableProp(promisified, "__isPromisified__", true); |
||||
|
return promisified; |
||||
|
} |
||||
|
|
||||
|
var makeNodePromisified = canEvaluate |
||||
|
? makeNodePromisifiedEval |
||||
|
: makeNodePromisifiedClosure; |
||||
|
|
||||
|
function promisifyAll(obj, suffix, filter, promisifier, multiArgs) { |
||||
|
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$"); |
||||
|
var methods = |
||||
|
promisifiableMethods(obj, suffix, suffixRegexp, filter); |
||||
|
|
||||
|
for (var i = 0, len = methods.length; i < len; i+= 2) { |
||||
|
var key = methods[i]; |
||||
|
var fn = methods[i+1]; |
||||
|
var promisifiedKey = key + suffix; |
||||
|
if (promisifier === makeNodePromisified) { |
||||
|
obj[promisifiedKey] = |
||||
|
makeNodePromisified(key, THIS, key, fn, suffix, multiArgs); |
||||
|
} else { |
||||
|
var promisified = promisifier(fn, function() { |
||||
|
return makeNodePromisified(key, THIS, key, |
||||
|
fn, suffix, multiArgs); |
||||
|
}); |
||||
|
util.notEnumerableProp(promisified, "__isPromisified__", true); |
||||
|
obj[promisifiedKey] = promisified; |
||||
|
} |
||||
|
} |
||||
|
util.toFastProperties(obj); |
||||
|
return obj; |
||||
|
} |
||||
|
|
||||
|
function promisify(callback, receiver, multiArgs) { |
||||
|
return makeNodePromisified(callback, receiver, undefined, |
||||
|
callback, null, multiArgs); |
||||
|
} |
||||
|
|
||||
|
Promise.promisify = function (fn, options) { |
||||
|
if (typeof fn !== "function") { |
||||
|
throw new TypeError("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
if (isPromisified(fn)) { |
||||
|
return fn; |
||||
|
} |
||||
|
options = Object(options); |
||||
|
var receiver = options.context === undefined ? THIS : options.context; |
||||
|
var multiArgs = !!options.multiArgs; |
||||
|
var ret = promisify(fn, receiver, multiArgs); |
||||
|
util.copyDescriptors(fn, ret, propsFilter); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.promisifyAll = function (target, options) { |
||||
|
if (typeof target !== "function" && typeof target !== "object") { |
||||
|
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
options = Object(options); |
||||
|
var multiArgs = !!options.multiArgs; |
||||
|
var suffix = options.suffix; |
||||
|
if (typeof suffix !== "string") suffix = defaultSuffix; |
||||
|
var filter = options.filter; |
||||
|
if (typeof filter !== "function") filter = defaultFilter; |
||||
|
var promisifier = options.promisifier; |
||||
|
if (typeof promisifier !== "function") promisifier = makeNodePromisified; |
||||
|
|
||||
|
if (!util.isIdentifier(suffix)) { |
||||
|
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
|
||||
|
var keys = util.inheritedDataKeys(target); |
||||
|
for (var i = 0; i < keys.length; ++i) { |
||||
|
var value = target[keys[i]]; |
||||
|
if (keys[i] !== "constructor" && |
||||
|
util.isClass(value)) { |
||||
|
promisifyAll(value.prototype, suffix, filter, promisifier, |
||||
|
multiArgs); |
||||
|
promisifyAll(value, suffix, filter, promisifier, multiArgs); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return promisifyAll(target, suffix, filter, promisifier, multiArgs); |
||||
|
}; |
||||
|
}; |
||||
|
|
@ -0,0 +1,118 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function( |
||||
|
Promise, PromiseArray, tryConvertToPromise, apiRejection) { |
||||
|
var util = require("./util"); |
||||
|
var isObject = util.isObject; |
||||
|
var es5 = require("./es5"); |
||||
|
var Es6Map; |
||||
|
if (typeof Map === "function") Es6Map = Map; |
||||
|
|
||||
|
var mapToEntries = (function() { |
||||
|
var index = 0; |
||||
|
var size = 0; |
||||
|
|
||||
|
function extractEntry(value, key) { |
||||
|
this[index] = value; |
||||
|
this[index + size] = key; |
||||
|
index++; |
||||
|
} |
||||
|
|
||||
|
return function mapToEntries(map) { |
||||
|
size = map.size; |
||||
|
index = 0; |
||||
|
var ret = new Array(map.size * 2); |
||||
|
map.forEach(extractEntry, ret); |
||||
|
return ret; |
||||
|
}; |
||||
|
})(); |
||||
|
|
||||
|
var entriesToMap = function(entries) { |
||||
|
var ret = new Es6Map(); |
||||
|
var length = entries.length / 2 | 0; |
||||
|
for (var i = 0; i < length; ++i) { |
||||
|
var key = entries[length + i]; |
||||
|
var value = entries[i]; |
||||
|
ret.set(key, value); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
function PropertiesPromiseArray(obj) { |
||||
|
var isMap = false; |
||||
|
var entries; |
||||
|
if (Es6Map !== undefined && obj instanceof Es6Map) { |
||||
|
entries = mapToEntries(obj); |
||||
|
isMap = true; |
||||
|
} else { |
||||
|
var keys = es5.keys(obj); |
||||
|
var len = keys.length; |
||||
|
entries = new Array(len * 2); |
||||
|
for (var i = 0; i < len; ++i) { |
||||
|
var key = keys[i]; |
||||
|
entries[i] = obj[key]; |
||||
|
entries[i + len] = key; |
||||
|
} |
||||
|
} |
||||
|
this.constructor$(entries); |
||||
|
this._isMap = isMap; |
||||
|
this._init$(undefined, isMap ? -6 : -3); |
||||
|
} |
||||
|
util.inherits(PropertiesPromiseArray, PromiseArray); |
||||
|
|
||||
|
PropertiesPromiseArray.prototype._init = function () {}; |
||||
|
|
||||
|
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) { |
||||
|
this._values[index] = value; |
||||
|
var totalResolved = ++this._totalResolved; |
||||
|
if (totalResolved >= this._length) { |
||||
|
var val; |
||||
|
if (this._isMap) { |
||||
|
val = entriesToMap(this._values); |
||||
|
} else { |
||||
|
val = {}; |
||||
|
var keyOffset = this.length(); |
||||
|
for (var i = 0, len = this.length(); i < len; ++i) { |
||||
|
val[this._values[i + keyOffset]] = this._values[i]; |
||||
|
} |
||||
|
} |
||||
|
this._resolve(val); |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
PropertiesPromiseArray.prototype.shouldCopyValues = function () { |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
PropertiesPromiseArray.prototype.getActualLength = function (len) { |
||||
|
return len >> 1; |
||||
|
}; |
||||
|
|
||||
|
function props(promises) { |
||||
|
var ret; |
||||
|
var castValue = tryConvertToPromise(promises); |
||||
|
|
||||
|
if (!isObject(castValue)) { |
||||
|
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} else if (castValue instanceof Promise) { |
||||
|
ret = castValue._then( |
||||
|
Promise.props, undefined, undefined, undefined, undefined); |
||||
|
} else { |
||||
|
ret = new PropertiesPromiseArray(castValue).promise(); |
||||
|
} |
||||
|
|
||||
|
if (castValue instanceof Promise) { |
||||
|
ret._propagateFrom(castValue, 2); |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.props = function () { |
||||
|
return props(this); |
||||
|
}; |
||||
|
|
||||
|
Promise.props = function (promises) { |
||||
|
return props(promises); |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,73 @@ |
|||||
|
"use strict"; |
||||
|
function arrayMove(src, srcIndex, dst, dstIndex, len) { |
||||
|
for (var j = 0; j < len; ++j) { |
||||
|
dst[j + dstIndex] = src[j + srcIndex]; |
||||
|
src[j + srcIndex] = void 0; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function Queue(capacity) { |
||||
|
this._capacity = capacity; |
||||
|
this._length = 0; |
||||
|
this._front = 0; |
||||
|
} |
||||
|
|
||||
|
Queue.prototype._willBeOverCapacity = function (size) { |
||||
|
return this._capacity < size; |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype._pushOne = function (arg) { |
||||
|
var length = this.length(); |
||||
|
this._checkCapacity(length + 1); |
||||
|
var i = (this._front + length) & (this._capacity - 1); |
||||
|
this[i] = arg; |
||||
|
this._length = length + 1; |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype.push = function (fn, receiver, arg) { |
||||
|
var length = this.length() + 3; |
||||
|
if (this._willBeOverCapacity(length)) { |
||||
|
this._pushOne(fn); |
||||
|
this._pushOne(receiver); |
||||
|
this._pushOne(arg); |
||||
|
return; |
||||
|
} |
||||
|
var j = this._front + length - 3; |
||||
|
this._checkCapacity(length); |
||||
|
var wrapMask = this._capacity - 1; |
||||
|
this[(j + 0) & wrapMask] = fn; |
||||
|
this[(j + 1) & wrapMask] = receiver; |
||||
|
this[(j + 2) & wrapMask] = arg; |
||||
|
this._length = length; |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype.shift = function () { |
||||
|
var front = this._front, |
||||
|
ret = this[front]; |
||||
|
|
||||
|
this[front] = undefined; |
||||
|
this._front = (front + 1) & (this._capacity - 1); |
||||
|
this._length--; |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype.length = function () { |
||||
|
return this._length; |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype._checkCapacity = function (size) { |
||||
|
if (this._capacity < size) { |
||||
|
this._resizeTo(this._capacity << 1); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Queue.prototype._resizeTo = function (capacity) { |
||||
|
var oldCapacity = this._capacity; |
||||
|
this._capacity = capacity; |
||||
|
var front = this._front; |
||||
|
var length = this._length; |
||||
|
var moveItemsCount = (front + length) & (oldCapacity - 1); |
||||
|
arrayMove(this, 0, this, oldCapacity, moveItemsCount); |
||||
|
}; |
||||
|
|
||||
|
module.exports = Queue; |
@ -0,0 +1,49 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function( |
||||
|
Promise, INTERNAL, tryConvertToPromise, apiRejection) { |
||||
|
var util = require("./util"); |
||||
|
|
||||
|
var raceLater = function (promise) { |
||||
|
return promise.then(function(array) { |
||||
|
return race(array, promise); |
||||
|
}); |
||||
|
}; |
||||
|
|
||||
|
function race(promises, parent) { |
||||
|
var maybePromise = tryConvertToPromise(promises); |
||||
|
|
||||
|
if (maybePromise instanceof Promise) { |
||||
|
return raceLater(maybePromise); |
||||
|
} else { |
||||
|
promises = util.asArray(promises); |
||||
|
if (promises === null) |
||||
|
return apiRejection("expecting an array or an iterable object but got " + util.classString(promises)); |
||||
|
} |
||||
|
|
||||
|
var ret = new Promise(INTERNAL); |
||||
|
if (parent !== undefined) { |
||||
|
ret._propagateFrom(parent, 3); |
||||
|
} |
||||
|
var fulfill = ret._fulfill; |
||||
|
var reject = ret._reject; |
||||
|
for (var i = 0, len = promises.length; i < len; ++i) { |
||||
|
var val = promises[i]; |
||||
|
|
||||
|
if (val === undefined && !(i in promises)) { |
||||
|
continue; |
||||
|
} |
||||
|
|
||||
|
Promise.cast(val)._then(fulfill, reject, undefined, ret, null); |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
Promise.race = function (promises) { |
||||
|
return race(promises, undefined); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.race = function () { |
||||
|
return race(this, undefined); |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,172 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, |
||||
|
PromiseArray, |
||||
|
apiRejection, |
||||
|
tryConvertToPromise, |
||||
|
INTERNAL, |
||||
|
debug) { |
||||
|
var getDomain = Promise._getDomain; |
||||
|
var util = require("./util"); |
||||
|
var tryCatch = util.tryCatch; |
||||
|
|
||||
|
function ReductionPromiseArray(promises, fn, initialValue, _each) { |
||||
|
this.constructor$(promises); |
||||
|
var domain = getDomain(); |
||||
|
this._fn = domain === null ? fn : util.domainBind(domain, fn); |
||||
|
if (initialValue !== undefined) { |
||||
|
initialValue = Promise.resolve(initialValue); |
||||
|
initialValue._attachCancellationCallback(this); |
||||
|
} |
||||
|
this._initialValue = initialValue; |
||||
|
this._currentCancellable = null; |
||||
|
if(_each === INTERNAL) { |
||||
|
this._eachValues = Array(this._length); |
||||
|
} else if (_each === 0) { |
||||
|
this._eachValues = null; |
||||
|
} else { |
||||
|
this._eachValues = undefined; |
||||
|
} |
||||
|
this._promise._captureStackTrace(); |
||||
|
this._init$(undefined, -5); |
||||
|
} |
||||
|
util.inherits(ReductionPromiseArray, PromiseArray); |
||||
|
|
||||
|
ReductionPromiseArray.prototype._gotAccum = function(accum) { |
||||
|
if (this._eachValues !== undefined && |
||||
|
this._eachValues !== null && |
||||
|
accum !== INTERNAL) { |
||||
|
this._eachValues.push(accum); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._eachComplete = function(value) { |
||||
|
if (this._eachValues !== null) { |
||||
|
this._eachValues.push(value); |
||||
|
} |
||||
|
return this._eachValues; |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._init = function() {}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._resolveEmptyArray = function() { |
||||
|
this._resolve(this._eachValues !== undefined ? this._eachValues |
||||
|
: this._initialValue); |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype.shouldCopyValues = function () { |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._resolve = function(value) { |
||||
|
this._promise._resolveCallback(value); |
||||
|
this._values = null; |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._resultCancelled = function(sender) { |
||||
|
if (sender === this._initialValue) return this._cancel(); |
||||
|
if (this._isResolved()) return; |
||||
|
this._resultCancelled$(); |
||||
|
if (this._currentCancellable instanceof Promise) { |
||||
|
this._currentCancellable.cancel(); |
||||
|
} |
||||
|
if (this._initialValue instanceof Promise) { |
||||
|
this._initialValue.cancel(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
ReductionPromiseArray.prototype._iterate = function (values) { |
||||
|
this._values = values; |
||||
|
var value; |
||||
|
var i; |
||||
|
var length = values.length; |
||||
|
if (this._initialValue !== undefined) { |
||||
|
value = this._initialValue; |
||||
|
i = 0; |
||||
|
} else { |
||||
|
value = Promise.resolve(values[0]); |
||||
|
i = 1; |
||||
|
} |
||||
|
|
||||
|
this._currentCancellable = value; |
||||
|
|
||||
|
if (!value.isRejected()) { |
||||
|
for (; i < length; ++i) { |
||||
|
var ctx = { |
||||
|
accum: null, |
||||
|
value: values[i], |
||||
|
index: i, |
||||
|
length: length, |
||||
|
array: this |
||||
|
}; |
||||
|
value = value._then(gotAccum, undefined, undefined, ctx, undefined); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (this._eachValues !== undefined) { |
||||
|
value = value |
||||
|
._then(this._eachComplete, undefined, undefined, this, undefined); |
||||
|
} |
||||
|
value._then(completed, completed, undefined, value, this); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.reduce = function (fn, initialValue) { |
||||
|
return reduce(this, fn, initialValue, null); |
||||
|
}; |
||||
|
|
||||
|
Promise.reduce = function (promises, fn, initialValue, _each) { |
||||
|
return reduce(promises, fn, initialValue, _each); |
||||
|
}; |
||||
|
|
||||
|
function completed(valueOrReason, array) { |
||||
|
if (this.isFulfilled()) { |
||||
|
array._resolve(valueOrReason); |
||||
|
} else { |
||||
|
array._reject(valueOrReason); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function reduce(promises, fn, initialValue, _each) { |
||||
|
if (typeof fn !== "function") { |
||||
|
return apiRejection("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
var array = new ReductionPromiseArray(promises, fn, initialValue, _each); |
||||
|
return array.promise(); |
||||
|
} |
||||
|
|
||||
|
function gotAccum(accum) { |
||||
|
this.accum = accum; |
||||
|
this.array._gotAccum(accum); |
||||
|
var value = tryConvertToPromise(this.value, this.array._promise); |
||||
|
if (value instanceof Promise) { |
||||
|
this.array._currentCancellable = value; |
||||
|
return value._then(gotValue, undefined, undefined, this, undefined); |
||||
|
} else { |
||||
|
return gotValue.call(this, value); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function gotValue(value) { |
||||
|
var array = this.array; |
||||
|
var promise = array._promise; |
||||
|
var fn = tryCatch(array._fn); |
||||
|
promise._pushContext(); |
||||
|
var ret; |
||||
|
if (array._eachValues !== undefined) { |
||||
|
ret = fn.call(promise._boundValue(), value, this.index, this.length); |
||||
|
} else { |
||||
|
ret = fn.call(promise._boundValue(), |
||||
|
this.accum, value, this.index, this.length); |
||||
|
} |
||||
|
if (ret instanceof Promise) { |
||||
|
array._currentCancellable = ret; |
||||
|
} |
||||
|
var promiseCreated = promise._popContext(); |
||||
|
debug.checkForgottenReturns( |
||||
|
ret, |
||||
|
promiseCreated, |
||||
|
array._eachValues !== undefined ? "Promise.each" : "Promise.reduce", |
||||
|
promise |
||||
|
); |
||||
|
return ret; |
||||
|
} |
||||
|
}; |
@ -0,0 +1,61 @@ |
|||||
|
"use strict"; |
||||
|
var util = require("./util"); |
||||
|
var schedule; |
||||
|
var noAsyncScheduler = function() { |
||||
|
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
}; |
||||
|
var NativePromise = util.getNativePromise(); |
||||
|
if (util.isNode && typeof MutationObserver === "undefined") { |
||||
|
var GlobalSetImmediate = global.setImmediate; |
||||
|
var ProcessNextTick = process.nextTick; |
||||
|
schedule = util.isRecentNode |
||||
|
? function(fn) { GlobalSetImmediate.call(global, fn); } |
||||
|
: function(fn) { ProcessNextTick.call(process, fn); }; |
||||
|
} else if (typeof NativePromise === "function" && |
||||
|
typeof NativePromise.resolve === "function") { |
||||
|
var nativePromise = NativePromise.resolve(); |
||||
|
schedule = function(fn) { |
||||
|
nativePromise.then(fn); |
||||
|
}; |
||||
|
} else if ((typeof MutationObserver !== "undefined") && |
||||
|
!(typeof window !== "undefined" && |
||||
|
window.navigator && |
||||
|
(window.navigator.standalone || window.cordova))) { |
||||
|
schedule = (function() { |
||||
|
var div = document.createElement("div"); |
||||
|
var opts = {attributes: true}; |
||||
|
var toggleScheduled = false; |
||||
|
var div2 = document.createElement("div"); |
||||
|
var o2 = new MutationObserver(function() { |
||||
|
div.classList.toggle("foo"); |
||||
|
toggleScheduled = false; |
||||
|
}); |
||||
|
o2.observe(div2, opts); |
||||
|
|
||||
|
var scheduleToggle = function() { |
||||
|
if (toggleScheduled) return; |
||||
|
toggleScheduled = true; |
||||
|
div2.classList.toggle("foo"); |
||||
|
}; |
||||
|
|
||||
|
return function schedule(fn) { |
||||
|
var o = new MutationObserver(function() { |
||||
|
o.disconnect(); |
||||
|
fn(); |
||||
|
}); |
||||
|
o.observe(div, opts); |
||||
|
scheduleToggle(); |
||||
|
}; |
||||
|
})(); |
||||
|
} else if (typeof setImmediate !== "undefined") { |
||||
|
schedule = function (fn) { |
||||
|
setImmediate(fn); |
||||
|
}; |
||||
|
} else if (typeof setTimeout !== "undefined") { |
||||
|
schedule = function (fn) { |
||||
|
setTimeout(fn, 0); |
||||
|
}; |
||||
|
} else { |
||||
|
schedule = noAsyncScheduler; |
||||
|
} |
||||
|
module.exports = schedule; |
@ -0,0 +1,43 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = |
||||
|
function(Promise, PromiseArray, debug) { |
||||
|
var PromiseInspection = Promise.PromiseInspection; |
||||
|
var util = require("./util"); |
||||
|
|
||||
|
function SettledPromiseArray(values) { |
||||
|
this.constructor$(values); |
||||
|
} |
||||
|
util.inherits(SettledPromiseArray, PromiseArray); |
||||
|
|
||||
|
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) { |
||||
|
this._values[index] = inspection; |
||||
|
var totalResolved = ++this._totalResolved; |
||||
|
if (totalResolved >= this._length) { |
||||
|
this._resolve(this._values); |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) { |
||||
|
var ret = new PromiseInspection(); |
||||
|
ret._bitField = 33554432; |
||||
|
ret._settledValueField = value; |
||||
|
return this._promiseResolved(index, ret); |
||||
|
}; |
||||
|
SettledPromiseArray.prototype._promiseRejected = function (reason, index) { |
||||
|
var ret = new PromiseInspection(); |
||||
|
ret._bitField = 16777216; |
||||
|
ret._settledValueField = reason; |
||||
|
return this._promiseResolved(index, ret); |
||||
|
}; |
||||
|
|
||||
|
Promise.settle = function (promises) { |
||||
|
debug.deprecated(".settle()", ".reflect()"); |
||||
|
return new SettledPromiseArray(promises).promise(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.settle = function () { |
||||
|
return Promise.settle(this); |
||||
|
}; |
||||
|
}; |
@ -0,0 +1,148 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = |
||||
|
function(Promise, PromiseArray, apiRejection) { |
||||
|
var util = require("./util"); |
||||
|
var RangeError = require("./errors").RangeError; |
||||
|
var AggregateError = require("./errors").AggregateError; |
||||
|
var isArray = util.isArray; |
||||
|
var CANCELLATION = {}; |
||||
|
|
||||
|
|
||||
|
function SomePromiseArray(values) { |
||||
|
this.constructor$(values); |
||||
|
this._howMany = 0; |
||||
|
this._unwrap = false; |
||||
|
this._initialized = false; |
||||
|
} |
||||
|
util.inherits(SomePromiseArray, PromiseArray); |
||||
|
|
||||
|
SomePromiseArray.prototype._init = function () { |
||||
|
if (!this._initialized) { |
||||
|
return; |
||||
|
} |
||||
|
if (this._howMany === 0) { |
||||
|
this._resolve([]); |
||||
|
return; |
||||
|
} |
||||
|
this._init$(undefined, -5); |
||||
|
var isArrayResolved = isArray(this._values); |
||||
|
if (!this._isResolved() && |
||||
|
isArrayResolved && |
||||
|
this._howMany > this._canPossiblyFulfill()) { |
||||
|
this._reject(this._getRangeError(this.length())); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype.init = function () { |
||||
|
this._initialized = true; |
||||
|
this._init(); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype.setUnwrap = function () { |
||||
|
this._unwrap = true; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype.howMany = function () { |
||||
|
return this._howMany; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype.setHowMany = function (count) { |
||||
|
this._howMany = count; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._promiseFulfilled = function (value) { |
||||
|
this._addFulfilled(value); |
||||
|
if (this._fulfilled() === this.howMany()) { |
||||
|
this._values.length = this.howMany(); |
||||
|
if (this.howMany() === 1 && this._unwrap) { |
||||
|
this._resolve(this._values[0]); |
||||
|
} else { |
||||
|
this._resolve(this._values); |
||||
|
} |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
|
||||
|
}; |
||||
|
SomePromiseArray.prototype._promiseRejected = function (reason) { |
||||
|
this._addRejected(reason); |
||||
|
return this._checkOutcome(); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._promiseCancelled = function () { |
||||
|
if (this._values instanceof Promise || this._values == null) { |
||||
|
return this._cancel(); |
||||
|
} |
||||
|
this._addRejected(CANCELLATION); |
||||
|
return this._checkOutcome(); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._checkOutcome = function() { |
||||
|
if (this.howMany() > this._canPossiblyFulfill()) { |
||||
|
var e = new AggregateError(); |
||||
|
for (var i = this.length(); i < this._values.length; ++i) { |
||||
|
if (this._values[i] !== CANCELLATION) { |
||||
|
e.push(this._values[i]); |
||||
|
} |
||||
|
} |
||||
|
if (e.length > 0) { |
||||
|
this._reject(e); |
||||
|
} else { |
||||
|
this._cancel(); |
||||
|
} |
||||
|
return true; |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._fulfilled = function () { |
||||
|
return this._totalResolved; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._rejected = function () { |
||||
|
return this._values.length - this.length(); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._addRejected = function (reason) { |
||||
|
this._values.push(reason); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._addFulfilled = function (value) { |
||||
|
this._values[this._totalResolved++] = value; |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._canPossiblyFulfill = function () { |
||||
|
return this.length() - this._rejected(); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._getRangeError = function (count) { |
||||
|
var message = "Input array must contain at least " + |
||||
|
this._howMany + " items but contains only " + count + " items"; |
||||
|
return new RangeError(message); |
||||
|
}; |
||||
|
|
||||
|
SomePromiseArray.prototype._resolveEmptyArray = function () { |
||||
|
this._reject(this._getRangeError(0)); |
||||
|
}; |
||||
|
|
||||
|
function some(promises, howMany) { |
||||
|
if ((howMany | 0) !== howMany || howMany < 0) { |
||||
|
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
var ret = new SomePromiseArray(promises); |
||||
|
var promise = ret.promise(); |
||||
|
ret.setHowMany(howMany); |
||||
|
ret.init(); |
||||
|
return promise; |
||||
|
} |
||||
|
|
||||
|
Promise.some = function (promises, howMany) { |
||||
|
return some(promises, howMany); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.some = function (howMany) { |
||||
|
return some(this, howMany); |
||||
|
}; |
||||
|
|
||||
|
Promise._SomePromiseArray = SomePromiseArray; |
||||
|
}; |
@ -0,0 +1,103 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise) { |
||||
|
function PromiseInspection(promise) { |
||||
|
if (promise !== undefined) { |
||||
|
promise = promise._target(); |
||||
|
this._bitField = promise._bitField; |
||||
|
this._settledValueField = promise._isFateSealed() |
||||
|
? promise._settledValue() : undefined; |
||||
|
} |
||||
|
else { |
||||
|
this._bitField = 0; |
||||
|
this._settledValueField = undefined; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
PromiseInspection.prototype._settledValue = function() { |
||||
|
return this._settledValueField; |
||||
|
}; |
||||
|
|
||||
|
var value = PromiseInspection.prototype.value = function () { |
||||
|
if (!this.isFulfilled()) { |
||||
|
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
return this._settledValue(); |
||||
|
}; |
||||
|
|
||||
|
var reason = PromiseInspection.prototype.error = |
||||
|
PromiseInspection.prototype.reason = function () { |
||||
|
if (!this.isRejected()) { |
||||
|
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a"); |
||||
|
} |
||||
|
return this._settledValue(); |
||||
|
}; |
||||
|
|
||||
|
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() { |
||||
|
return (this._bitField & 33554432) !== 0; |
||||
|
}; |
||||
|
|
||||
|
var isRejected = PromiseInspection.prototype.isRejected = function () { |
||||
|
return (this._bitField & 16777216) !== 0; |
||||
|
}; |
||||
|
|
||||
|
var isPending = PromiseInspection.prototype.isPending = function () { |
||||
|
return (this._bitField & 50397184) === 0; |
||||
|
}; |
||||
|
|
||||
|
var isResolved = PromiseInspection.prototype.isResolved = function () { |
||||
|
return (this._bitField & 50331648) !== 0; |
||||
|
}; |
||||
|
|
||||
|
PromiseInspection.prototype.isCancelled = function() { |
||||
|
return (this._bitField & 8454144) !== 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.__isCancelled = function() { |
||||
|
return (this._bitField & 65536) === 65536; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isCancelled = function() { |
||||
|
return this._target().__isCancelled(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isCancelled = function() { |
||||
|
return (this._target()._bitField & 8454144) !== 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isPending = function() { |
||||
|
return isPending.call(this._target()); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isRejected = function() { |
||||
|
return isRejected.call(this._target()); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isFulfilled = function() { |
||||
|
return isFulfilled.call(this._target()); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.isResolved = function() { |
||||
|
return isResolved.call(this._target()); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.value = function() { |
||||
|
return value.call(this._target()); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.reason = function() { |
||||
|
var target = this._target(); |
||||
|
target._unsetRejectionIsUnhandled(); |
||||
|
return reason.call(target); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._value = function() { |
||||
|
return this._settledValue(); |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._reason = function() { |
||||
|
this._unsetRejectionIsUnhandled(); |
||||
|
return this._settledValue(); |
||||
|
}; |
||||
|
|
||||
|
Promise.PromiseInspection = PromiseInspection; |
||||
|
}; |
@ -0,0 +1,86 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL) { |
||||
|
var util = require("./util"); |
||||
|
var errorObj = util.errorObj; |
||||
|
var isObject = util.isObject; |
||||
|
|
||||
|
function tryConvertToPromise(obj, context) { |
||||
|
if (isObject(obj)) { |
||||
|
if (obj instanceof Promise) return obj; |
||||
|
var then = getThen(obj); |
||||
|
if (then === errorObj) { |
||||
|
if (context) context._pushContext(); |
||||
|
var ret = Promise.reject(then.e); |
||||
|
if (context) context._popContext(); |
||||
|
return ret; |
||||
|
} else if (typeof then === "function") { |
||||
|
if (isAnyBluebirdPromise(obj)) { |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
obj._then( |
||||
|
ret._fulfill, |
||||
|
ret._reject, |
||||
|
undefined, |
||||
|
ret, |
||||
|
null |
||||
|
); |
||||
|
return ret; |
||||
|
} |
||||
|
return doThenable(obj, then, context); |
||||
|
} |
||||
|
} |
||||
|
return obj; |
||||
|
} |
||||
|
|
||||
|
function doGetThen(obj) { |
||||
|
return obj.then; |
||||
|
} |
||||
|
|
||||
|
function getThen(obj) { |
||||
|
try { |
||||
|
return doGetThen(obj); |
||||
|
} catch (e) { |
||||
|
errorObj.e = e; |
||||
|
return errorObj; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var hasProp = {}.hasOwnProperty; |
||||
|
function isAnyBluebirdPromise(obj) { |
||||
|
try { |
||||
|
return hasProp.call(obj, "_promise0"); |
||||
|
} catch (e) { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function doThenable(x, then, context) { |
||||
|
var promise = new Promise(INTERNAL); |
||||
|
var ret = promise; |
||||
|
if (context) context._pushContext(); |
||||
|
promise._captureStackTrace(); |
||||
|
if (context) context._popContext(); |
||||
|
var synchronous = true; |
||||
|
var result = util.tryCatch(then).call(x, resolve, reject); |
||||
|
synchronous = false; |
||||
|
|
||||
|
if (promise && result === errorObj) { |
||||
|
promise._rejectCallback(result.e, true, true); |
||||
|
promise = null; |
||||
|
} |
||||
|
|
||||
|
function resolve(value) { |
||||
|
if (!promise) return; |
||||
|
promise._resolveCallback(value); |
||||
|
promise = null; |
||||
|
} |
||||
|
|
||||
|
function reject(reason) { |
||||
|
if (!promise) return; |
||||
|
promise._rejectCallback(reason, synchronous, true); |
||||
|
promise = null; |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
return tryConvertToPromise; |
||||
|
}; |
@ -0,0 +1,93 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function(Promise, INTERNAL, debug) { |
||||
|
var util = require("./util"); |
||||
|
var TimeoutError = Promise.TimeoutError; |
||||
|
|
||||
|
function HandleWrapper(handle) { |
||||
|
this.handle = handle; |
||||
|
} |
||||
|
|
||||
|
HandleWrapper.prototype._resultCancelled = function() { |
||||
|
clearTimeout(this.handle); |
||||
|
}; |
||||
|
|
||||
|
var afterValue = function(value) { return delay(+this).thenReturn(value); }; |
||||
|
var delay = Promise.delay = function (ms, value) { |
||||
|
var ret; |
||||
|
var handle; |
||||
|
if (value !== undefined) { |
||||
|
ret = Promise.resolve(value) |
||||
|
._then(afterValue, null, null, ms, undefined); |
||||
|
if (debug.cancellation() && value instanceof Promise) { |
||||
|
ret._setOnCancel(value); |
||||
|
} |
||||
|
} else { |
||||
|
ret = new Promise(INTERNAL); |
||||
|
handle = setTimeout(function() { ret._fulfill(); }, +ms); |
||||
|
if (debug.cancellation()) { |
||||
|
ret._setOnCancel(new HandleWrapper(handle)); |
||||
|
} |
||||
|
ret._captureStackTrace(); |
||||
|
} |
||||
|
ret._setAsyncGuaranteed(); |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.delay = function (ms) { |
||||
|
return delay(ms, this); |
||||
|
}; |
||||
|
|
||||
|
var afterTimeout = function (promise, message, parent) { |
||||
|
var err; |
||||
|
if (typeof message !== "string") { |
||||
|
if (message instanceof Error) { |
||||
|
err = message; |
||||
|
} else { |
||||
|
err = new TimeoutError("operation timed out"); |
||||
|
} |
||||
|
} else { |
||||
|
err = new TimeoutError(message); |
||||
|
} |
||||
|
util.markAsOriginatingFromRejection(err); |
||||
|
promise._attachExtraTrace(err); |
||||
|
promise._reject(err); |
||||
|
|
||||
|
if (parent != null) { |
||||
|
parent.cancel(); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
function successClear(value) { |
||||
|
clearTimeout(this.handle); |
||||
|
return value; |
||||
|
} |
||||
|
|
||||
|
function failureClear(reason) { |
||||
|
clearTimeout(this.handle); |
||||
|
throw reason; |
||||
|
} |
||||
|
|
||||
|
Promise.prototype.timeout = function (ms, message) { |
||||
|
ms = +ms; |
||||
|
var ret, parent; |
||||
|
|
||||
|
var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() { |
||||
|
if (ret.isPending()) { |
||||
|
afterTimeout(ret, message, parent); |
||||
|
} |
||||
|
}, ms)); |
||||
|
|
||||
|
if (debug.cancellation()) { |
||||
|
parent = this.then(); |
||||
|
ret = parent._then(successClear, failureClear, |
||||
|
undefined, handleWrapper, undefined); |
||||
|
ret._setOnCancel(handleWrapper); |
||||
|
} else { |
||||
|
ret = this._then(successClear, failureClear, |
||||
|
undefined, handleWrapper, undefined); |
||||
|
} |
||||
|
|
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,226 @@ |
|||||
|
"use strict"; |
||||
|
module.exports = function (Promise, apiRejection, tryConvertToPromise, |
||||
|
createContext, INTERNAL, debug) { |
||||
|
var util = require("./util"); |
||||
|
var TypeError = require("./errors").TypeError; |
||||
|
var inherits = require("./util").inherits; |
||||
|
var errorObj = util.errorObj; |
||||
|
var tryCatch = util.tryCatch; |
||||
|
var NULL = {}; |
||||
|
|
||||
|
function thrower(e) { |
||||
|
setTimeout(function(){throw e;}, 0); |
||||
|
} |
||||
|
|
||||
|
function castPreservingDisposable(thenable) { |
||||
|
var maybePromise = tryConvertToPromise(thenable); |
||||
|
if (maybePromise !== thenable && |
||||
|
typeof thenable._isDisposable === "function" && |
||||
|
typeof thenable._getDisposer === "function" && |
||||
|
thenable._isDisposable()) { |
||||
|
maybePromise._setDisposable(thenable._getDisposer()); |
||||
|
} |
||||
|
return maybePromise; |
||||
|
} |
||||
|
function dispose(resources, inspection) { |
||||
|
var i = 0; |
||||
|
var len = resources.length; |
||||
|
var ret = new Promise(INTERNAL); |
||||
|
function iterator() { |
||||
|
if (i >= len) return ret._fulfill(); |
||||
|
var maybePromise = castPreservingDisposable(resources[i++]); |
||||
|
if (maybePromise instanceof Promise && |
||||
|
maybePromise._isDisposable()) { |
||||
|
try { |
||||
|
maybePromise = tryConvertToPromise( |
||||
|
maybePromise._getDisposer().tryDispose(inspection), |
||||
|
resources.promise); |
||||
|
} catch (e) { |
||||
|
return thrower(e); |
||||
|
} |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
return maybePromise._then(iterator, thrower, |
||||
|
null, null, null); |
||||
|
} |
||||
|
} |
||||
|
iterator(); |
||||
|
} |
||||
|
iterator(); |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
function Disposer(data, promise, context) { |
||||
|
this._data = data; |
||||
|
this._promise = promise; |
||||
|
this._context = context; |
||||
|
} |
||||
|
|
||||
|
Disposer.prototype.data = function () { |
||||
|
return this._data; |
||||
|
}; |
||||
|
|
||||
|
Disposer.prototype.promise = function () { |
||||
|
return this._promise; |
||||
|
}; |
||||
|
|
||||
|
Disposer.prototype.resource = function () { |
||||
|
if (this.promise().isFulfilled()) { |
||||
|
return this.promise().value(); |
||||
|
} |
||||
|
return NULL; |
||||
|
}; |
||||
|
|
||||
|
Disposer.prototype.tryDispose = function(inspection) { |
||||
|
var resource = this.resource(); |
||||
|
var context = this._context; |
||||
|
if (context !== undefined) context._pushContext(); |
||||
|
var ret = resource !== NULL |
||||
|
? this.doDispose(resource, inspection) : null; |
||||
|
if (context !== undefined) context._popContext(); |
||||
|
this._promise._unsetDisposable(); |
||||
|
this._data = null; |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
Disposer.isDisposer = function (d) { |
||||
|
return (d != null && |
||||
|
typeof d.resource === "function" && |
||||
|
typeof d.tryDispose === "function"); |
||||
|
}; |
||||
|
|
||||
|
function FunctionDisposer(fn, promise, context) { |
||||
|
this.constructor$(fn, promise, context); |
||||
|
} |
||||
|
inherits(FunctionDisposer, Disposer); |
||||
|
|
||||
|
FunctionDisposer.prototype.doDispose = function (resource, inspection) { |
||||
|
var fn = this.data(); |
||||
|
return fn.call(resource, resource, inspection); |
||||
|
}; |
||||
|
|
||||
|
function maybeUnwrapDisposer(value) { |
||||
|
if (Disposer.isDisposer(value)) { |
||||
|
this.resources[this.index]._setDisposable(value); |
||||
|
return value.promise(); |
||||
|
} |
||||
|
return value; |
||||
|
} |
||||
|
|
||||
|
function ResourceList(length) { |
||||
|
this.length = length; |
||||
|
this.promise = null; |
||||
|
this[length-1] = null; |
||||
|
} |
||||
|
|
||||
|
ResourceList.prototype._resultCancelled = function() { |
||||
|
var len = this.length; |
||||
|
for (var i = 0; i < len; ++i) { |
||||
|
var item = this[i]; |
||||
|
if (item instanceof Promise) { |
||||
|
item.cancel(); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Promise.using = function () { |
||||
|
var len = arguments.length; |
||||
|
if (len < 2) return apiRejection( |
||||
|
"you must pass at least 2 arguments to Promise.using"); |
||||
|
var fn = arguments[len - 1]; |
||||
|
if (typeof fn !== "function") { |
||||
|
return apiRejection("expecting a function but got " + util.classString(fn)); |
||||
|
} |
||||
|
var input; |
||||
|
var spreadArgs = true; |
||||
|
if (len === 2 && Array.isArray(arguments[0])) { |
||||
|
input = arguments[0]; |
||||
|
len = input.length; |
||||
|
spreadArgs = false; |
||||
|
} else { |
||||
|
input = arguments; |
||||
|
len--; |
||||
|
} |
||||
|
var resources = new ResourceList(len); |
||||
|
for (var i = 0; i < len; ++i) { |
||||
|
var resource = input[i]; |
||||
|
if (Disposer.isDisposer(resource)) { |
||||
|
var disposer = resource; |
||||
|
resource = resource.promise(); |
||||
|
resource._setDisposable(disposer); |
||||
|
} else { |
||||
|
var maybePromise = tryConvertToPromise(resource); |
||||
|
if (maybePromise instanceof Promise) { |
||||
|
resource = |
||||
|
maybePromise._then(maybeUnwrapDisposer, null, null, { |
||||
|
resources: resources, |
||||
|
index: i |
||||
|
}, undefined); |
||||
|
} |
||||
|
} |
||||
|
resources[i] = resource; |
||||
|
} |
||||
|
|
||||
|
var reflectedResources = new Array(resources.length); |
||||
|
for (var i = 0; i < reflectedResources.length; ++i) { |
||||
|
reflectedResources[i] = Promise.resolve(resources[i]).reflect(); |
||||
|
} |
||||
|
|
||||
|
var resultPromise = Promise.all(reflectedResources) |
||||
|
.then(function(inspections) { |
||||
|
for (var i = 0; i < inspections.length; ++i) { |
||||
|
var inspection = inspections[i]; |
||||
|
if (inspection.isRejected()) { |
||||
|
errorObj.e = inspection.error(); |
||||
|
return errorObj; |
||||
|
} else if (!inspection.isFulfilled()) { |
||||
|
resultPromise.cancel(); |
||||
|
return; |
||||
|
} |
||||
|
inspections[i] = inspection.value(); |
||||
|
} |
||||
|
promise._pushContext(); |
||||
|
|
||||
|
fn = tryCatch(fn); |
||||
|
var ret = spreadArgs |
||||
|
? fn.apply(undefined, inspections) : fn(inspections); |
||||
|
var promiseCreated = promise._popContext(); |
||||
|
debug.checkForgottenReturns( |
||||
|
ret, promiseCreated, "Promise.using", promise); |
||||
|
return ret; |
||||
|
}); |
||||
|
|
||||
|
var promise = resultPromise.lastly(function() { |
||||
|
var inspection = new Promise.PromiseInspection(resultPromise); |
||||
|
return dispose(resources, inspection); |
||||
|
}); |
||||
|
resources.promise = promise; |
||||
|
promise._setOnCancel(resources); |
||||
|
return promise; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._setDisposable = function (disposer) { |
||||
|
this._bitField = this._bitField | 131072; |
||||
|
this._disposer = disposer; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._isDisposable = function () { |
||||
|
return (this._bitField & 131072) > 0; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._getDisposer = function () { |
||||
|
return this._disposer; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype._unsetDisposable = function () { |
||||
|
this._bitField = this._bitField & (~131072); |
||||
|
this._disposer = undefined; |
||||
|
}; |
||||
|
|
||||
|
Promise.prototype.disposer = function (fn) { |
||||
|
if (typeof fn === "function") { |
||||
|
return new FunctionDisposer(fn, this, createContext()); |
||||
|
} |
||||
|
throw new TypeError(); |
||||
|
}; |
||||
|
|
||||
|
}; |
@ -0,0 +1,380 @@ |
|||||
|
"use strict"; |
||||
|
var es5 = require("./es5"); |
||||
|
var canEvaluate = typeof navigator == "undefined"; |
||||
|
|
||||
|
var errorObj = {e: {}}; |
||||
|
var tryCatchTarget; |
||||
|
var globalObject = typeof self !== "undefined" ? self : |
||||
|
typeof window !== "undefined" ? window : |
||||
|
typeof global !== "undefined" ? global : |
||||
|
this !== undefined ? this : null; |
||||
|
|
||||
|
function tryCatcher() { |
||||
|
try { |
||||
|
var target = tryCatchTarget; |
||||
|
tryCatchTarget = null; |
||||
|
return target.apply(this, arguments); |
||||
|
} catch (e) { |
||||
|
errorObj.e = e; |
||||
|
return errorObj; |
||||
|
} |
||||
|
} |
||||
|
function tryCatch(fn) { |
||||
|
tryCatchTarget = fn; |
||||
|
return tryCatcher; |
||||
|
} |
||||
|
|
||||
|
var inherits = function(Child, Parent) { |
||||
|
var hasProp = {}.hasOwnProperty; |
||||
|
|
||||
|
function T() { |
||||
|
this.constructor = Child; |
||||
|
this.constructor$ = Parent; |
||||
|
for (var propertyName in Parent.prototype) { |
||||
|
if (hasProp.call(Parent.prototype, propertyName) && |
||||
|
propertyName.charAt(propertyName.length-1) !== "$" |
||||
|
) { |
||||
|
this[propertyName + "$"] = Parent.prototype[propertyName]; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
T.prototype = Parent.prototype; |
||||
|
Child.prototype = new T(); |
||||
|
return Child.prototype; |
||||
|
}; |
||||
|
|
||||
|
|
||||
|
function isPrimitive(val) { |
||||
|
return val == null || val === true || val === false || |
||||
|
typeof val === "string" || typeof val === "number"; |
||||
|
|
||||
|
} |
||||
|
|
||||
|
function isObject(value) { |
||||
|
return typeof value === "function" || |
||||
|
typeof value === "object" && value !== null; |
||||
|
} |
||||
|
|
||||
|
function maybeWrapAsError(maybeError) { |
||||
|
if (!isPrimitive(maybeError)) return maybeError; |
||||
|
|
||||
|
return new Error(safeToString(maybeError)); |
||||
|
} |
||||
|
|
||||
|
function withAppended(target, appendee) { |
||||
|
var len = target.length; |
||||
|
var ret = new Array(len + 1); |
||||
|
var i; |
||||
|
for (i = 0; i < len; ++i) { |
||||
|
ret[i] = target[i]; |
||||
|
} |
||||
|
ret[i] = appendee; |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
function getDataPropertyOrDefault(obj, key, defaultValue) { |
||||
|
if (es5.isES5) { |
||||
|
var desc = Object.getOwnPropertyDescriptor(obj, key); |
||||
|
|
||||
|
if (desc != null) { |
||||
|
return desc.get == null && desc.set == null |
||||
|
? desc.value |
||||
|
: defaultValue; |
||||
|
} |
||||
|
} else { |
||||
|
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function notEnumerableProp(obj, name, value) { |
||||
|
if (isPrimitive(obj)) return obj; |
||||
|
var descriptor = { |
||||
|
value: value, |
||||
|
configurable: true, |
||||
|
enumerable: false, |
||||
|
writable: true |
||||
|
}; |
||||
|
es5.defineProperty(obj, name, descriptor); |
||||
|
return obj; |
||||
|
} |
||||
|
|
||||
|
function thrower(r) { |
||||
|
throw r; |
||||
|
} |
||||
|
|
||||
|
var inheritedDataKeys = (function() { |
||||
|
var excludedPrototypes = [ |
||||
|
Array.prototype, |
||||
|
Object.prototype, |
||||
|
Function.prototype |
||||
|
]; |
||||
|
|
||||
|
var isExcludedProto = function(val) { |
||||
|
for (var i = 0; i < excludedPrototypes.length; ++i) { |
||||
|
if (excludedPrototypes[i] === val) { |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
if (es5.isES5) { |
||||
|
var getKeys = Object.getOwnPropertyNames; |
||||
|
return function(obj) { |
||||
|
var ret = []; |
||||
|
var visitedKeys = Object.create(null); |
||||
|
while (obj != null && !isExcludedProto(obj)) { |
||||
|
var keys; |
||||
|
try { |
||||
|
keys = getKeys(obj); |
||||
|
} catch (e) { |
||||
|
return ret; |
||||
|
} |
||||
|
for (var i = 0; i < keys.length; ++i) { |
||||
|
var key = keys[i]; |
||||
|
if (visitedKeys[key]) continue; |
||||
|
visitedKeys[key] = true; |
||||
|
var desc = Object.getOwnPropertyDescriptor(obj, key); |
||||
|
if (desc != null && desc.get == null && desc.set == null) { |
||||
|
ret.push(key); |
||||
|
} |
||||
|
} |
||||
|
obj = es5.getPrototypeOf(obj); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
} else { |
||||
|
var hasProp = {}.hasOwnProperty; |
||||
|
return function(obj) { |
||||
|
if (isExcludedProto(obj)) return []; |
||||
|
var ret = []; |
||||
|
|
||||
|
/*jshint forin:false */ |
||||
|
enumeration: for (var key in obj) { |
||||
|
if (hasProp.call(obj, key)) { |
||||
|
ret.push(key); |
||||
|
} else { |
||||
|
for (var i = 0; i < excludedPrototypes.length; ++i) { |
||||
|
if (hasProp.call(excludedPrototypes[i], key)) { |
||||
|
continue enumeration; |
||||
|
} |
||||
|
} |
||||
|
ret.push(key); |
||||
|
} |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
})(); |
||||
|
|
||||
|
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/; |
||||
|
function isClass(fn) { |
||||
|
try { |
||||
|
if (typeof fn === "function") { |
||||
|
var keys = es5.names(fn.prototype); |
||||
|
|
||||
|
var hasMethods = es5.isES5 && keys.length > 1; |
||||
|
var hasMethodsOtherThanConstructor = keys.length > 0 && |
||||
|
!(keys.length === 1 && keys[0] === "constructor"); |
||||
|
var hasThisAssignmentAndStaticMethods = |
||||
|
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0; |
||||
|
|
||||
|
if (hasMethods || hasMethodsOtherThanConstructor || |
||||
|
hasThisAssignmentAndStaticMethods) { |
||||
|
return true; |
||||
|
} |
||||
|
} |
||||
|
return false; |
||||
|
} catch (e) { |
||||
|
return false; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function toFastProperties(obj) { |
||||
|
/*jshint -W027,-W055,-W031*/ |
||||
|
function FakeConstructor() {} |
||||
|
FakeConstructor.prototype = obj; |
||||
|
var l = 8; |
||||
|
while (l--) new FakeConstructor(); |
||||
|
return obj; |
||||
|
eval(obj); |
||||
|
} |
||||
|
|
||||
|
var rident = /^[a-z$_][a-z$_0-9]*$/i; |
||||
|
function isIdentifier(str) { |
||||
|
return rident.test(str); |
||||
|
} |
||||
|
|
||||
|
function filledRange(count, prefix, suffix) { |
||||
|
var ret = new Array(count); |
||||
|
for(var i = 0; i < count; ++i) { |
||||
|
ret[i] = prefix + i + suffix; |
||||
|
} |
||||
|
return ret; |
||||
|
} |
||||
|
|
||||
|
function safeToString(obj) { |
||||
|
try { |
||||
|
return obj + ""; |
||||
|
} catch (e) { |
||||
|
return "[no string representation]"; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function isError(obj) { |
||||
|
return obj instanceof Error || |
||||
|
(obj !== null && |
||||
|
typeof obj === "object" && |
||||
|
typeof obj.message === "string" && |
||||
|
typeof obj.name === "string"); |
||||
|
} |
||||
|
|
||||
|
function markAsOriginatingFromRejection(e) { |
||||
|
try { |
||||
|
notEnumerableProp(e, "isOperational", true); |
||||
|
} |
||||
|
catch(ignore) {} |
||||
|
} |
||||
|
|
||||
|
function originatesFromRejection(e) { |
||||
|
if (e == null) return false; |
||||
|
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) || |
||||
|
e["isOperational"] === true); |
||||
|
} |
||||
|
|
||||
|
function canAttachTrace(obj) { |
||||
|
return isError(obj) && es5.propertyIsWritable(obj, "stack"); |
||||
|
} |
||||
|
|
||||
|
var ensureErrorObject = (function() { |
||||
|
if (!("stack" in new Error())) { |
||||
|
return function(value) { |
||||
|
if (canAttachTrace(value)) return value; |
||||
|
try {throw new Error(safeToString(value));} |
||||
|
catch(err) {return err;} |
||||
|
}; |
||||
|
} else { |
||||
|
return function(value) { |
||||
|
if (canAttachTrace(value)) return value; |
||||
|
return new Error(safeToString(value)); |
||||
|
}; |
||||
|
} |
||||
|
})(); |
||||
|
|
||||
|
function classString(obj) { |
||||
|
return {}.toString.call(obj); |
||||
|
} |
||||
|
|
||||
|
function copyDescriptors(from, to, filter) { |
||||
|
var keys = es5.names(from); |
||||
|
for (var i = 0; i < keys.length; ++i) { |
||||
|
var key = keys[i]; |
||||
|
if (filter(key)) { |
||||
|
try { |
||||
|
es5.defineProperty(to, key, es5.getDescriptor(from, key)); |
||||
|
} catch (ignore) {} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var asArray = function(v) { |
||||
|
if (es5.isArray(v)) { |
||||
|
return v; |
||||
|
} |
||||
|
return null; |
||||
|
}; |
||||
|
|
||||
|
if (typeof Symbol !== "undefined" && Symbol.iterator) { |
||||
|
var ArrayFrom = typeof Array.from === "function" ? function(v) { |
||||
|
return Array.from(v); |
||||
|
} : function(v) { |
||||
|
var ret = []; |
||||
|
var it = v[Symbol.iterator](); |
||||
|
var itResult; |
||||
|
while (!((itResult = it.next()).done)) { |
||||
|
ret.push(itResult.value); |
||||
|
} |
||||
|
return ret; |
||||
|
}; |
||||
|
|
||||
|
asArray = function(v) { |
||||
|
if (es5.isArray(v)) { |
||||
|
return v; |
||||
|
} else if (v != null && typeof v[Symbol.iterator] === "function") { |
||||
|
return ArrayFrom(v); |
||||
|
} |
||||
|
return null; |
||||
|
}; |
||||
|
} |
||||
|
|
||||
|
var isNode = typeof process !== "undefined" && |
||||
|
classString(process).toLowerCase() === "[object process]"; |
||||
|
|
||||
|
var hasEnvVariables = typeof process !== "undefined" && |
||||
|
typeof process.env !== "undefined"; |
||||
|
|
||||
|
function env(key) { |
||||
|
return hasEnvVariables ? process.env[key] : undefined; |
||||
|
} |
||||
|
|
||||
|
function getNativePromise() { |
||||
|
if (typeof Promise === "function") { |
||||
|
try { |
||||
|
var promise = new Promise(function(){}); |
||||
|
if ({}.toString.call(promise) === "[object Promise]") { |
||||
|
return Promise; |
||||
|
} |
||||
|
} catch (e) {} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function domainBind(self, cb) { |
||||
|
return self.bind(cb); |
||||
|
} |
||||
|
|
||||
|
var ret = { |
||||
|
isClass: isClass, |
||||
|
isIdentifier: isIdentifier, |
||||
|
inheritedDataKeys: inheritedDataKeys, |
||||
|
getDataPropertyOrDefault: getDataPropertyOrDefault, |
||||
|
thrower: thrower, |
||||
|
isArray: es5.isArray, |
||||
|
asArray: asArray, |
||||
|
notEnumerableProp: notEnumerableProp, |
||||
|
isPrimitive: isPrimitive, |
||||
|
isObject: isObject, |
||||
|
isError: isError, |
||||
|
canEvaluate: canEvaluate, |
||||
|
errorObj: errorObj, |
||||
|
tryCatch: tryCatch, |
||||
|
inherits: inherits, |
||||
|
withAppended: withAppended, |
||||
|
maybeWrapAsError: maybeWrapAsError, |
||||
|
toFastProperties: toFastProperties, |
||||
|
filledRange: filledRange, |
||||
|
toString: safeToString, |
||||
|
canAttachTrace: canAttachTrace, |
||||
|
ensureErrorObject: ensureErrorObject, |
||||
|
originatesFromRejection: originatesFromRejection, |
||||
|
markAsOriginatingFromRejection: markAsOriginatingFromRejection, |
||||
|
classString: classString, |
||||
|
copyDescriptors: copyDescriptors, |
||||
|
hasDevTools: typeof chrome !== "undefined" && chrome && |
||||
|
typeof chrome.loadTimes === "function", |
||||
|
isNode: isNode, |
||||
|
hasEnvVariables: hasEnvVariables, |
||||
|
env: env, |
||||
|
global: globalObject, |
||||
|
getNativePromise: getNativePromise, |
||||
|
domainBind: domainBind |
||||
|
}; |
||||
|
ret.isRecentNode = ret.isNode && (function() { |
||||
|
var version = process.versions.node.split(".").map(Number); |
||||
|
return (version[0] === 0 && version[1] > 10) || (version[0] > 0); |
||||
|
})(); |
||||
|
|
||||
|
if (ret.isNode) ret.toFastProperties(process); |
||||
|
|
||||
|
try {throw new Error(); } catch (e) {ret.lastLineError = e;} |
||||
|
module.exports = ret; |
@ -0,0 +1,130 @@ |
|||||
|
{ |
||||
|
"_args": [ |
||||
|
[ |
||||
|
"bluebird@3.5.1", |
||||
|
"/home/art/Documents/API-REST-Etudiants/api/node_modules/mquery" |
||||
|
] |
||||
|
], |
||||
|
"_from": "bluebird@3.5.1", |
||||
|
"_id": "bluebird@3.5.1", |
||||
|
"_inCache": true, |
||||
|
"_installable": true, |
||||
|
"_location": "/bluebird", |
||||
|
"_nodeVersion": "8.0.0", |
||||
|
"_npmOperationalInternal": { |
||||
|
"host": "s3://npm-registry-packages", |
||||
|
"tmp": "tmp/bluebird-3.5.1.tgz_1507132268699_0.46325381100177765" |
||||
|
}, |
||||
|
"_npmUser": { |
||||
|
"email": "petka_antonov@hotmail.com", |
||||
|
"name": "esailija" |
||||
|
}, |
||||
|
"_npmVersion": "5.0.2", |
||||
|
"_phantomChildren": {}, |
||||
|
"_requested": { |
||||
|
"name": "bluebird", |
||||
|
"raw": "bluebird@3.5.1", |
||||
|
"rawSpec": "3.5.1", |
||||
|
"scope": null, |
||||
|
"spec": "3.5.1", |
||||
|
"type": "version" |
||||
|
}, |
||||
|
"_requiredBy": [ |
||||
|
"/mquery" |
||||
|
], |
||||
|
"_resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz", |
||||
|
"_shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", |
||||
|
"_shrinkwrap": null, |
||||
|
"_spec": "bluebird@3.5.1", |
||||
|
"_where": "/home/art/Documents/API-REST-Etudiants/api/node_modules/mquery", |
||||
|
"author": { |
||||
|
"email": "petka_antonov@hotmail.com", |
||||
|
"name": "Petka Antonov", |
||||
|
"url": "http://github.com/petkaantonov/" |
||||
|
}, |
||||
|
"browser": "./js/browser/bluebird.js", |
||||
|
"bugs": { |
||||
|
"url": "http://github.com/petkaantonov/bluebird/issues" |
||||
|
}, |
||||
|
"dependencies": {}, |
||||
|
"description": "Full featured Promises/A+ implementation with exceptionally good performance", |
||||
|
"devDependencies": { |
||||
|
"acorn": "~0.6.0", |
||||
|
"baconjs": "^0.7.43", |
||||
|
"bluebird": "^2.9.2", |
||||
|
"body-parser": "^1.10.2", |
||||
|
"browserify": "^8.1.1", |
||||
|
"cli-table": "~0.3.1", |
||||
|
"co": "^4.2.0", |
||||
|
"cross-spawn": "^0.2.3", |
||||
|
"glob": "^4.3.2", |
||||
|
"grunt-saucelabs": "~8.4.1", |
||||
|
"highland": "^2.3.0", |
||||
|
"istanbul": "^0.3.5", |
||||
|
"jshint": "^2.6.0", |
||||
|
"jshint-stylish": "~0.2.0", |
||||
|
"kefir": "^2.4.1", |
||||
|
"mkdirp": "~0.5.0", |
||||
|
"mocha": "~2.1", |
||||
|
"open": "~0.0.5", |
||||
|
"optimist": "~0.6.1", |
||||
|
"rimraf": "~2.2.6", |
||||
|
"rx": "^2.3.25", |
||||
|
"serve-static": "^1.7.1", |
||||
|
"sinon": "~1.7.3", |
||||
|
"uglify-js": "~2.4.16" |
||||
|
}, |
||||
|
"directories": {}, |
||||
|
"dist": { |
||||
|
"integrity": "sha512-MKiLiV+I1AA596t9w1sQJ8jkiSr5+ZKi0WKrYGUn6d1Fx+Ij4tIj+m2WMQSGczs5jZVxV339chE8iwk6F64wjA==", |
||||
|
"shasum": "d9551f9de98f1fcda1e683d17ee91a0602ee2eb9", |
||||
|
"tarball": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.1.tgz" |
||||
|
}, |
||||
|
"files": [ |
||||
|
"LICENSE", |
||||
|
"js/browser", |
||||
|
"js/release" |
||||
|
], |
||||
|
"gitHead": "dcfa52bf8b8a8fc5cfb0ca24bccb33f7493960ae", |
||||
|
"homepage": "https://github.com/petkaantonov/bluebird", |
||||
|
"keywords": [ |
||||
|
"async", |
||||
|
"await", |
||||
|
"deferred", |
||||
|
"deferreds", |
||||
|
"dsl", |
||||
|
"flow control", |
||||
|
"fluent interface", |
||||
|
"future", |
||||
|
"performance", |
||||
|
"promise", |
||||
|
"promises", |
||||
|
"promises-a", |
||||
|
"promises-aplus" |
||||
|
], |
||||
|
"license": "MIT", |
||||
|
"main": "./js/release/bluebird.js", |
||||
|
"maintainers": [ |
||||
|
{ |
||||
|
"name": "esailija", |
||||
|
"email": "petka_antonov@hotmail.com" |
||||
|
} |
||||
|
], |
||||
|
"name": "bluebird", |
||||
|
"optionalDependencies": {}, |
||||
|
"readme": "ERROR: No README data found!", |
||||
|
"repository": { |
||||
|
"type": "git", |
||||
|
"url": "git://github.com/petkaantonov/bluebird.git" |
||||
|
}, |
||||
|
"scripts": { |
||||
|
"generate-browser-core": "node tools/build.js --features=core --no-debug --release --zalgo --browser --minify && mv js/browser/bluebird.js js/browser/bluebird.core.js && mv js/browser/bluebird.min.js js/browser/bluebird.core.min.js", |
||||
|
"generate-browser-full": "node tools/build.js --no-clean --no-debug --release --browser --minify", |
||||
|
"istanbul": "istanbul", |
||||
|
"lint": "node scripts/jshint.js", |
||||
|
"prepublish": "npm run generate-browser-core && npm run generate-browser-full", |
||||
|
"test": "node tools/test.js" |
||||
|
}, |
||||
|
"version": "3.5.1", |
||||
|
"webpack": "./js/release/bluebird.js" |
||||
|
} |
@ -0,0 +1,283 @@ |
|||||
|
<a name="1.1.3"></a> |
||||
|
## [1.1.3](https://github.com/mongodb/js-bson/compare/v1.1.2...v1.1.3) (2019-11-09) |
||||
|
|
||||
|
Reverts 1.1.2 |
||||
|
|
||||
|
<a name="1.1.2"></a> |
||||
|
## [1.1.2](https://github.com/mongodb/js-bson/compare/v1.1.1...v1.1.2) (2019-11-08) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **_bsontype:** only check bsontype if it is a prototype member. ([dd8a349](https://github.com/mongodb/js-bson/commit/dd8a349)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.1.1"></a> |
||||
|
## [1.1.1](https://github.com/mongodb/js-bson/compare/v1.1.0...v1.1.1) (2019-03-08) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **object-id:** support 4.x->1.x interop for MinKey and ObjectId ([53419a5](https://github.com/mongodb/js-bson/commit/53419a5)) |
||||
|
|
||||
|
|
||||
|
### Features |
||||
|
|
||||
|
* replace new Buffer with modern versions ([24aefba](https://github.com/mongodb/js-bson/commit/24aefba)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.1.0"></a> |
||||
|
# [1.1.0](https://github.com/mongodb/js-bson/compare/v1.0.9...v1.1.0) (2018-08-13) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **serializer:** do not use checkKeys for $clusterTime ([573e141](https://github.com/mongodb/js-bson/commit/573e141)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.0.9"></a> |
||||
|
## [1.0.9](https://github.com/mongodb/js-bson/compare/v1.0.8...v1.0.9) (2018-06-07) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **serializer:** remove use of `const` ([5feb12f](https://github.com/mongodb/js-bson/commit/5feb12f)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.0.7"></a> |
||||
|
## [1.0.7](https://github.com/mongodb/js-bson/compare/v1.0.6...v1.0.7) (2018-06-06) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **binary:** add type checking for buffer ([26b05b5](https://github.com/mongodb/js-bson/commit/26b05b5)) |
||||
|
* **bson:** fix custom inspect property ([080323b](https://github.com/mongodb/js-bson/commit/080323b)) |
||||
|
* **readme:** clarify documentation about deserialize methods ([20f764c](https://github.com/mongodb/js-bson/commit/20f764c)) |
||||
|
* **serialization:** normalize function stringification ([1320c10](https://github.com/mongodb/js-bson/commit/1320c10)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.0.6"></a> |
||||
|
## [1.0.6](https://github.com/mongodb/js-bson/compare/v1.0.5...v1.0.6) (2018-03-12) |
||||
|
|
||||
|
|
||||
|
### Features |
||||
|
|
||||
|
* **serialization:** support arbitrary sizes for the internal serialization buffer ([abe97bc](https://github.com/mongodb/js-bson/commit/abe97bc)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
<a name="1.0.5"></a> |
||||
|
## 1.0.5 (2018-02-26) |
||||
|
|
||||
|
|
||||
|
### Bug Fixes |
||||
|
|
||||
|
* **decimal128:** add basic guard against REDOS attacks ([bd61c45](https://github.com/mongodb/js-bson/commit/bd61c45)) |
||||
|
* **objectid:** if pid is 1, use random value ([e188ae6](https://github.com/mongodb/js-bson/commit/e188ae6)) |
||||
|
|
||||
|
|
||||
|
|
||||
|
1.0.4 2016-01-11 |
||||
|
---------------- |
||||
|
- #204 remove Buffer.from as it's partially broken in early 4.x.x. series of node releases. |
||||
|
|
||||
|
1.0.3 2016-01-03 |
||||
|
---------------- |
||||
|
- Fixed toString for ObjectId so it will work with inspect. |
||||
|
|
||||
|
1.0.2 2016-01-02 |
||||
|
---------------- |
||||
|
- Minor optimizations for ObjectID to use Buffer.from where available. |
||||
|
|
||||
|
1.0.1 2016-12-06 |
||||
|
---------------- |
||||
|
- Reverse behavior for undefined to be serialized as NULL. MongoDB 3.4 does not allow for undefined comparisons. |
||||
|
|
||||
|
1.0.0 2016-12-06 |
||||
|
---------------- |
||||
|
- Introduced new BSON API and documentation. |
||||
|
|
||||
|
0.5.7 2016-11-18 |
||||
|
----------------- |
||||
|
- NODE-848 BSON Regex flags must be alphabetically ordered. |
||||
|
|
||||
|
0.5.6 2016-10-19 |
||||
|
----------------- |
||||
|
- NODE-833, Detects cyclic dependencies in documents and throws error if one is found. |
||||
|
- Fix(deserializer): corrected the check for (size + index) comparison… (Issue #195, https://github.com/JoelParke). |
||||
|
|
||||
|
0.5.5 2016-09-15 |
||||
|
----------------- |
||||
|
- Added DBPointer up conversion to DBRef |
||||
|
|
||||
|
0.5.4 2016-08-23 |
||||
|
----------------- |
||||
|
- Added promoteValues flag (default to true) allowing user to specify if deserialization should be into wrapper classes only. |
||||
|
|
||||
|
0.5.3 2016-07-11 |
||||
|
----------------- |
||||
|
- Throw error if ObjectId is not a string or a buffer. |
||||
|
|
||||
|
0.5.2 2016-07-11 |
||||
|
----------------- |
||||
|
- All values encoded big-endian style for ObjectId. |
||||
|
|
||||
|
0.5.1 2016-07-11 |
||||
|
----------------- |
||||
|
- Fixed encoding/decoding issue in ObjectId timestamp generation. |
||||
|
- Removed BinaryParser dependency from the serializer/deserializer. |
||||
|
|
||||
|
0.5.0 2016-07-05 |
||||
|
----------------- |
||||
|
- Added Decimal128 type and extended test suite to include entire bson corpus. |
||||
|
|
||||
|
0.4.23 2016-04-08 |
||||
|
----------------- |
||||
|
- Allow for proper detection of ObjectId or objects that look like ObjectId, improving compatibility across third party libraries. |
||||
|
- Remove one package from dependency due to having been pulled from NPM. |
||||
|
|
||||
|
0.4.22 2016-03-04 |
||||
|
----------------- |
||||
|
- Fix "TypeError: data.copy is not a function" in Electron (Issue #170, https://github.com/kangas). |
||||
|
- Fixed issue with undefined type on deserializing. |
||||
|
|
||||
|
0.4.21 2016-01-12 |
||||
|
----------------- |
||||
|
- Minor optimizations to avoid non needed object creation. |
||||
|
|
||||
|
0.4.20 2015-10-15 |
||||
|
----------------- |
||||
|
- Added bower file to repository. |
||||
|
- Fixed browser pid sometimes set greater than 0xFFFF on browsers (Issue #155, https://github.com/rahatarmanahmed) |
||||
|
|
||||
|
0.4.19 2015-10-15 |
||||
|
----------------- |
||||
|
- Remove all support for bson-ext. |
||||
|
|
||||
|
0.4.18 2015-10-15 |
||||
|
----------------- |
||||
|
- ObjectID equality check should return boolean instead of throwing exception for invalid oid string #139 |
||||
|
- add option for deserializing binary into Buffer object #116 |
||||
|
|
||||
|
0.4.17 2015-10-15 |
||||
|
----------------- |
||||
|
- Validate regexp string for null bytes and throw if there is one. |
||||
|
|
||||
|
0.4.16 2015-10-07 |
||||
|
----------------- |
||||
|
- Fixed issue with return statement in Map.js. |
||||
|
|
||||
|
0.4.15 2015-10-06 |
||||
|
----------------- |
||||
|
- Exposed Map correctly via index.js file. |
||||
|
|
||||
|
0.4.14 2015-10-06 |
||||
|
----------------- |
||||
|
- Exposed Map correctly via bson.js file. |
||||
|
|
||||
|
0.4.13 2015-10-06 |
||||
|
----------------- |
||||
|
- Added ES6 Map type serialization as well as a polyfill for ES5. |
||||
|
|
||||
|
0.4.12 2015-09-18 |
||||
|
----------------- |
||||
|
- Made ignore undefined an optional parameter. |
||||
|
|
||||
|
0.4.11 2015-08-06 |
||||
|
----------------- |
||||
|
- Minor fix for invalid key checking. |
||||
|
|
||||
|
0.4.10 2015-08-06 |
||||
|
----------------- |
||||
|
- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. |
||||
|
- Some performance improvements by in lining code. |
||||
|
|
||||
|
0.4.9 2015-08-06 |
||||
|
---------------- |
||||
|
- Undefined fields are omitted from serialization in objects. |
||||
|
|
||||
|
0.4.8 2015-07-14 |
||||
|
---------------- |
||||
|
- Fixed size validation to ensure we can deserialize from dumped files. |
||||
|
|
||||
|
0.4.7 2015-06-26 |
||||
|
---------------- |
||||
|
- Added ability to instruct deserializer to return raw BSON buffers for named array fields. |
||||
|
- Minor deserialization optimization by moving inlined function out. |
||||
|
|
||||
|
0.4.6 2015-06-17 |
||||
|
---------------- |
||||
|
- Fixed serializeWithBufferAndIndex bug. |
||||
|
|
||||
|
0.4.5 2015-06-17 |
||||
|
---------------- |
||||
|
- Removed any references to the shared buffer to avoid non GC collectible bson instances. |
||||
|
|
||||
|
0.4.4 2015-06-17 |
||||
|
---------------- |
||||
|
- Fixed rethrowing of error when not RangeError. |
||||
|
|
||||
|
0.4.3 2015-06-17 |
||||
|
---------------- |
||||
|
- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. |
||||
|
|
||||
|
0.4.2 2015-06-16 |
||||
|
---------------- |
||||
|
- More fixes for corrupt Bson |
||||
|
|
||||
|
0.4.1 2015-06-16 |
||||
|
---------------- |
||||
|
- More fixes for corrupt Bson |
||||
|
|
||||
|
0.4.0 2015-06-16 |
||||
|
---------------- |
||||
|
- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. |
||||
|
- Removed bson-ext extension dependency for now. |
||||
|
|
||||
|
0.3.2 2015-03-27 |
||||
|
---------------- |
||||
|
- Removed node-gyp from install script in package.json. |
||||
|
|
||||
|
0.3.1 2015-03-27 |
||||
|
---------------- |
||||
|
- Return pure js version on native() call if failed to initialize. |
||||
|
|
||||
|
0.3.0 2015-03-26 |
||||
|
---------------- |
||||
|
- Pulled out all C++ code into bson-ext and made it an optional dependency. |
||||
|
|
||||
|
0.2.21 2015-03-21 |
||||
|
----------------- |
||||
|
- Updated Nan to 1.7.0 to support io.js and node 0.12.0 |
||||
|
|
||||
|
0.2.19 2015-02-16 |
||||
|
----------------- |
||||
|
- Updated Nan to 1.6.2 to support io.js and node 0.12.0 |
||||
|
|
||||
|
0.2.18 2015-01-20 |
||||
|
----------------- |
||||
|
- Updated Nan to 1.5.1 to support io.js |
||||
|
|
||||
|
0.2.16 2014-12-17 |
||||
|
----------------- |
||||
|
- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's |
||||
|
|
||||
|
0.2.12 2014-08-24 |
||||
|
----------------- |
||||
|
- Fixes for fortify review of c++ extension |
||||
|
- toBSON correctly allows returns of non objects |
||||
|
|
||||
|
0.2.3 2013-10-01 |
||||
|
---------------- |
||||
|
- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) |
||||
|
- Fixed issue where corrupt CString's could cause endless loop |
||||
|
- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) |
||||
|
|
||||
|
0.1.4 2012-09-25 |
||||
|
---------------- |
||||
|
- Added precompiled c++ native extensions for win32 ia32 and x64 |
@ -0,0 +1,201 @@ |
|||||
|
Apache License |
||||
|
Version 2.0, January 2004 |
||||
|
http://www.apache.org/licenses/ |
||||
|
|
||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION |
||||
|
|
||||
|
1. Definitions. |
||||
|
|
||||
|
"License" shall mean the terms and conditions for use, reproduction, |
||||
|
and distribution as defined by Sections 1 through 9 of this document. |
||||
|
|
||||
|
"Licensor" shall mean the copyright owner or entity authorized by |
||||
|
the copyright owner that is granting the License. |
||||
|
|
||||
|
"Legal Entity" shall mean the union of the acting entity and all |
||||
|
other entities that control, are controlled by, or are under common |
||||
|
control with that entity. For the purposes of this definition, |
||||
|
"control" means (i) the power, direct or indirect, to cause the |
||||
|
direction or management of such entity, whether by contract or |
||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the |
||||
|
outstanding shares, or (iii) beneficial ownership of such entity. |
||||
|
|
||||
|
"You" (or "Your") shall mean an individual or Legal Entity |
||||
|
exercising permissions granted by this License. |
||||
|
|
||||
|
"Source" form shall mean the preferred form for making modifications, |
||||
|
including but not limited to software source code, documentation |
||||
|
source, and configuration files. |
||||
|
|
||||
|
"Object" form shall mean any form resulting from mechanical |
||||
|
transformation or translation of a Source form, including but |
||||
|
not limited to compiled object code, generated documentation, |
||||
|
and conversions to other media types. |
||||
|
|
||||
|
"Work" shall mean the work of authorship, whether in Source or |
||||
|
Object form, made available under the License, as indicated by a |
||||
|
copyright notice that is included in or attached to the work |
||||
|
(an example is provided in the Appendix below). |
||||
|
|
||||
|
"Derivative Works" shall mean any work, whether in Source or Object |
||||
|
form, that is based on (or derived from) the Work and for which the |
||||
|
editorial revisions, annotations, elaborations, or other modifications |
||||
|
represent, as a whole, an original work of authorship. For the purposes |
||||
|
of this License, Derivative Works shall not include works that remain |
||||
|
separable from, or merely link (or bind by name) to the interfaces of, |
||||
|
the Work and Derivative Works thereof. |
||||
|
|
||||
|
"Contribution" shall mean any work of authorship, including |
||||
|
the original version of the Work and any modifications or additions |
||||
|
to that Work or Derivative Works thereof, that is intentionally |
||||
|
submitted to Licensor for inclusion in the Work by the copyright owner |
||||
|
or by an individual or Legal Entity authorized to submit on behalf of |
||||
|
the copyright owner. For the purposes of this definition, "submitted" |
||||
|
means any form of electronic, verbal, or written communication sent |
||||
|
to the Licensor or its representatives, including but not limited to |
||||
|
communication on electronic mailing lists, source code control systems, |
||||
|
and issue tracking systems that are managed by, or on behalf of, the |
||||
|
Licensor for the purpose of discussing and improving the Work, but |
||||
|
excluding communication that is conspicuously marked or otherwise |
||||
|
designated in writing by the copyright owner as "Not a Contribution." |
||||
|
|
||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity |
||||
|
on behalf of whom a Contribution has been received by Licensor and |
||||
|
subsequently incorporated within the Work. |
||||
|
|
||||
|
2. Grant of Copyright License. Subject to the terms and conditions of |
||||
|
this License, each Contributor hereby grants to You a perpetual, |
||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
|
copyright license to reproduce, prepare Derivative Works of, |
||||
|
publicly display, publicly perform, sublicense, and distribute the |
||||
|
Work and such Derivative Works in Source or Object form. |
||||
|
|
||||
|
3. Grant of Patent License. Subject to the terms and conditions of |
||||
|
this License, each Contributor hereby grants to You a perpetual, |
||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable |
||||
|
(except as stated in this section) patent license to make, have made, |
||||
|
use, offer to sell, sell, import, and otherwise transfer the Work, |
||||
|
where such license applies only to those patent claims licensable |
||||
|
by such Contributor that are necessarily infringed by their |
||||
|
Contribution(s) alone or by combination of their Contribution(s) |
||||
|
with the Work to which such Contribution(s) was submitted. If You |
||||
|
institute patent litigation against any entity (including a |
||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work |
||||
|
or a Contribution incorporated within the Work constitutes direct |
||||
|
or contributory patent infringement, then any patent licenses |
||||
|
granted to You under this License for that Work shall terminate |
||||
|
as of the date such litigation is filed. |
||||
|
|
||||
|
4. Redistribution. You may reproduce and distribute copies of the |
||||
|
Work or Derivative Works thereof in any medium, with or without |
||||
|
modifications, and in Source or Object form, provided that You |
||||
|
meet the following conditions: |
||||
|
|
||||
|
(a) You must give any other recipients of the Work or |
||||
|
Derivative Works a copy of this License; and |
||||
|
|
||||
|
(b) You must cause any modified files to carry prominent notices |
||||
|
stating that You changed the files; and |
||||
|
|
||||
|
(c) You must retain, in the Source form of any Derivative Works |
||||
|
that You distribute, all copyright, patent, trademark, and |
||||
|
attribution notices from the Source form of the Work, |
||||
|
excluding those notices that do not pertain to any part of |
||||
|
the Derivative Works; and |
||||
|
|
||||
|
(d) If the Work includes a "NOTICE" text file as part of its |
||||
|
distribution, then any Derivative Works that You distribute must |
||||
|
include a readable copy of the attribution notices contained |
||||
|
within such NOTICE file, excluding those notices that do not |
||||
|
pertain to any part of the Derivative Works, in at least one |
||||
|
of the following places: within a NOTICE text file distributed |
||||
|
as part of the Derivative Works; within the Source form or |
||||
|
documentation, if provided along with the Derivative Works; or, |
||||
|
within a display generated by the Derivative Works, if and |
||||
|
wherever such third-party notices normally appear. The contents |
||||
|
of the NOTICE file are for informational purposes only and |
||||
|
do not modify the License. You may add Your own attribution |
||||
|
notices within Derivative Works that You distribute, alongside |
||||
|
or as an addendum to the NOTICE text from the Work, provided |
||||
|
that such additional attribution notices cannot be construed |
||||
|
as modifying the License. |
||||
|
|
||||
|
You may add Your own copyright statement to Your modifications and |
||||
|
may provide additional or different license terms and conditions |
||||
|
for use, reproduction, or distribution of Your modifications, or |
||||
|
for any such Derivative Works as a whole, provided Your use, |
||||
|
reproduction, and distribution of the Work otherwise complies with |
||||
|
the conditions stated in this License. |
||||
|
|
||||
|
5. Submission of Contributions. Unless You explicitly state otherwise, |
||||
|
any Contribution intentionally submitted for inclusion in the Work |
||||
|
by You to the Licensor shall be under the terms and conditions of |
||||
|
this License, without any additional terms or conditions. |
||||
|
Notwithstanding the above, nothing herein shall supersede or modify |
||||
|
the terms of any separate license agreement you may have executed |
||||
|
with Licensor regarding such Contributions. |
||||
|
|
||||
|
6. Trademarks. This License does not grant permission to use the trade |
||||
|
names, trademarks, service marks, or product names of the Licensor, |
||||
|
except as required for reasonable and customary use in describing the |
||||
|
origin of the Work and reproducing the content of the NOTICE file. |
||||
|
|
||||
|
7. Disclaimer of Warranty. Unless required by applicable law or |
||||
|
agreed to in writing, Licensor provides the Work (and each |
||||
|
Contributor provides its Contributions) on an "AS IS" BASIS, |
||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
||||
|
implied, including, without limitation, any warranties or conditions |
||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A |
||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the |
||||
|
appropriateness of using or redistributing the Work and assume any |
||||
|
risks associated with Your exercise of permissions under this License. |
||||
|
|
||||
|
8. Limitation of Liability. In no event and under no legal theory, |
||||
|
whether in tort (including negligence), contract, or otherwise, |
||||
|
unless required by applicable law (such as deliberate and grossly |
||||
|
negligent acts) or agreed to in writing, shall any Contributor be |
||||
|
liable to You for damages, including any direct, indirect, special, |
||||
|
incidental, or consequential damages of any character arising as a |
||||
|
result of this License or out of the use or inability to use the |
||||
|
Work (including but not limited to damages for loss of goodwill, |
||||
|
work stoppage, computer failure or malfunction, or any and all |
||||
|
other commercial damages or losses), even if such Contributor |
||||
|
has been advised of the possibility of such damages. |
||||
|
|
||||
|
9. Accepting Warranty or Additional Liability. While redistributing |
||||
|
the Work or Derivative Works thereof, You may choose to offer, |
||||
|
and charge a fee for, acceptance of support, warranty, indemnity, |
||||
|
or other liability obligations and/or rights consistent with this |
||||
|
License. However, in accepting such obligations, You may act only |
||||
|
on Your own behalf and on Your sole responsibility, not on behalf |
||||
|
of any other Contributor, and only if You agree to indemnify, |
||||
|
defend, and hold each Contributor harmless for any liability |
||||
|
incurred by, or claims asserted against, such Contributor by reason |
||||
|
of your accepting any such warranty or additional liability. |
||||
|
|
||||
|
END OF TERMS AND CONDITIONS |
||||
|
|
||||
|
APPENDIX: How to apply the Apache License to your work. |
||||
|
|
||||
|
To apply the Apache License to your work, attach the following |
||||
|
boilerplate notice, with the fields enclosed by brackets "[]" |
||||
|
replaced with your own identifying information. (Don't include |
||||
|
the brackets!) The text should be enclosed in the appropriate |
||||
|
comment syntax for the file format. We also recommend that a |
||||
|
file or class name and description of purpose be included on the |
||||
|
same "printed page" as the copyright notice for easier |
||||
|
identification within third-party archives. |
||||
|
|
||||
|
Copyright [yyyy] [name of copyright owner] |
||||
|
|
||||
|
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. |
@ -0,0 +1,170 @@ |
|||||
|
# BSON parser |
||||
|
|
||||
|
BSON is short for Binary JSON and is the binary-encoded serialization of JSON-like documents. You can learn more about it in [the specification](http://bsonspec.org). |
||||
|
|
||||
|
This browser version of the BSON parser is compiled using [webpack](https://webpack.js.org/) and the current version is pre-compiled in the `browser_build` directory. |
||||
|
|
||||
|
This is the default BSON parser, however, there is a C++ Node.js addon version as well that does not support the browser. It can be found at [mongod-js/bson-ext](https://github.com/mongodb-js/bson-ext). |
||||
|
|
||||
|
## Usage |
||||
|
|
||||
|
To build a new version perform the following operations: |
||||
|
|
||||
|
``` |
||||
|
npm install |
||||
|
npm run build |
||||
|
``` |
||||
|
|
||||
|
A simple example of how to use BSON in the browser: |
||||
|
|
||||
|
```html |
||||
|
<script src="./browser_build/bson.js"></script> |
||||
|
|
||||
|
<script> |
||||
|
function start() { |
||||
|
// Get the Long type |
||||
|
var Long = BSON.Long; |
||||
|
// Create a bson parser instance |
||||
|
var bson = new BSON(); |
||||
|
|
||||
|
// Serialize document |
||||
|
var doc = { long: Long.fromNumber(100) } |
||||
|
|
||||
|
// Serialize a document |
||||
|
var data = bson.serialize(doc) |
||||
|
// De serialize it again |
||||
|
var doc_2 = bson.deserialize(data) |
||||
|
} |
||||
|
</script> |
||||
|
``` |
||||
|
|
||||
|
A simple example of how to use BSON in `Node.js`: |
||||
|
|
||||
|
```js |
||||
|
// Get BSON parser class |
||||
|
var BSON = require('bson') |
||||
|
// Get the Long type |
||||
|
var Long = BSON.Long; |
||||
|
// Create a bson parser instance |
||||
|
var bson = new BSON(); |
||||
|
|
||||
|
// Serialize document |
||||
|
var doc = { long: Long.fromNumber(100) } |
||||
|
|
||||
|
// Serialize a document |
||||
|
var data = bson.serialize(doc) |
||||
|
console.log('data:', data) |
||||
|
|
||||
|
// Deserialize the resulting Buffer |
||||
|
var doc_2 = bson.deserialize(data) |
||||
|
console.log('doc_2:', doc_2) |
||||
|
``` |
||||
|
|
||||
|
## Installation |
||||
|
|
||||
|
`npm install bson` |
||||
|
|
||||
|
## API |
||||
|
|
||||
|
### BSON types |
||||
|
|
||||
|
For all BSON types documentation, please refer to the following sources: |
||||
|
* [MongoDB BSON Type Reference](https://docs.mongodb.com/manual/reference/bson-types/) |
||||
|
* [BSON Spec](https://bsonspec.org/) |
||||
|
|
||||
|
### BSON serialization and deserialiation |
||||
|
|
||||
|
**`new BSON()`** - Creates a new BSON serializer/deserializer you can use to serialize and deserialize BSON. |
||||
|
|
||||
|
#### BSON.serialize |
||||
|
|
||||
|
The BSON `serialize` method takes a JavaScript object and an optional options object and returns a Node.js Buffer. |
||||
|
|
||||
|
* `BSON.serialize(object, options)` |
||||
|
* @param {Object} object the JavaScript object to serialize. |
||||
|
* @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] |
||||
|
* @return {Buffer} returns a Buffer instance. |
||||
|
|
||||
|
#### BSON.serializeWithBufferAndIndex |
||||
|
|
||||
|
The BSON `serializeWithBufferAndIndex` method takes an object, a target buffer instance and an optional options object and returns the end serialization index in the final buffer. |
||||
|
|
||||
|
* `BSON.serializeWithBufferAndIndex(object, buffer, options)` |
||||
|
* @param {Object} object the JavaScript object to serialize. |
||||
|
* @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. |
||||
|
* @param {Boolean} [options.checkKeys=false] the serializer will check if keys are valid. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields. |
||||
|
* @param {Number} [options.index=0] the index in the buffer where we wish to start serializing into. |
||||
|
* @return {Number} returns the index pointing to the last written byte in the buffer. |
||||
|
|
||||
|
#### BSON.calculateObjectSize |
||||
|
|
||||
|
The BSON `calculateObjectSize` method takes a JavaScript object and an optional options object and returns the size of the BSON object. |
||||
|
|
||||
|
* `BSON.calculateObjectSize(object, options)` |
||||
|
* @param {Object} object the JavaScript object to serialize. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the JavaScript functions. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] |
||||
|
* @return {Buffer} returns a Buffer instance. |
||||
|
|
||||
|
#### BSON.deserialize |
||||
|
|
||||
|
The BSON `deserialize` method takes a Node.js Buffer and an optional options object and returns a deserialized JavaScript object. |
||||
|
|
||||
|
* `BSON.deserialize(buffer, options)` |
||||
|
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. |
||||
|
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. |
||||
|
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. |
||||
|
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
||||
|
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. |
||||
|
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. |
||||
|
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. |
||||
|
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. |
||||
|
* @return {Object} returns the deserialized Javascript Object. |
||||
|
|
||||
|
#### BSON.deserializeStream |
||||
|
|
||||
|
The BSON `deserializeStream` method takes a Node.js Buffer, `startIndex` and allow more control over deserialization of a Buffer containing concatenated BSON documents. |
||||
|
|
||||
|
* `BSON.deserializeStream(buffer, startIndex, numberOfDocuments, documents, docStartIndex, options)` |
||||
|
* @param {Buffer} buffer the buffer containing the serialized set of BSON documents. |
||||
|
* @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. |
||||
|
* @param {Number} numberOfDocuments number of documents to deserialize. |
||||
|
* @param {Array} documents an array where to store the deserialized documents. |
||||
|
* @param {Number} docStartIndex the index in the documents array from where to start inserting documents. |
||||
|
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. |
||||
|
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. |
||||
|
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. |
||||
|
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
||||
|
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a Node.js Buffer instance. |
||||
|
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. |
||||
|
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. |
||||
|
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. |
||||
|
* @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. |
||||
|
|
||||
|
## FAQ |
||||
|
|
||||
|
#### Why does `undefined` get converted to `null`? |
||||
|
|
||||
|
The `undefined` BSON type has been [deprecated for many years](http://bsonspec.org/spec.html), so this library has dropped support for it. Use the `ignoreUndefined` option (for example, from the [driver](http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect) ) to instead remove `undefined` keys. |
||||
|
|
||||
|
#### How do I add custom serialization logic? |
||||
|
|
||||
|
This library looks for `toBSON()` functions on every path, and calls the `toBSON()` function to get the value to serialize. |
||||
|
|
||||
|
```javascript |
||||
|
var bson = new BSON(); |
||||
|
|
||||
|
class CustomSerialize { |
||||
|
toBSON() { |
||||
|
return 42; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
const obj = { answer: new CustomSerialize() }; |
||||
|
// "{ answer: 42 }" |
||||
|
console.log(bson.deserialize(bson.serialize(obj))); |
||||
|
``` |
@ -0,0 +1,25 @@ |
|||||
|
{ |
||||
|
"name": "bson", |
||||
|
"description": "A bson parser for node.js and the browser", |
||||
|
"keywords": [ |
||||
|
"mongodb", |
||||
|
"bson", |
||||
|
"parser" |
||||
|
], |
||||
|
"author": "Christian Amor Kvalheim <christkv@gmail.com>", |
||||
|
"main": "./browser_build/bson.js", |
||||
|
"license": "Apache-2.0", |
||||
|
"moduleType": [ |
||||
|
"globals", |
||||
|
"node" |
||||
|
], |
||||
|
"ignore": [ |
||||
|
"**/.*", |
||||
|
"alternate_parsers", |
||||
|
"benchmarks", |
||||
|
"bower_components", |
||||
|
"node_modules", |
||||
|
"test", |
||||
|
"tools" |
||||
|
] |
||||
|
} |
File diff suppressed because it is too large
@ -0,0 +1,8 @@ |
|||||
|
{ "name" : "bson" |
||||
|
, "description" : "A bson parser for node.js and the browser" |
||||
|
, "main": "../" |
||||
|
, "directories" : { "lib" : "../lib/bson" } |
||||
|
, "engines" : { "node" : ">=0.6.0" } |
||||
|
, "licenses" : [ { "type" : "Apache License, Version 2.0" |
||||
|
, "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] |
||||
|
} |
@ -0,0 +1,46 @@ |
|||||
|
var BSON = require('./lib/bson/bson'), |
||||
|
Binary = require('./lib/bson/binary'), |
||||
|
Code = require('./lib/bson/code'), |
||||
|
DBRef = require('./lib/bson/db_ref'), |
||||
|
Decimal128 = require('./lib/bson/decimal128'), |
||||
|
Double = require('./lib/bson/double'), |
||||
|
Int32 = require('./lib/bson/int_32'), |
||||
|
Long = require('./lib/bson/long'), |
||||
|
Map = require('./lib/bson/map'), |
||||
|
MaxKey = require('./lib/bson/max_key'), |
||||
|
MinKey = require('./lib/bson/min_key'), |
||||
|
ObjectId = require('./lib/bson/objectid'), |
||||
|
BSONRegExp = require('./lib/bson/regexp'), |
||||
|
Symbol = require('./lib/bson/symbol'), |
||||
|
Timestamp = require('./lib/bson/timestamp'); |
||||
|
|
||||
|
// BSON MAX VALUES
|
||||
|
BSON.BSON_INT32_MAX = 0x7fffffff; |
||||
|
BSON.BSON_INT32_MIN = -0x80000000; |
||||
|
|
||||
|
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; |
||||
|
BSON.BSON_INT64_MIN = -Math.pow(2, 63); |
||||
|
|
||||
|
// JS MAX PRECISE VALUES
|
||||
|
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
// Add BSON types to function creation
|
||||
|
BSON.Binary = Binary; |
||||
|
BSON.Code = Code; |
||||
|
BSON.DBRef = DBRef; |
||||
|
BSON.Decimal128 = Decimal128; |
||||
|
BSON.Double = Double; |
||||
|
BSON.Int32 = Int32; |
||||
|
BSON.Long = Long; |
||||
|
BSON.Map = Map; |
||||
|
BSON.MaxKey = MaxKey; |
||||
|
BSON.MinKey = MinKey; |
||||
|
BSON.ObjectId = ObjectId; |
||||
|
BSON.ObjectID = ObjectId; |
||||
|
BSON.BSONRegExp = BSONRegExp; |
||||
|
BSON.Symbol = Symbol; |
||||
|
BSON.Timestamp = Timestamp; |
||||
|
|
||||
|
// Return the BSON
|
||||
|
module.exports = BSON; |
@ -0,0 +1,384 @@ |
|||||
|
/** |
||||
|
* Module dependencies. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
|
||||
|
// Test if we're in Node via presence of "global" not absence of "window"
|
||||
|
// to support hybrid environments like Electron
|
||||
|
if (typeof global !== 'undefined') { |
||||
|
var Buffer = require('buffer').Buffer; // TODO just use global Buffer
|
||||
|
} |
||||
|
|
||||
|
var utils = require('./parser/utils'); |
||||
|
|
||||
|
/** |
||||
|
* A class representation of the BSON Binary type. |
||||
|
* |
||||
|
* Sub types |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. |
||||
|
* - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {Buffer} buffer a buffer object containing the binary data. |
||||
|
* @param {Number} [subType] the option binary type. |
||||
|
* @return {Binary} |
||||
|
*/ |
||||
|
function Binary(buffer, subType) { |
||||
|
if (!(this instanceof Binary)) return new Binary(buffer, subType); |
||||
|
|
||||
|
if ( |
||||
|
buffer != null && |
||||
|
!(typeof buffer === 'string') && |
||||
|
!Buffer.isBuffer(buffer) && |
||||
|
!(buffer instanceof Uint8Array) && |
||||
|
!Array.isArray(buffer) |
||||
|
) { |
||||
|
throw new Error('only String, Buffer, Uint8Array or Array accepted'); |
||||
|
} |
||||
|
|
||||
|
this._bsontype = 'Binary'; |
||||
|
|
||||
|
if (buffer instanceof Number) { |
||||
|
this.sub_type = buffer; |
||||
|
this.position = 0; |
||||
|
} else { |
||||
|
this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; |
||||
|
this.position = 0; |
||||
|
} |
||||
|
|
||||
|
if (buffer != null && !(buffer instanceof Number)) { |
||||
|
// Only accept Buffer, Uint8Array or Arrays
|
||||
|
if (typeof buffer === 'string') { |
||||
|
// Different ways of writing the length of the string for the different types
|
||||
|
if (typeof Buffer !== 'undefined') { |
||||
|
this.buffer = utils.toBuffer(buffer); |
||||
|
} else if ( |
||||
|
typeof Uint8Array !== 'undefined' || |
||||
|
Object.prototype.toString.call(buffer) === '[object Array]' |
||||
|
) { |
||||
|
this.buffer = writeStringToArray(buffer); |
||||
|
} else { |
||||
|
throw new Error('only String, Buffer, Uint8Array or Array accepted'); |
||||
|
} |
||||
|
} else { |
||||
|
this.buffer = buffer; |
||||
|
} |
||||
|
this.position = buffer.length; |
||||
|
} else { |
||||
|
if (typeof Buffer !== 'undefined') { |
||||
|
this.buffer = utils.allocBuffer(Binary.BUFFER_SIZE); |
||||
|
} else if (typeof Uint8Array !== 'undefined') { |
||||
|
this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); |
||||
|
} else { |
||||
|
this.buffer = new Array(Binary.BUFFER_SIZE); |
||||
|
} |
||||
|
// Set position to start of buffer
|
||||
|
this.position = 0; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Updates this binary with byte_value. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {string} byte_value a single byte we wish to write. |
||||
|
*/ |
||||
|
Binary.prototype.put = function put(byte_value) { |
||||
|
// If it's a string and a has more than one character throw an error
|
||||
|
if (byte_value['length'] != null && typeof byte_value !== 'number' && byte_value.length !== 1) |
||||
|
throw new Error('only accepts single character String, Uint8Array or Array'); |
||||
|
if ((typeof byte_value !== 'number' && byte_value < 0) || byte_value > 255) |
||||
|
throw new Error('only accepts number in a valid unsigned byte range 0-255'); |
||||
|
|
||||
|
// Decode the byte value once
|
||||
|
var decoded_byte = null; |
||||
|
if (typeof byte_value === 'string') { |
||||
|
decoded_byte = byte_value.charCodeAt(0); |
||||
|
} else if (byte_value['length'] != null) { |
||||
|
decoded_byte = byte_value[0]; |
||||
|
} else { |
||||
|
decoded_byte = byte_value; |
||||
|
} |
||||
|
|
||||
|
if (this.buffer.length > this.position) { |
||||
|
this.buffer[this.position++] = decoded_byte; |
||||
|
} else { |
||||
|
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { |
||||
|
// Create additional overflow buffer
|
||||
|
var buffer = utils.allocBuffer(Binary.BUFFER_SIZE + this.buffer.length); |
||||
|
// Combine the two buffers together
|
||||
|
this.buffer.copy(buffer, 0, 0, this.buffer.length); |
||||
|
this.buffer = buffer; |
||||
|
this.buffer[this.position++] = decoded_byte; |
||||
|
} else { |
||||
|
buffer = null; |
||||
|
// Create a new buffer (typed or normal array)
|
||||
|
if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { |
||||
|
buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); |
||||
|
} else { |
||||
|
buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); |
||||
|
} |
||||
|
|
||||
|
// We need to copy all the content to the new array
|
||||
|
for (var i = 0; i < this.buffer.length; i++) { |
||||
|
buffer[i] = this.buffer[i]; |
||||
|
} |
||||
|
|
||||
|
// Reassign the buffer
|
||||
|
this.buffer = buffer; |
||||
|
// Write the byte
|
||||
|
this.buffer[this.position++] = decoded_byte; |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Writes a buffer or string to the binary. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. |
||||
|
* @param {number} offset specify the binary of where to write the content. |
||||
|
* @return {null} |
||||
|
*/ |
||||
|
Binary.prototype.write = function write(string, offset) { |
||||
|
offset = typeof offset === 'number' ? offset : this.position; |
||||
|
|
||||
|
// If the buffer is to small let's extend the buffer
|
||||
|
if (this.buffer.length < offset + string.length) { |
||||
|
var buffer = null; |
||||
|
// If we are in node.js
|
||||
|
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { |
||||
|
buffer = utils.allocBuffer(this.buffer.length + string.length); |
||||
|
this.buffer.copy(buffer, 0, 0, this.buffer.length); |
||||
|
} else if (Object.prototype.toString.call(this.buffer) === '[object Uint8Array]') { |
||||
|
// Create a new buffer
|
||||
|
buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)); |
||||
|
// Copy the content
|
||||
|
for (var i = 0; i < this.position; i++) { |
||||
|
buffer[i] = this.buffer[i]; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Assign the new buffer
|
||||
|
this.buffer = buffer; |
||||
|
} |
||||
|
|
||||
|
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { |
||||
|
string.copy(this.buffer, offset, 0, string.length); |
||||
|
this.position = offset + string.length > this.position ? offset + string.length : this.position; |
||||
|
// offset = string.length
|
||||
|
} else if ( |
||||
|
typeof Buffer !== 'undefined' && |
||||
|
typeof string === 'string' && |
||||
|
Buffer.isBuffer(this.buffer) |
||||
|
) { |
||||
|
this.buffer.write(string, offset, 'binary'); |
||||
|
this.position = offset + string.length > this.position ? offset + string.length : this.position; |
||||
|
// offset = string.length;
|
||||
|
} else if ( |
||||
|
Object.prototype.toString.call(string) === '[object Uint8Array]' || |
||||
|
(Object.prototype.toString.call(string) === '[object Array]' && typeof string !== 'string') |
||||
|
) { |
||||
|
for (i = 0; i < string.length; i++) { |
||||
|
this.buffer[offset++] = string[i]; |
||||
|
} |
||||
|
|
||||
|
this.position = offset > this.position ? offset : this.position; |
||||
|
} else if (typeof string === 'string') { |
||||
|
for (i = 0; i < string.length; i++) { |
||||
|
this.buffer[offset++] = string.charCodeAt(i); |
||||
|
} |
||||
|
|
||||
|
this.position = offset > this.position ? offset : this.position; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Reads **length** bytes starting at **position**. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} position read from the given position in the Binary. |
||||
|
* @param {number} length the number of bytes to read. |
||||
|
* @return {Buffer} |
||||
|
*/ |
||||
|
Binary.prototype.read = function read(position, length) { |
||||
|
length = length && length > 0 ? length : this.position; |
||||
|
|
||||
|
// Let's return the data based on the type we have
|
||||
|
if (this.buffer['slice']) { |
||||
|
return this.buffer.slice(position, position + length); |
||||
|
} else { |
||||
|
// Create a buffer to keep the result
|
||||
|
var buffer = |
||||
|
typeof Uint8Array !== 'undefined' |
||||
|
? new Uint8Array(new ArrayBuffer(length)) |
||||
|
: new Array(length); |
||||
|
for (var i = 0; i < length; i++) { |
||||
|
buffer[i] = this.buffer[position++]; |
||||
|
} |
||||
|
} |
||||
|
// Return the buffer
|
||||
|
return buffer; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the value of this binary as a string. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {string} |
||||
|
*/ |
||||
|
Binary.prototype.value = function value(asRaw) { |
||||
|
asRaw = asRaw == null ? false : asRaw; |
||||
|
|
||||
|
// Optimize to serialize for the situation where the data == size of buffer
|
||||
|
if ( |
||||
|
asRaw && |
||||
|
typeof Buffer !== 'undefined' && |
||||
|
Buffer.isBuffer(this.buffer) && |
||||
|
this.buffer.length === this.position |
||||
|
) |
||||
|
return this.buffer; |
||||
|
|
||||
|
// If it's a node.js buffer object
|
||||
|
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(this.buffer)) { |
||||
|
return asRaw |
||||
|
? this.buffer.slice(0, this.position) |
||||
|
: this.buffer.toString('binary', 0, this.position); |
||||
|
} else { |
||||
|
if (asRaw) { |
||||
|
// we support the slice command use it
|
||||
|
if (this.buffer['slice'] != null) { |
||||
|
return this.buffer.slice(0, this.position); |
||||
|
} else { |
||||
|
// Create a new buffer to copy content to
|
||||
|
var newBuffer = |
||||
|
Object.prototype.toString.call(this.buffer) === '[object Uint8Array]' |
||||
|
? new Uint8Array(new ArrayBuffer(this.position)) |
||||
|
: new Array(this.position); |
||||
|
// Copy content
|
||||
|
for (var i = 0; i < this.position; i++) { |
||||
|
newBuffer[i] = this.buffer[i]; |
||||
|
} |
||||
|
// Return the buffer
|
||||
|
return newBuffer; |
||||
|
} |
||||
|
} else { |
||||
|
return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Length. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the length of the binary. |
||||
|
*/ |
||||
|
Binary.prototype.length = function length() { |
||||
|
return this.position; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Binary.prototype.toJSON = function() { |
||||
|
return this.buffer != null ? this.buffer.toString('base64') : ''; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Binary.prototype.toString = function(format) { |
||||
|
return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Binary default subtype |
||||
|
* @ignore |
||||
|
*/ |
||||
|
var BSON_BINARY_SUBTYPE_DEFAULT = 0; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
var writeStringToArray = function(data) { |
||||
|
// Create a buffer
|
||||
|
var buffer = |
||||
|
typeof Uint8Array !== 'undefined' |
||||
|
? new Uint8Array(new ArrayBuffer(data.length)) |
||||
|
: new Array(data.length); |
||||
|
// Write the content to the buffer
|
||||
|
for (var i = 0; i < data.length; i++) { |
||||
|
buffer[i] = data.charCodeAt(i); |
||||
|
} |
||||
|
// Write the string to the buffer
|
||||
|
return buffer; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Convert Array ot Uint8Array to Binary String |
||||
|
* |
||||
|
* @ignore |
||||
|
*/ |
||||
|
var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { |
||||
|
var result = ''; |
||||
|
for (var i = startIndex; i < endIndex; i++) { |
||||
|
result = result + String.fromCharCode(byteArray[i]); |
||||
|
} |
||||
|
return result; |
||||
|
}; |
||||
|
|
||||
|
Binary.BUFFER_SIZE = 256; |
||||
|
|
||||
|
/** |
||||
|
* Default BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_DEFAULT = 0; |
||||
|
/** |
||||
|
* Function BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_FUNCTION = 1; |
||||
|
/** |
||||
|
* Byte Array BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_BYTE_ARRAY = 2; |
||||
|
/** |
||||
|
* OLD UUID BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_UUID_OLD = 3; |
||||
|
/** |
||||
|
* UUID BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_UUID = 4; |
||||
|
/** |
||||
|
* MD5 BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_MD5 = 5; |
||||
|
/** |
||||
|
* User BSON type |
||||
|
* |
||||
|
* @classconstant SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
Binary.SUBTYPE_USER_DEFINED = 128; |
||||
|
|
||||
|
/** |
||||
|
* Expose. |
||||
|
*/ |
||||
|
module.exports = Binary; |
||||
|
module.exports.Binary = Binary; |
@ -0,0 +1,386 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
var Map = require('./map'), |
||||
|
Long = require('./long'), |
||||
|
Double = require('./double'), |
||||
|
Timestamp = require('./timestamp'), |
||||
|
ObjectID = require('./objectid'), |
||||
|
BSONRegExp = require('./regexp'), |
||||
|
Symbol = require('./symbol'), |
||||
|
Int32 = require('./int_32'), |
||||
|
Code = require('./code'), |
||||
|
Decimal128 = require('./decimal128'), |
||||
|
MinKey = require('./min_key'), |
||||
|
MaxKey = require('./max_key'), |
||||
|
DBRef = require('./db_ref'), |
||||
|
Binary = require('./binary'); |
||||
|
|
||||
|
// Parts of the parser
|
||||
|
var deserialize = require('./parser/deserializer'), |
||||
|
serializer = require('./parser/serializer'), |
||||
|
calculateObjectSize = require('./parser/calculate_size'), |
||||
|
utils = require('./parser/utils'); |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
// Default Max Size
|
||||
|
var MAXSIZE = 1024 * 1024 * 17; |
||||
|
|
||||
|
// Current Internal Temporary Serialization Buffer
|
||||
|
var buffer = utils.allocBuffer(MAXSIZE); |
||||
|
|
||||
|
var BSON = function() {}; |
||||
|
|
||||
|
/** |
||||
|
* Serialize a Javascript object. |
||||
|
* |
||||
|
* @param {Object} object the Javascript object to serialize. |
||||
|
* @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. |
||||
|
* @param {Number} [options.minInternalBufferSize=1024*1024*17] minimum size of the internal temporary serialization buffer **(default:1024*1024*17)**. |
||||
|
* @return {Buffer} returns the Buffer object containing the serialized object. |
||||
|
* @api public |
||||
|
*/ |
||||
|
BSON.prototype.serialize = function serialize(object, options) { |
||||
|
options = options || {}; |
||||
|
// Unpack the options
|
||||
|
var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; |
||||
|
var serializeFunctions = |
||||
|
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; |
||||
|
var ignoreUndefined = |
||||
|
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; |
||||
|
var minInternalBufferSize = |
||||
|
typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE; |
||||
|
|
||||
|
// Resize the internal serialization buffer if needed
|
||||
|
if (buffer.length < minInternalBufferSize) { |
||||
|
buffer = utils.allocBuffer(minInternalBufferSize); |
||||
|
} |
||||
|
|
||||
|
// Attempt to serialize
|
||||
|
var serializationIndex = serializer( |
||||
|
buffer, |
||||
|
object, |
||||
|
checkKeys, |
||||
|
0, |
||||
|
0, |
||||
|
serializeFunctions, |
||||
|
ignoreUndefined, |
||||
|
[] |
||||
|
); |
||||
|
// Create the final buffer
|
||||
|
var finishedBuffer = utils.allocBuffer(serializationIndex); |
||||
|
// Copy into the finished buffer
|
||||
|
buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); |
||||
|
// Return the buffer
|
||||
|
return finishedBuffer; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. |
||||
|
* |
||||
|
* @param {Object} object the Javascript object to serialize. |
||||
|
* @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. |
||||
|
* @param {Boolean} [options.checkKeys] the serializer will check if keys are valid. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. |
||||
|
* @param {Number} [options.index] the index in the buffer where we wish to start serializing into. |
||||
|
* @return {Number} returns the index pointing to the last written byte in the buffer. |
||||
|
* @api public |
||||
|
*/ |
||||
|
BSON.prototype.serializeWithBufferAndIndex = function(object, finalBuffer, options) { |
||||
|
options = options || {}; |
||||
|
// Unpack the options
|
||||
|
var checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false; |
||||
|
var serializeFunctions = |
||||
|
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; |
||||
|
var ignoreUndefined = |
||||
|
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; |
||||
|
var startIndex = typeof options.index === 'number' ? options.index : 0; |
||||
|
|
||||
|
// Attempt to serialize
|
||||
|
var serializationIndex = serializer( |
||||
|
finalBuffer, |
||||
|
object, |
||||
|
checkKeys, |
||||
|
startIndex || 0, |
||||
|
0, |
||||
|
serializeFunctions, |
||||
|
ignoreUndefined |
||||
|
); |
||||
|
|
||||
|
// Return the index
|
||||
|
return serializationIndex - 1; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Deserialize data as BSON. |
||||
|
* |
||||
|
* @param {Buffer} buffer the buffer containing the serialized set of BSON documents. |
||||
|
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. |
||||
|
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. |
||||
|
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. |
||||
|
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
||||
|
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. |
||||
|
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. |
||||
|
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. |
||||
|
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. |
||||
|
* @return {Object} returns the deserialized Javascript Object. |
||||
|
* @api public |
||||
|
*/ |
||||
|
BSON.prototype.deserialize = function(buffer, options) { |
||||
|
return deserialize(buffer, options); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Calculate the bson size for a passed in Javascript object. |
||||
|
* |
||||
|
* @param {Object} object the Javascript object to calculate the BSON byte size for. |
||||
|
* @param {Boolean} [options.serializeFunctions=false] serialize the javascript functions **(default:false)**. |
||||
|
* @param {Boolean} [options.ignoreUndefined=true] ignore undefined fields **(default:true)**. |
||||
|
* @return {Number} returns the number of bytes the BSON object will take up. |
||||
|
* @api public |
||||
|
*/ |
||||
|
BSON.prototype.calculateObjectSize = function(object, options) { |
||||
|
options = options || {}; |
||||
|
|
||||
|
var serializeFunctions = |
||||
|
typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false; |
||||
|
var ignoreUndefined = |
||||
|
typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true; |
||||
|
|
||||
|
return calculateObjectSize(object, serializeFunctions, ignoreUndefined); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Deserialize stream data as BSON documents. |
||||
|
* |
||||
|
* @param {Buffer} data the buffer containing the serialized set of BSON documents. |
||||
|
* @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. |
||||
|
* @param {Number} numberOfDocuments number of documents to deserialize. |
||||
|
* @param {Array} documents an array where to store the deserialized documents. |
||||
|
* @param {Number} docStartIndex the index in the documents array from where to start inserting documents. |
||||
|
* @param {Object} [options] additional options used for the deserialization. |
||||
|
* @param {Object} [options.evalFunctions=false] evaluate functions in the BSON document scoped to the object deserialized. |
||||
|
* @param {Object} [options.cacheFunctions=false] cache evaluated functions for reuse. |
||||
|
* @param {Object} [options.cacheFunctionsCrc32=false] use a crc32 code for caching, otherwise use the string of the function. |
||||
|
* @param {Object} [options.promoteLongs=true] when deserializing a Long will fit it into a Number if it's smaller than 53 bits |
||||
|
* @param {Object} [options.promoteBuffers=false] when deserializing a Binary will return it as a node.js Buffer instance. |
||||
|
* @param {Object} [options.promoteValues=false] when deserializing will promote BSON values to their Node.js closest equivalent types. |
||||
|
* @param {Object} [options.fieldsAsRaw=null] allow to specify if there what fields we wish to return as unserialized raw buffer. |
||||
|
* @param {Object} [options.bsonRegExp=false] return BSON regular expressions as BSONRegExp instances. |
||||
|
* @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. |
||||
|
* @api public |
||||
|
*/ |
||||
|
BSON.prototype.deserializeStream = function( |
||||
|
data, |
||||
|
startIndex, |
||||
|
numberOfDocuments, |
||||
|
documents, |
||||
|
docStartIndex, |
||||
|
options |
||||
|
) { |
||||
|
options = options != null ? options : {}; |
||||
|
var index = startIndex; |
||||
|
// Loop over all documents
|
||||
|
for (var i = 0; i < numberOfDocuments; i++) { |
||||
|
// Find size of the document
|
||||
|
var size = |
||||
|
data[index] | (data[index + 1] << 8) | (data[index + 2] << 16) | (data[index + 3] << 24); |
||||
|
// Update options with index
|
||||
|
options['index'] = index; |
||||
|
// Parse the document at this point
|
||||
|
documents[docStartIndex + i] = this.deserialize(data, options); |
||||
|
// Adjust index by the document size
|
||||
|
index = index + size; |
||||
|
} |
||||
|
|
||||
|
// Return object containing end index of parsing and list of documents
|
||||
|
return index; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
// BSON MAX VALUES
|
||||
|
BSON.BSON_INT32_MAX = 0x7fffffff; |
||||
|
BSON.BSON_INT32_MIN = -0x80000000; |
||||
|
|
||||
|
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; |
||||
|
BSON.BSON_INT64_MIN = -Math.pow(2, 63); |
||||
|
|
||||
|
// JS MAX PRECISE VALUES
|
||||
|
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
// Internal long versions
|
||||
|
// var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
// var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
/** |
||||
|
* Number BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_NUMBER |
||||
|
**/ |
||||
|
BSON.BSON_DATA_NUMBER = 1; |
||||
|
/** |
||||
|
* String BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_STRING |
||||
|
**/ |
||||
|
BSON.BSON_DATA_STRING = 2; |
||||
|
/** |
||||
|
* Object BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_OBJECT |
||||
|
**/ |
||||
|
BSON.BSON_DATA_OBJECT = 3; |
||||
|
/** |
||||
|
* Array BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_ARRAY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_ARRAY = 4; |
||||
|
/** |
||||
|
* Binary BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_BINARY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_BINARY = 5; |
||||
|
/** |
||||
|
* ObjectID BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_OID |
||||
|
**/ |
||||
|
BSON.BSON_DATA_OID = 7; |
||||
|
/** |
||||
|
* Boolean BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_BOOLEAN |
||||
|
**/ |
||||
|
BSON.BSON_DATA_BOOLEAN = 8; |
||||
|
/** |
||||
|
* Date BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_DATE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_DATE = 9; |
||||
|
/** |
||||
|
* null BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_NULL |
||||
|
**/ |
||||
|
BSON.BSON_DATA_NULL = 10; |
||||
|
/** |
||||
|
* RegExp BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_REGEXP |
||||
|
**/ |
||||
|
BSON.BSON_DATA_REGEXP = 11; |
||||
|
/** |
||||
|
* Code BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_CODE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_CODE = 13; |
||||
|
/** |
||||
|
* Symbol BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_SYMBOL |
||||
|
**/ |
||||
|
BSON.BSON_DATA_SYMBOL = 14; |
||||
|
/** |
||||
|
* Code with Scope BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_CODE_W_SCOPE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_CODE_W_SCOPE = 15; |
||||
|
/** |
||||
|
* 32 bit Integer BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_INT |
||||
|
**/ |
||||
|
BSON.BSON_DATA_INT = 16; |
||||
|
/** |
||||
|
* Timestamp BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_TIMESTAMP |
||||
|
**/ |
||||
|
BSON.BSON_DATA_TIMESTAMP = 17; |
||||
|
/** |
||||
|
* Long BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_LONG |
||||
|
**/ |
||||
|
BSON.BSON_DATA_LONG = 18; |
||||
|
/** |
||||
|
* MinKey BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_MIN_KEY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_MIN_KEY = 0xff; |
||||
|
/** |
||||
|
* MaxKey BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_MAX_KEY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_MAX_KEY = 0x7f; |
||||
|
|
||||
|
/** |
||||
|
* Binary Default Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; |
||||
|
/** |
||||
|
* Binary Function Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_FUNCTION |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; |
||||
|
/** |
||||
|
* Binary Byte Array Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; |
||||
|
/** |
||||
|
* Binary UUID Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_UUID |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_UUID = 3; |
||||
|
/** |
||||
|
* Binary MD5 Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_MD5 |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_MD5 = 4; |
||||
|
/** |
||||
|
* Binary User Defined Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; |
||||
|
|
||||
|
// Return BSON
|
||||
|
module.exports = BSON; |
||||
|
module.exports.Code = Code; |
||||
|
module.exports.Map = Map; |
||||
|
module.exports.Symbol = Symbol; |
||||
|
module.exports.BSON = BSON; |
||||
|
module.exports.DBRef = DBRef; |
||||
|
module.exports.Binary = Binary; |
||||
|
module.exports.ObjectID = ObjectID; |
||||
|
module.exports.Long = Long; |
||||
|
module.exports.Timestamp = Timestamp; |
||||
|
module.exports.Double = Double; |
||||
|
module.exports.Int32 = Int32; |
||||
|
module.exports.MinKey = MinKey; |
||||
|
module.exports.MaxKey = MaxKey; |
||||
|
module.exports.BSONRegExp = BSONRegExp; |
||||
|
module.exports.Decimal128 = Decimal128; |
@ -0,0 +1,24 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON Code type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {(string|function)} code a string or function. |
||||
|
* @param {Object} [scope] an optional scope for the function. |
||||
|
* @return {Code} |
||||
|
*/ |
||||
|
var Code = function Code(code, scope) { |
||||
|
if (!(this instanceof Code)) return new Code(code, scope); |
||||
|
this._bsontype = 'Code'; |
||||
|
this.code = code; |
||||
|
this.scope = scope; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Code.prototype.toJSON = function() { |
||||
|
return { scope: this.scope, code: this.code }; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Code; |
||||
|
module.exports.Code = Code; |
@ -0,0 +1,32 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON DBRef type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {string} namespace the collection name. |
||||
|
* @param {ObjectID} oid the reference ObjectID. |
||||
|
* @param {string} [db] optional db name, if omitted the reference is local to the current db. |
||||
|
* @return {DBRef} |
||||
|
*/ |
||||
|
function DBRef(namespace, oid, db) { |
||||
|
if (!(this instanceof DBRef)) return new DBRef(namespace, oid, db); |
||||
|
|
||||
|
this._bsontype = 'DBRef'; |
||||
|
this.namespace = namespace; |
||||
|
this.oid = oid; |
||||
|
this.db = db; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
DBRef.prototype.toJSON = function() { |
||||
|
return { |
||||
|
$ref: this.namespace, |
||||
|
$id: this.oid, |
||||
|
$db: this.db == null ? '' : this.db |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
module.exports = DBRef; |
||||
|
module.exports.DBRef = DBRef; |
@ -0,0 +1,820 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
var Long = require('./long'); |
||||
|
|
||||
|
var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/; |
||||
|
var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i; |
||||
|
var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i; |
||||
|
|
||||
|
var EXPONENT_MAX = 6111; |
||||
|
var EXPONENT_MIN = -6176; |
||||
|
var EXPONENT_BIAS = 6176; |
||||
|
var MAX_DIGITS = 34; |
||||
|
|
||||
|
// Nan value bits as 32 bit values (due to lack of longs)
|
||||
|
var NAN_BUFFER = [ |
||||
|
0x7c, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00 |
||||
|
].reverse(); |
||||
|
// Infinity value bits 32 bit values (due to lack of longs)
|
||||
|
var INF_NEGATIVE_BUFFER = [ |
||||
|
0xf8, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00 |
||||
|
].reverse(); |
||||
|
var INF_POSITIVE_BUFFER = [ |
||||
|
0x78, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00, |
||||
|
0x00 |
||||
|
].reverse(); |
||||
|
|
||||
|
var EXPONENT_REGEX = /^([-+])?(\d+)?$/; |
||||
|
|
||||
|
var utils = require('./parser/utils'); |
||||
|
|
||||
|
// Detect if the value is a digit
|
||||
|
var isDigit = function(value) { |
||||
|
return !isNaN(parseInt(value, 10)); |
||||
|
}; |
||||
|
|
||||
|
// Divide two uint128 values
|
||||
|
var divideu128 = function(value) { |
||||
|
var DIVISOR = Long.fromNumber(1000 * 1000 * 1000); |
||||
|
var _rem = Long.fromNumber(0); |
||||
|
var i = 0; |
||||
|
|
||||
|
if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) { |
||||
|
return { quotient: value, rem: _rem }; |
||||
|
} |
||||
|
|
||||
|
for (i = 0; i <= 3; i++) { |
||||
|
// Adjust remainder to match value of next dividend
|
||||
|
_rem = _rem.shiftLeft(32); |
||||
|
// Add the divided to _rem
|
||||
|
_rem = _rem.add(new Long(value.parts[i], 0)); |
||||
|
value.parts[i] = _rem.div(DIVISOR).low_; |
||||
|
_rem = _rem.modulo(DIVISOR); |
||||
|
} |
||||
|
|
||||
|
return { quotient: value, rem: _rem }; |
||||
|
}; |
||||
|
|
||||
|
// Multiply two Long values and return the 128 bit value
|
||||
|
var multiply64x2 = function(left, right) { |
||||
|
if (!left && !right) { |
||||
|
return { high: Long.fromNumber(0), low: Long.fromNumber(0) }; |
||||
|
} |
||||
|
|
||||
|
var leftHigh = left.shiftRightUnsigned(32); |
||||
|
var leftLow = new Long(left.getLowBits(), 0); |
||||
|
var rightHigh = right.shiftRightUnsigned(32); |
||||
|
var rightLow = new Long(right.getLowBits(), 0); |
||||
|
|
||||
|
var productHigh = leftHigh.multiply(rightHigh); |
||||
|
var productMid = leftHigh.multiply(rightLow); |
||||
|
var productMid2 = leftLow.multiply(rightHigh); |
||||
|
var productLow = leftLow.multiply(rightLow); |
||||
|
|
||||
|
productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); |
||||
|
productMid = new Long(productMid.getLowBits(), 0) |
||||
|
.add(productMid2) |
||||
|
.add(productLow.shiftRightUnsigned(32)); |
||||
|
|
||||
|
productHigh = productHigh.add(productMid.shiftRightUnsigned(32)); |
||||
|
productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0)); |
||||
|
|
||||
|
// Return the 128 bit result
|
||||
|
return { high: productHigh, low: productLow }; |
||||
|
}; |
||||
|
|
||||
|
var lessThan = function(left, right) { |
||||
|
// Make values unsigned
|
||||
|
var uhleft = left.high_ >>> 0; |
||||
|
var uhright = right.high_ >>> 0; |
||||
|
|
||||
|
// Compare high bits first
|
||||
|
if (uhleft < uhright) { |
||||
|
return true; |
||||
|
} else if (uhleft === uhright) { |
||||
|
var ulleft = left.low_ >>> 0; |
||||
|
var ulright = right.low_ >>> 0; |
||||
|
if (ulleft < ulright) return true; |
||||
|
} |
||||
|
|
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
// var longtoHex = function(value) {
|
||||
|
// var buffer = utils.allocBuffer(8);
|
||||
|
// var index = 0;
|
||||
|
// // Encode the low 64 bits of the decimal
|
||||
|
// // Encode low bits
|
||||
|
// buffer[index++] = value.low_ & 0xff;
|
||||
|
// buffer[index++] = (value.low_ >> 8) & 0xff;
|
||||
|
// buffer[index++] = (value.low_ >> 16) & 0xff;
|
||||
|
// buffer[index++] = (value.low_ >> 24) & 0xff;
|
||||
|
// // Encode high bits
|
||||
|
// buffer[index++] = value.high_ & 0xff;
|
||||
|
// buffer[index++] = (value.high_ >> 8) & 0xff;
|
||||
|
// buffer[index++] = (value.high_ >> 16) & 0xff;
|
||||
|
// buffer[index++] = (value.high_ >> 24) & 0xff;
|
||||
|
// return buffer.reverse().toString('hex');
|
||||
|
// };
|
||||
|
|
||||
|
// var int32toHex = function(value) {
|
||||
|
// var buffer = utils.allocBuffer(4);
|
||||
|
// var index = 0;
|
||||
|
// // Encode the low 64 bits of the decimal
|
||||
|
// // Encode low bits
|
||||
|
// buffer[index++] = value & 0xff;
|
||||
|
// buffer[index++] = (value >> 8) & 0xff;
|
||||
|
// buffer[index++] = (value >> 16) & 0xff;
|
||||
|
// buffer[index++] = (value >> 24) & 0xff;
|
||||
|
// return buffer.reverse().toString('hex');
|
||||
|
// };
|
||||
|
|
||||
|
/** |
||||
|
* A class representation of the BSON Decimal128 type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {Buffer} bytes a buffer containing the raw Decimal128 bytes. |
||||
|
* @return {Double} |
||||
|
*/ |
||||
|
var Decimal128 = function(bytes) { |
||||
|
this._bsontype = 'Decimal128'; |
||||
|
this.bytes = bytes; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Create a Decimal128 instance from a string representation |
||||
|
* |
||||
|
* @method |
||||
|
* @param {string} string a numeric string representation. |
||||
|
* @return {Decimal128} returns a Decimal128 instance. |
||||
|
*/ |
||||
|
Decimal128.fromString = function(string) { |
||||
|
// Parse state tracking
|
||||
|
var isNegative = false; |
||||
|
var sawRadix = false; |
||||
|
var foundNonZero = false; |
||||
|
|
||||
|
// Total number of significant digits (no leading or trailing zero)
|
||||
|
var significantDigits = 0; |
||||
|
// Total number of significand digits read
|
||||
|
var nDigitsRead = 0; |
||||
|
// Total number of digits (no leading zeros)
|
||||
|
var nDigits = 0; |
||||
|
// The number of the digits after radix
|
||||
|
var radixPosition = 0; |
||||
|
// The index of the first non-zero in *str*
|
||||
|
var firstNonZero = 0; |
||||
|
|
||||
|
// Digits Array
|
||||
|
var digits = [0]; |
||||
|
// The number of digits in digits
|
||||
|
var nDigitsStored = 0; |
||||
|
// Insertion pointer for digits
|
||||
|
var digitsInsert = 0; |
||||
|
// The index of the first non-zero digit
|
||||
|
var firstDigit = 0; |
||||
|
// The index of the last digit
|
||||
|
var lastDigit = 0; |
||||
|
|
||||
|
// Exponent
|
||||
|
var exponent = 0; |
||||
|
// loop index over array
|
||||
|
var i = 0; |
||||
|
// The high 17 digits of the significand
|
||||
|
var significandHigh = [0, 0]; |
||||
|
// The low 17 digits of the significand
|
||||
|
var significandLow = [0, 0]; |
||||
|
// The biased exponent
|
||||
|
var biasedExponent = 0; |
||||
|
|
||||
|
// Read index
|
||||
|
var index = 0; |
||||
|
|
||||
|
// Trim the string
|
||||
|
string = string.trim(); |
||||
|
|
||||
|
// Naively prevent against REDOS attacks.
|
||||
|
// TODO: implementing a custom parsing for this, or refactoring the regex would yield
|
||||
|
// further gains.
|
||||
|
if (string.length >= 7000) { |
||||
|
throw new Error('' + string + ' not a valid Decimal128 string'); |
||||
|
} |
||||
|
|
||||
|
// Results
|
||||
|
var stringMatch = string.match(PARSE_STRING_REGEXP); |
||||
|
var infMatch = string.match(PARSE_INF_REGEXP); |
||||
|
var nanMatch = string.match(PARSE_NAN_REGEXP); |
||||
|
|
||||
|
// Validate the string
|
||||
|
if ((!stringMatch && !infMatch && !nanMatch) || string.length === 0) { |
||||
|
throw new Error('' + string + ' not a valid Decimal128 string'); |
||||
|
} |
||||
|
|
||||
|
// Check if we have an illegal exponent format
|
||||
|
if (stringMatch && stringMatch[4] && stringMatch[2] === undefined) { |
||||
|
throw new Error('' + string + ' not a valid Decimal128 string'); |
||||
|
} |
||||
|
|
||||
|
// Get the negative or positive sign
|
||||
|
if (string[index] === '+' || string[index] === '-') { |
||||
|
isNegative = string[index++] === '-'; |
||||
|
} |
||||
|
|
||||
|
// Check if user passed Infinity or NaN
|
||||
|
if (!isDigit(string[index]) && string[index] !== '.') { |
||||
|
if (string[index] === 'i' || string[index] === 'I') { |
||||
|
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); |
||||
|
} else if (string[index] === 'N') { |
||||
|
return new Decimal128(utils.toBuffer(NAN_BUFFER)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Read all the digits
|
||||
|
while (isDigit(string[index]) || string[index] === '.') { |
||||
|
if (string[index] === '.') { |
||||
|
if (sawRadix) { |
||||
|
return new Decimal128(utils.toBuffer(NAN_BUFFER)); |
||||
|
} |
||||
|
|
||||
|
sawRadix = true; |
||||
|
index = index + 1; |
||||
|
continue; |
||||
|
} |
||||
|
|
||||
|
if (nDigitsStored < 34) { |
||||
|
if (string[index] !== '0' || foundNonZero) { |
||||
|
if (!foundNonZero) { |
||||
|
firstNonZero = nDigitsRead; |
||||
|
} |
||||
|
|
||||
|
foundNonZero = true; |
||||
|
|
||||
|
// Only store 34 digits
|
||||
|
digits[digitsInsert++] = parseInt(string[index], 10); |
||||
|
nDigitsStored = nDigitsStored + 1; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (foundNonZero) { |
||||
|
nDigits = nDigits + 1; |
||||
|
} |
||||
|
|
||||
|
if (sawRadix) { |
||||
|
radixPosition = radixPosition + 1; |
||||
|
} |
||||
|
|
||||
|
nDigitsRead = nDigitsRead + 1; |
||||
|
index = index + 1; |
||||
|
} |
||||
|
|
||||
|
if (sawRadix && !nDigitsRead) { |
||||
|
throw new Error('' + string + ' not a valid Decimal128 string'); |
||||
|
} |
||||
|
|
||||
|
// Read exponent if exists
|
||||
|
if (string[index] === 'e' || string[index] === 'E') { |
||||
|
// Read exponent digits
|
||||
|
var match = string.substr(++index).match(EXPONENT_REGEX); |
||||
|
|
||||
|
// No digits read
|
||||
|
if (!match || !match[2]) { |
||||
|
return new Decimal128(utils.toBuffer(NAN_BUFFER)); |
||||
|
} |
||||
|
|
||||
|
// Get exponent
|
||||
|
exponent = parseInt(match[0], 10); |
||||
|
|
||||
|
// Adjust the index
|
||||
|
index = index + match[0].length; |
||||
|
} |
||||
|
|
||||
|
// Return not a number
|
||||
|
if (string[index]) { |
||||
|
return new Decimal128(utils.toBuffer(NAN_BUFFER)); |
||||
|
} |
||||
|
|
||||
|
// Done reading input
|
||||
|
// Find first non-zero digit in digits
|
||||
|
firstDigit = 0; |
||||
|
|
||||
|
if (!nDigitsStored) { |
||||
|
firstDigit = 0; |
||||
|
lastDigit = 0; |
||||
|
digits[0] = 0; |
||||
|
nDigits = 1; |
||||
|
nDigitsStored = 1; |
||||
|
significantDigits = 0; |
||||
|
} else { |
||||
|
lastDigit = nDigitsStored - 1; |
||||
|
significantDigits = nDigits; |
||||
|
|
||||
|
if (exponent !== 0 && significantDigits !== 1) { |
||||
|
while (string[firstNonZero + significantDigits - 1] === '0') { |
||||
|
significantDigits = significantDigits - 1; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Normalization of exponent
|
||||
|
// Correct exponent based on radix position, and shift significand as needed
|
||||
|
// to represent user input
|
||||
|
|
||||
|
// Overflow prevention
|
||||
|
if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { |
||||
|
exponent = EXPONENT_MIN; |
||||
|
} else { |
||||
|
exponent = exponent - radixPosition; |
||||
|
} |
||||
|
|
||||
|
// Attempt to normalize the exponent
|
||||
|
while (exponent > EXPONENT_MAX) { |
||||
|
// Shift exponent to significand and decrease
|
||||
|
lastDigit = lastDigit + 1; |
||||
|
|
||||
|
if (lastDigit - firstDigit > MAX_DIGITS) { |
||||
|
// Check if we have a zero then just hard clamp, otherwise fail
|
||||
|
var digitsString = digits.join(''); |
||||
|
if (digitsString.match(/^0+$/)) { |
||||
|
exponent = EXPONENT_MAX; |
||||
|
break; |
||||
|
} else { |
||||
|
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
exponent = exponent - 1; |
||||
|
} |
||||
|
|
||||
|
while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { |
||||
|
// Shift last digit
|
||||
|
if (lastDigit === 0) { |
||||
|
exponent = EXPONENT_MIN; |
||||
|
significantDigits = 0; |
||||
|
break; |
||||
|
} |
||||
|
|
||||
|
if (nDigitsStored < nDigits) { |
||||
|
// adjust to match digits not stored
|
||||
|
nDigits = nDigits - 1; |
||||
|
} else { |
||||
|
// adjust to round
|
||||
|
lastDigit = lastDigit - 1; |
||||
|
} |
||||
|
|
||||
|
if (exponent < EXPONENT_MAX) { |
||||
|
exponent = exponent + 1; |
||||
|
} else { |
||||
|
// Check if we have a zero then just hard clamp, otherwise fail
|
||||
|
digitsString = digits.join(''); |
||||
|
if (digitsString.match(/^0+$/)) { |
||||
|
exponent = EXPONENT_MAX; |
||||
|
break; |
||||
|
} else { |
||||
|
return new Decimal128(utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER)); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Round
|
||||
|
// We've normalized the exponent, but might still need to round.
|
||||
|
if (lastDigit - firstDigit + 1 < significantDigits && string[significantDigits] !== '0') { |
||||
|
var endOfString = nDigitsRead; |
||||
|
|
||||
|
// If we have seen a radix point, 'string' is 1 longer than we have
|
||||
|
// documented with ndigits_read, so inc the position of the first nonzero
|
||||
|
// digit and the position that digits are read to.
|
||||
|
if (sawRadix && exponent === EXPONENT_MIN) { |
||||
|
firstNonZero = firstNonZero + 1; |
||||
|
endOfString = endOfString + 1; |
||||
|
} |
||||
|
|
||||
|
var roundDigit = parseInt(string[firstNonZero + lastDigit + 1], 10); |
||||
|
var roundBit = 0; |
||||
|
|
||||
|
if (roundDigit >= 5) { |
||||
|
roundBit = 1; |
||||
|
|
||||
|
if (roundDigit === 5) { |
||||
|
roundBit = digits[lastDigit] % 2 === 1; |
||||
|
|
||||
|
for (i = firstNonZero + lastDigit + 2; i < endOfString; i++) { |
||||
|
if (parseInt(string[i], 10)) { |
||||
|
roundBit = 1; |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
if (roundBit) { |
||||
|
var dIdx = lastDigit; |
||||
|
|
||||
|
for (; dIdx >= 0; dIdx--) { |
||||
|
if (++digits[dIdx] > 9) { |
||||
|
digits[dIdx] = 0; |
||||
|
|
||||
|
// overflowed most significant digit
|
||||
|
if (dIdx === 0) { |
||||
|
if (exponent < EXPONENT_MAX) { |
||||
|
exponent = exponent + 1; |
||||
|
digits[dIdx] = 1; |
||||
|
} else { |
||||
|
return new Decimal128( |
||||
|
utils.toBuffer(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER) |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
} else { |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Encode significand
|
||||
|
// The high 17 digits of the significand
|
||||
|
significandHigh = Long.fromNumber(0); |
||||
|
// The low 17 digits of the significand
|
||||
|
significandLow = Long.fromNumber(0); |
||||
|
|
||||
|
// read a zero
|
||||
|
if (significantDigits === 0) { |
||||
|
significandHigh = Long.fromNumber(0); |
||||
|
significandLow = Long.fromNumber(0); |
||||
|
} else if (lastDigit - firstDigit < 17) { |
||||
|
dIdx = firstDigit; |
||||
|
significandLow = Long.fromNumber(digits[dIdx++]); |
||||
|
significandHigh = new Long(0, 0); |
||||
|
|
||||
|
for (; dIdx <= lastDigit; dIdx++) { |
||||
|
significandLow = significandLow.multiply(Long.fromNumber(10)); |
||||
|
significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); |
||||
|
} |
||||
|
} else { |
||||
|
dIdx = firstDigit; |
||||
|
significandHigh = Long.fromNumber(digits[dIdx++]); |
||||
|
|
||||
|
for (; dIdx <= lastDigit - 17; dIdx++) { |
||||
|
significandHigh = significandHigh.multiply(Long.fromNumber(10)); |
||||
|
significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx])); |
||||
|
} |
||||
|
|
||||
|
significandLow = Long.fromNumber(digits[dIdx++]); |
||||
|
|
||||
|
for (; dIdx <= lastDigit; dIdx++) { |
||||
|
significandLow = significandLow.multiply(Long.fromNumber(10)); |
||||
|
significandLow = significandLow.add(Long.fromNumber(digits[dIdx])); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var significand = multiply64x2(significandHigh, Long.fromString('100000000000000000')); |
||||
|
|
||||
|
significand.low = significand.low.add(significandLow); |
||||
|
|
||||
|
if (lessThan(significand.low, significandLow)) { |
||||
|
significand.high = significand.high.add(Long.fromNumber(1)); |
||||
|
} |
||||
|
|
||||
|
// Biased exponent
|
||||
|
biasedExponent = exponent + EXPONENT_BIAS; |
||||
|
var dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; |
||||
|
|
||||
|
// Encode combination, exponent, and significand.
|
||||
|
if ( |
||||
|
significand.high |
||||
|
.shiftRightUnsigned(49) |
||||
|
.and(Long.fromNumber(1)) |
||||
|
.equals(Long.fromNumber) |
||||
|
) { |
||||
|
// Encode '11' into bits 1 to 3
|
||||
|
dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61)); |
||||
|
dec.high = dec.high.or( |
||||
|
Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)) |
||||
|
); |
||||
|
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff))); |
||||
|
} else { |
||||
|
dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49)); |
||||
|
dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff))); |
||||
|
} |
||||
|
|
||||
|
dec.low = significand.low; |
||||
|
|
||||
|
// Encode sign
|
||||
|
if (isNegative) { |
||||
|
dec.high = dec.high.or(Long.fromString('9223372036854775808')); |
||||
|
} |
||||
|
|
||||
|
// Encode into a buffer
|
||||
|
var buffer = utils.allocBuffer(16); |
||||
|
index = 0; |
||||
|
|
||||
|
// Encode the low 64 bits of the decimal
|
||||
|
// Encode low bits
|
||||
|
buffer[index++] = dec.low.low_ & 0xff; |
||||
|
buffer[index++] = (dec.low.low_ >> 8) & 0xff; |
||||
|
buffer[index++] = (dec.low.low_ >> 16) & 0xff; |
||||
|
buffer[index++] = (dec.low.low_ >> 24) & 0xff; |
||||
|
// Encode high bits
|
||||
|
buffer[index++] = dec.low.high_ & 0xff; |
||||
|
buffer[index++] = (dec.low.high_ >> 8) & 0xff; |
||||
|
buffer[index++] = (dec.low.high_ >> 16) & 0xff; |
||||
|
buffer[index++] = (dec.low.high_ >> 24) & 0xff; |
||||
|
|
||||
|
// Encode the high 64 bits of the decimal
|
||||
|
// Encode low bits
|
||||
|
buffer[index++] = dec.high.low_ & 0xff; |
||||
|
buffer[index++] = (dec.high.low_ >> 8) & 0xff; |
||||
|
buffer[index++] = (dec.high.low_ >> 16) & 0xff; |
||||
|
buffer[index++] = (dec.high.low_ >> 24) & 0xff; |
||||
|
// Encode high bits
|
||||
|
buffer[index++] = dec.high.high_ & 0xff; |
||||
|
buffer[index++] = (dec.high.high_ >> 8) & 0xff; |
||||
|
buffer[index++] = (dec.high.high_ >> 16) & 0xff; |
||||
|
buffer[index++] = (dec.high.high_ >> 24) & 0xff; |
||||
|
|
||||
|
// Return the new Decimal128
|
||||
|
return new Decimal128(buffer); |
||||
|
}; |
||||
|
|
||||
|
// Extract least significant 5 bits
|
||||
|
var COMBINATION_MASK = 0x1f; |
||||
|
// Extract least significant 14 bits
|
||||
|
var EXPONENT_MASK = 0x3fff; |
||||
|
// Value of combination field for Inf
|
||||
|
var COMBINATION_INFINITY = 30; |
||||
|
// Value of combination field for NaN
|
||||
|
var COMBINATION_NAN = 31; |
||||
|
// Value of combination field for NaN
|
||||
|
// var COMBINATION_SNAN = 32;
|
||||
|
// decimal128 exponent bias
|
||||
|
EXPONENT_BIAS = 6176; |
||||
|
|
||||
|
/** |
||||
|
* Create a string representation of the raw Decimal128 value |
||||
|
* |
||||
|
* @method |
||||
|
* @return {string} returns a Decimal128 string representation. |
||||
|
*/ |
||||
|
Decimal128.prototype.toString = function() { |
||||
|
// Note: bits in this routine are referred to starting at 0,
|
||||
|
// from the sign bit, towards the coefficient.
|
||||
|
|
||||
|
// bits 0 - 31
|
||||
|
var high; |
||||
|
// bits 32 - 63
|
||||
|
var midh; |
||||
|
// bits 64 - 95
|
||||
|
var midl; |
||||
|
// bits 96 - 127
|
||||
|
var low; |
||||
|
// bits 1 - 5
|
||||
|
var combination; |
||||
|
// decoded biased exponent (14 bits)
|
||||
|
var biased_exponent; |
||||
|
// the number of significand digits
|
||||
|
var significand_digits = 0; |
||||
|
// the base-10 digits in the significand
|
||||
|
var significand = new Array(36); |
||||
|
for (var i = 0; i < significand.length; i++) significand[i] = 0; |
||||
|
// read pointer into significand
|
||||
|
var index = 0; |
||||
|
|
||||
|
// unbiased exponent
|
||||
|
var exponent; |
||||
|
// the exponent if scientific notation is used
|
||||
|
var scientific_exponent; |
||||
|
|
||||
|
// true if the number is zero
|
||||
|
var is_zero = false; |
||||
|
|
||||
|
// the most signifcant significand bits (50-46)
|
||||
|
var significand_msb; |
||||
|
// temporary storage for significand decoding
|
||||
|
var significand128 = { parts: new Array(4) }; |
||||
|
// indexing variables
|
||||
|
i; |
||||
|
var j, k; |
||||
|
|
||||
|
// Output string
|
||||
|
var string = []; |
||||
|
|
||||
|
// Unpack index
|
||||
|
index = 0; |
||||
|
|
||||
|
// Buffer reference
|
||||
|
var buffer = this.bytes; |
||||
|
|
||||
|
// Unpack the low 64bits into a long
|
||||
|
low = |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); |
||||
|
midl = |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); |
||||
|
|
||||
|
// Unpack the high 64bits into a long
|
||||
|
midh = |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); |
||||
|
high = |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); |
||||
|
|
||||
|
// Unpack index
|
||||
|
index = 0; |
||||
|
|
||||
|
// Create the state of the decimal
|
||||
|
var dec = { |
||||
|
low: new Long(low, midl), |
||||
|
high: new Long(midh, high) |
||||
|
}; |
||||
|
|
||||
|
if (dec.high.lessThan(Long.ZERO)) { |
||||
|
string.push('-'); |
||||
|
} |
||||
|
|
||||
|
// Decode combination field and exponent
|
||||
|
combination = (high >> 26) & COMBINATION_MASK; |
||||
|
|
||||
|
if (combination >> 3 === 3) { |
||||
|
// Check for 'special' values
|
||||
|
if (combination === COMBINATION_INFINITY) { |
||||
|
return string.join('') + 'Infinity'; |
||||
|
} else if (combination === COMBINATION_NAN) { |
||||
|
return 'NaN'; |
||||
|
} else { |
||||
|
biased_exponent = (high >> 15) & EXPONENT_MASK; |
||||
|
significand_msb = 0x08 + ((high >> 14) & 0x01); |
||||
|
} |
||||
|
} else { |
||||
|
significand_msb = (high >> 14) & 0x07; |
||||
|
biased_exponent = (high >> 17) & EXPONENT_MASK; |
||||
|
} |
||||
|
|
||||
|
exponent = biased_exponent - EXPONENT_BIAS; |
||||
|
|
||||
|
// Create string of significand digits
|
||||
|
|
||||
|
// Convert the 114-bit binary number represented by
|
||||
|
// (significand_high, significand_low) to at most 34 decimal
|
||||
|
// digits through modulo and division.
|
||||
|
significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14); |
||||
|
significand128.parts[1] = midh; |
||||
|
significand128.parts[2] = midl; |
||||
|
significand128.parts[3] = low; |
||||
|
|
||||
|
if ( |
||||
|
significand128.parts[0] === 0 && |
||||
|
significand128.parts[1] === 0 && |
||||
|
significand128.parts[2] === 0 && |
||||
|
significand128.parts[3] === 0 |
||||
|
) { |
||||
|
is_zero = true; |
||||
|
} else { |
||||
|
for (k = 3; k >= 0; k--) { |
||||
|
var least_digits = 0; |
||||
|
// Peform the divide
|
||||
|
var result = divideu128(significand128); |
||||
|
significand128 = result.quotient; |
||||
|
least_digits = result.rem.low_; |
||||
|
|
||||
|
// We now have the 9 least significant digits (in base 2).
|
||||
|
// Convert and output to string.
|
||||
|
if (!least_digits) continue; |
||||
|
|
||||
|
for (j = 8; j >= 0; j--) { |
||||
|
// significand[k * 9 + j] = Math.round(least_digits % 10);
|
||||
|
significand[k * 9 + j] = least_digits % 10; |
||||
|
// least_digits = Math.round(least_digits / 10);
|
||||
|
least_digits = Math.floor(least_digits / 10); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Output format options:
|
||||
|
// Scientific - [-]d.dddE(+/-)dd or [-]dE(+/-)dd
|
||||
|
// Regular - ddd.ddd
|
||||
|
|
||||
|
if (is_zero) { |
||||
|
significand_digits = 1; |
||||
|
significand[index] = 0; |
||||
|
} else { |
||||
|
significand_digits = 36; |
||||
|
i = 0; |
||||
|
|
||||
|
while (!significand[index]) { |
||||
|
i++; |
||||
|
significand_digits = significand_digits - 1; |
||||
|
index = index + 1; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
scientific_exponent = significand_digits - 1 + exponent; |
||||
|
|
||||
|
// The scientific exponent checks are dictated by the string conversion
|
||||
|
// specification and are somewhat arbitrary cutoffs.
|
||||
|
//
|
||||
|
// We must check exponent > 0, because if this is the case, the number
|
||||
|
// has trailing zeros. However, we *cannot* output these trailing zeros,
|
||||
|
// because doing so would change the precision of the value, and would
|
||||
|
// change stored data if the string converted number is round tripped.
|
||||
|
|
||||
|
if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { |
||||
|
// Scientific format
|
||||
|
string.push(significand[index++]); |
||||
|
significand_digits = significand_digits - 1; |
||||
|
|
||||
|
if (significand_digits) { |
||||
|
string.push('.'); |
||||
|
} |
||||
|
|
||||
|
for (i = 0; i < significand_digits; i++) { |
||||
|
string.push(significand[index++]); |
||||
|
} |
||||
|
|
||||
|
// Exponent
|
||||
|
string.push('E'); |
||||
|
if (scientific_exponent > 0) { |
||||
|
string.push('+' + scientific_exponent); |
||||
|
} else { |
||||
|
string.push(scientific_exponent); |
||||
|
} |
||||
|
} else { |
||||
|
// Regular format with no decimal place
|
||||
|
if (exponent >= 0) { |
||||
|
for (i = 0; i < significand_digits; i++) { |
||||
|
string.push(significand[index++]); |
||||
|
} |
||||
|
} else { |
||||
|
var radix_position = significand_digits + exponent; |
||||
|
|
||||
|
// non-zero digits before radix
|
||||
|
if (radix_position > 0) { |
||||
|
for (i = 0; i < radix_position; i++) { |
||||
|
string.push(significand[index++]); |
||||
|
} |
||||
|
} else { |
||||
|
string.push('0'); |
||||
|
} |
||||
|
|
||||
|
string.push('.'); |
||||
|
// add leading zeros after radix
|
||||
|
while (radix_position++ < 0) { |
||||
|
string.push('0'); |
||||
|
} |
||||
|
|
||||
|
for (i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) { |
||||
|
string.push(significand[index++]); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return string.join(''); |
||||
|
}; |
||||
|
|
||||
|
Decimal128.prototype.toJSON = function() { |
||||
|
return { $numberDecimal: this.toString() }; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Decimal128; |
||||
|
module.exports.Decimal128 = Decimal128; |
@ -0,0 +1,33 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON Double type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {number} value the number we want to represent as a double. |
||||
|
* @return {Double} |
||||
|
*/ |
||||
|
function Double(value) { |
||||
|
if (!(this instanceof Double)) return new Double(value); |
||||
|
|
||||
|
this._bsontype = 'Double'; |
||||
|
this.value = value; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Access the number value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} returns the wrapped double number. |
||||
|
*/ |
||||
|
Double.prototype.valueOf = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Double.prototype.toJSON = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Double; |
||||
|
module.exports.Double = Double; |
@ -0,0 +1,124 @@ |
|||||
|
// Copyright (c) 2008, Fair Oaks Labs, Inc.
|
||||
|
// All rights reserved.
|
||||
|
//
|
||||
|
// Redistribution and use in source and binary forms, with or without
|
||||
|
// modification, are permitted provided that the following conditions are met:
|
||||
|
//
|
||||
|
// * Redistributions of source code must retain the above copyright notice,
|
||||
|
// this list of conditions and the following disclaimer.
|
||||
|
//
|
||||
|
// * Redistributions in binary form must reproduce the above copyright notice,
|
||||
|
// this list of conditions and the following disclaimer in the documentation
|
||||
|
// and/or other materials provided with the distribution.
|
||||
|
//
|
||||
|
// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors
|
||||
|
// may be used to endorse or promote products derived from this software
|
||||
|
// without specific prior written permission.
|
||||
|
//
|
||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
|
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
|
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
|
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
|
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
|
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
|
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
|
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
|
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
|
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
|
// POSSIBILITY OF SUCH DAMAGE.
|
||||
|
//
|
||||
|
//
|
||||
|
// Modifications to writeIEEE754 to support negative zeroes made by Brian White
|
||||
|
|
||||
|
var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { |
||||
|
var e, |
||||
|
m, |
||||
|
bBE = endian === 'big', |
||||
|
eLen = nBytes * 8 - mLen - 1, |
||||
|
eMax = (1 << eLen) - 1, |
||||
|
eBias = eMax >> 1, |
||||
|
nBits = -7, |
||||
|
i = bBE ? 0 : nBytes - 1, |
||||
|
d = bBE ? 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); |
||||
|
}; |
||||
|
|
||||
|
var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { |
||||
|
var e, |
||||
|
m, |
||||
|
c, |
||||
|
bBE = endian === 'big', |
||||
|
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 = bBE ? nBytes - 1 : 0, |
||||
|
d = bBE ? -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; |
||||
|
}; |
||||
|
|
||||
|
exports.readIEEE754 = readIEEE754; |
||||
|
exports.writeIEEE754 = writeIEEE754; |
@ -0,0 +1,33 @@ |
|||||
|
/** |
||||
|
* A class representation of a BSON Int32 type. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {number} value the number we want to represent as an int32. |
||||
|
* @return {Int32} |
||||
|
*/ |
||||
|
var Int32 = function(value) { |
||||
|
if (!(this instanceof Int32)) return new Int32(value); |
||||
|
|
||||
|
this._bsontype = 'Int32'; |
||||
|
this.value = value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Access the number value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} returns the wrapped int32 number. |
||||
|
*/ |
||||
|
Int32.prototype.valueOf = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Int32.prototype.toJSON = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Int32; |
||||
|
module.exports.Int32 = Int32; |
@ -0,0 +1,851 @@ |
|||||
|
// 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.
|
||||
|
//
|
||||
|
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
|
||||
|
/** |
||||
|
* Defines a Long class for representing a 64-bit two's-complement |
||||
|
* integer value, which faithfully simulates the behavior of a Java "Long". This |
||||
|
* implementation is derived from LongLib in GWT. |
||||
|
* |
||||
|
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit |
||||
|
* values as *signed* integers. See the from* functions below for more |
||||
|
* convenient ways of constructing Longs. |
||||
|
* |
||||
|
* The internal representation of a Long is the two given signed, 32-bit values. |
||||
|
* We use 32-bit pieces because these are the size of integers on which |
||||
|
* Javascript performs bit-operations. For operations like addition and |
||||
|
* multiplication, we split each number into 16-bit pieces, which can easily be |
||||
|
* multiplied within Javascript's floating-point representation without overflow |
||||
|
* or change in sign. |
||||
|
* |
||||
|
* In the algorithms below, we frequently reduce the negative case to the |
||||
|
* positive case by negating the input(s) and then post-processing the result. |
||||
|
* Note that we must ALWAYS check specially whether those values are MIN_VALUE |
||||
|
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as |
||||
|
* a positive number, it overflows back into a negative). Not handling this |
||||
|
* case would often result in infinite recursion. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {number} low the low (signed) 32 bits of the Long. |
||||
|
* @param {number} high the high (signed) 32 bits of the Long. |
||||
|
* @return {Long} |
||||
|
*/ |
||||
|
function Long(low, high) { |
||||
|
if (!(this instanceof Long)) return new Long(low, high); |
||||
|
|
||||
|
this._bsontype = 'Long'; |
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
this.high_ = high | 0; // force into 32 signed bits.
|
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Return the int value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the value, assuming it is a 32-bit integer. |
||||
|
*/ |
||||
|
Long.prototype.toInt = function() { |
||||
|
return this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the Number value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the closest floating-point representation to this value. |
||||
|
*/ |
||||
|
Long.prototype.toNumber = function() { |
||||
|
return this.high_ * Long.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the JSON value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {string} the JSON representation. |
||||
|
*/ |
||||
|
Long.prototype.toJSON = function() { |
||||
|
return this.toString(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the String value. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} [opt_radix] the radix in which the text should be written. |
||||
|
* @return {string} the textual representation of this value. |
||||
|
*/ |
||||
|
Long.prototype.toString = function(opt_radix) { |
||||
|
var radix = opt_radix || 10; |
||||
|
if (radix < 2 || 36 < radix) { |
||||
|
throw Error('radix out of range: ' + radix); |
||||
|
} |
||||
|
|
||||
|
if (this.isZero()) { |
||||
|
return '0'; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (this.equals(Long.MIN_VALUE)) { |
||||
|
// We need to change the Long value before it can be negated, so we remove
|
||||
|
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
|
var radixLong = Long.fromNumber(radix); |
||||
|
var div = this.div(radixLong); |
||||
|
var rem = div.multiply(radixLong).subtract(this); |
||||
|
return div.toString(radix) + rem.toInt().toString(radix); |
||||
|
} else { |
||||
|
return '-' + this.negate().toString(radix); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Do several (6) digits each time through the loop, so as to
|
||||
|
// minimize the calls to the very expensive emulated div.
|
||||
|
var radixToPower = Long.fromNumber(Math.pow(radix, 6)); |
||||
|
|
||||
|
rem = this; |
||||
|
var result = ''; |
||||
|
|
||||
|
while (!rem.isZero()) { |
||||
|
var remDiv = rem.div(radixToPower); |
||||
|
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); |
||||
|
var digits = intval.toString(radix); |
||||
|
|
||||
|
rem = remDiv; |
||||
|
if (rem.isZero()) { |
||||
|
return digits + result; |
||||
|
} else { |
||||
|
while (digits.length < 6) { |
||||
|
digits = '0' + digits; |
||||
|
} |
||||
|
result = '' + digits + result; |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the high 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the high 32-bits as a signed value. |
||||
|
*/ |
||||
|
Long.prototype.getHighBits = function() { |
||||
|
return this.high_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the low 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the low 32-bits as a signed value. |
||||
|
*/ |
||||
|
Long.prototype.getLowBits = function() { |
||||
|
return this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the low unsigned 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the low 32-bits as an unsigned value. |
||||
|
*/ |
||||
|
Long.prototype.getLowBitsUnsigned = function() { |
||||
|
return this.low_ >= 0 ? this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the number of bits needed to represent the absolute value of this Long. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} Returns the number of bits needed to represent the absolute value of this Long. |
||||
|
*/ |
||||
|
Long.prototype.getNumBitsAbs = function() { |
||||
|
if (this.isNegative()) { |
||||
|
if (this.equals(Long.MIN_VALUE)) { |
||||
|
return 64; |
||||
|
} else { |
||||
|
return this.negate().getNumBitsAbs(); |
||||
|
} |
||||
|
} else { |
||||
|
var val = this.high_ !== 0 ? this.high_ : this.low_; |
||||
|
for (var bit = 31; bit > 0; bit--) { |
||||
|
if ((val & (1 << bit)) !== 0) { |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
return this.high_ !== 0 ? bit + 33 : bit + 1; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is zero. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is zero. |
||||
|
*/ |
||||
|
Long.prototype.isZero = function() { |
||||
|
return this.high_ === 0 && this.low_ === 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is negative. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is negative. |
||||
|
*/ |
||||
|
Long.prototype.isNegative = function() { |
||||
|
return this.high_ < 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is odd. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is odd. |
||||
|
*/ |
||||
|
Long.prototype.isOdd = function() { |
||||
|
return (this.low_ & 1) === 1; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long equals the other |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long equals the other |
||||
|
*/ |
||||
|
Long.prototype.equals = function(other) { |
||||
|
return this.high_ === other.high_ && this.low_ === other.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long does not equal the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long does not equal the other. |
||||
|
*/ |
||||
|
Long.prototype.notEquals = function(other) { |
||||
|
return this.high_ !== other.high_ || this.low_ !== other.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long is less than the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long is less than the other. |
||||
|
*/ |
||||
|
Long.prototype.lessThan = function(other) { |
||||
|
return this.compare(other) < 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long is less than or equal to the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long is less than or equal to the other. |
||||
|
*/ |
||||
|
Long.prototype.lessThanOrEqual = function(other) { |
||||
|
return this.compare(other) <= 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long is greater than the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long is greater than the other. |
||||
|
*/ |
||||
|
Long.prototype.greaterThan = function(other) { |
||||
|
return this.compare(other) > 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Long is greater than or equal to the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} whether this Long is greater than or equal to the other. |
||||
|
*/ |
||||
|
Long.prototype.greaterThanOrEqual = function(other) { |
||||
|
return this.compare(other) >= 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Compares this Long with the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to compare against. |
||||
|
* @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. |
||||
|
*/ |
||||
|
Long.prototype.compare = function(other) { |
||||
|
if (this.equals(other)) { |
||||
|
return 0; |
||||
|
} |
||||
|
|
||||
|
var thisNeg = this.isNegative(); |
||||
|
var otherNeg = other.isNegative(); |
||||
|
if (thisNeg && !otherNeg) { |
||||
|
return -1; |
||||
|
} |
||||
|
if (!thisNeg && otherNeg) { |
||||
|
return 1; |
||||
|
} |
||||
|
|
||||
|
// at this point, the signs are the same, so subtraction will not overflow
|
||||
|
if (this.subtract(other).isNegative()) { |
||||
|
return -1; |
||||
|
} else { |
||||
|
return 1; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* The negation of this value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {Long} the negation of this value. |
||||
|
*/ |
||||
|
Long.prototype.negate = function() { |
||||
|
if (this.equals(Long.MIN_VALUE)) { |
||||
|
return Long.MIN_VALUE; |
||||
|
} else { |
||||
|
return this.not().add(Long.ONE); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the sum of this and the given Long. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to add to this one. |
||||
|
* @return {Long} the sum of this and the given Long. |
||||
|
*/ |
||||
|
Long.prototype.add = function(other) { |
||||
|
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
|
||||
|
var a48 = this.high_ >>> 16; |
||||
|
var a32 = this.high_ & 0xffff; |
||||
|
var a16 = this.low_ >>> 16; |
||||
|
var a00 = this.low_ & 0xffff; |
||||
|
|
||||
|
var b48 = other.high_ >>> 16; |
||||
|
var b32 = other.high_ & 0xffff; |
||||
|
var b16 = other.low_ >>> 16; |
||||
|
var b00 = other.low_ & 0xffff; |
||||
|
|
||||
|
var c48 = 0, |
||||
|
c32 = 0, |
||||
|
c16 = 0, |
||||
|
c00 = 0; |
||||
|
c00 += a00 + b00; |
||||
|
c16 += c00 >>> 16; |
||||
|
c00 &= 0xffff; |
||||
|
c16 += a16 + b16; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c32 += a32 + b32; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c48 += a48 + b48; |
||||
|
c48 &= 0xffff; |
||||
|
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the difference of this and the given Long. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to subtract from this. |
||||
|
* @return {Long} the difference of this and the given Long. |
||||
|
*/ |
||||
|
Long.prototype.subtract = function(other) { |
||||
|
return this.add(other.negate()); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the product of this and the given Long. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long to multiply with this. |
||||
|
* @return {Long} the product of this and the other. |
||||
|
*/ |
||||
|
Long.prototype.multiply = function(other) { |
||||
|
if (this.isZero()) { |
||||
|
return Long.ZERO; |
||||
|
} else if (other.isZero()) { |
||||
|
return Long.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.equals(Long.MIN_VALUE)) { |
||||
|
return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; |
||||
|
} else if (other.equals(Long.MIN_VALUE)) { |
||||
|
return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (other.isNegative()) { |
||||
|
return this.negate().multiply(other.negate()); |
||||
|
} else { |
||||
|
return this.negate() |
||||
|
.multiply(other) |
||||
|
.negate(); |
||||
|
} |
||||
|
} else if (other.isNegative()) { |
||||
|
return this.multiply(other.negate()).negate(); |
||||
|
} |
||||
|
|
||||
|
// If both Longs are small, use float multiplication
|
||||
|
if (this.lessThan(Long.TWO_PWR_24_) && other.lessThan(Long.TWO_PWR_24_)) { |
||||
|
return Long.fromNumber(this.toNumber() * other.toNumber()); |
||||
|
} |
||||
|
|
||||
|
// Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
|
// We can skip products that would overflow.
|
||||
|
|
||||
|
var a48 = this.high_ >>> 16; |
||||
|
var a32 = this.high_ & 0xffff; |
||||
|
var a16 = this.low_ >>> 16; |
||||
|
var a00 = this.low_ & 0xffff; |
||||
|
|
||||
|
var b48 = other.high_ >>> 16; |
||||
|
var b32 = other.high_ & 0xffff; |
||||
|
var b16 = other.low_ >>> 16; |
||||
|
var b00 = other.low_ & 0xffff; |
||||
|
|
||||
|
var c48 = 0, |
||||
|
c32 = 0, |
||||
|
c16 = 0, |
||||
|
c00 = 0; |
||||
|
c00 += a00 * b00; |
||||
|
c16 += c00 >>> 16; |
||||
|
c00 &= 0xffff; |
||||
|
c16 += a16 * b00; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c16 += a00 * b16; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c32 += a32 * b00; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c32 += a16 * b16; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c32 += a00 * b32; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; |
||||
|
c48 &= 0xffff; |
||||
|
return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Long divided by the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long by which to divide. |
||||
|
* @return {Long} this Long divided by the given one. |
||||
|
*/ |
||||
|
Long.prototype.div = function(other) { |
||||
|
if (other.isZero()) { |
||||
|
throw Error('division by zero'); |
||||
|
} else if (this.isZero()) { |
||||
|
return Long.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.equals(Long.MIN_VALUE)) { |
||||
|
if (other.equals(Long.ONE) || other.equals(Long.NEG_ONE)) { |
||||
|
return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
|
} else if (other.equals(Long.MIN_VALUE)) { |
||||
|
return Long.ONE; |
||||
|
} else { |
||||
|
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
|
var halfThis = this.shiftRight(1); |
||||
|
var approx = halfThis.div(other).shiftLeft(1); |
||||
|
if (approx.equals(Long.ZERO)) { |
||||
|
return other.isNegative() ? Long.ONE : Long.NEG_ONE; |
||||
|
} else { |
||||
|
var rem = this.subtract(other.multiply(approx)); |
||||
|
var result = approx.add(rem.div(other)); |
||||
|
return result; |
||||
|
} |
||||
|
} |
||||
|
} else if (other.equals(Long.MIN_VALUE)) { |
||||
|
return Long.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (other.isNegative()) { |
||||
|
return this.negate().div(other.negate()); |
||||
|
} else { |
||||
|
return this.negate() |
||||
|
.div(other) |
||||
|
.negate(); |
||||
|
} |
||||
|
} else if (other.isNegative()) { |
||||
|
return this.div(other.negate()).negate(); |
||||
|
} |
||||
|
|
||||
|
// Repeat the following until the remainder is less than other: find a
|
||||
|
// floating-point that approximates remainder / other *from below*, add this
|
||||
|
// into the result, and subtract it from the remainder. It is critical that
|
||||
|
// the approximate value is less than or equal to the real value so that the
|
||||
|
// remainder never becomes negative.
|
||||
|
var res = Long.ZERO; |
||||
|
rem = this; |
||||
|
while (rem.greaterThanOrEqual(other)) { |
||||
|
// Approximate the result of division. This may be a little greater or
|
||||
|
// smaller than the actual value.
|
||||
|
approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); |
||||
|
|
||||
|
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
|
// the smallest non-fractional digit, whichever is larger.
|
||||
|
var log2 = Math.ceil(Math.log(approx) / Math.LN2); |
||||
|
var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); |
||||
|
|
||||
|
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
|
// that if it is too large, the product overflows and is negative.
|
||||
|
var approxRes = Long.fromNumber(approx); |
||||
|
var approxRem = approxRes.multiply(other); |
||||
|
while (approxRem.isNegative() || approxRem.greaterThan(rem)) { |
||||
|
approx -= delta; |
||||
|
approxRes = Long.fromNumber(approx); |
||||
|
approxRem = approxRes.multiply(other); |
||||
|
} |
||||
|
|
||||
|
// We know the answer can't be zero... and actually, zero would cause
|
||||
|
// infinite recursion since we would make no progress.
|
||||
|
if (approxRes.isZero()) { |
||||
|
approxRes = Long.ONE; |
||||
|
} |
||||
|
|
||||
|
res = res.add(approxRes); |
||||
|
rem = rem.subtract(approxRem); |
||||
|
} |
||||
|
return res; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Long modulo the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other Long by which to mod. |
||||
|
* @return {Long} this Long modulo the given one. |
||||
|
*/ |
||||
|
Long.prototype.modulo = function(other) { |
||||
|
return this.subtract(this.div(other).multiply(other)); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* The bitwise-NOT of this value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {Long} the bitwise-NOT of this value. |
||||
|
*/ |
||||
|
Long.prototype.not = function() { |
||||
|
return Long.fromBits(~this.low_, ~this.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-AND of this Long and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other the Long with which to AND. |
||||
|
* @return {Long} the bitwise-AND of this and the other. |
||||
|
*/ |
||||
|
Long.prototype.and = function(other) { |
||||
|
return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-OR of this Long and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other the Long with which to OR. |
||||
|
* @return {Long} the bitwise-OR of this and the other. |
||||
|
*/ |
||||
|
Long.prototype.or = function(other) { |
||||
|
return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-XOR of this Long and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Long} other the Long with which to XOR. |
||||
|
* @return {Long} the bitwise-XOR of this and the other. |
||||
|
*/ |
||||
|
Long.prototype.xor = function(other) { |
||||
|
return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Long with bits shifted to the left by the given amount. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Long} this shifted to the left by the given amount. |
||||
|
*/ |
||||
|
Long.prototype.shiftLeft = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var low = this.low_; |
||||
|
if (numBits < 32) { |
||||
|
var high = this.high_; |
||||
|
return Long.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); |
||||
|
} else { |
||||
|
return Long.fromBits(0, low << (numBits - 32)); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Long with bits shifted to the right by the given amount. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Long} this shifted to the right by the given amount. |
||||
|
*/ |
||||
|
Long.prototype.shiftRight = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var high = this.high_; |
||||
|
if (numBits < 32) { |
||||
|
var low = this.low_; |
||||
|
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); |
||||
|
} else { |
||||
|
return Long.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. |
||||
|
*/ |
||||
|
Long.prototype.shiftRightUnsigned = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var high = this.high_; |
||||
|
if (numBits < 32) { |
||||
|
var low = this.low_; |
||||
|
return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); |
||||
|
} else if (numBits === 32) { |
||||
|
return Long.fromBits(high, 0); |
||||
|
} else { |
||||
|
return Long.fromBits(high >>> (numBits - 32), 0); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Long representing the given (32-bit) integer value. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} value the 32-bit integer in question. |
||||
|
* @return {Long} the corresponding Long value. |
||||
|
*/ |
||||
|
Long.fromInt = function(value) { |
||||
|
if (-128 <= value && value < 128) { |
||||
|
var cachedObj = Long.INT_CACHE_[value]; |
||||
|
if (cachedObj) { |
||||
|
return cachedObj; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var obj = new Long(value | 0, value < 0 ? -1 : 0); |
||||
|
if (-128 <= value && value < 128) { |
||||
|
Long.INT_CACHE_[value] = obj; |
||||
|
} |
||||
|
return obj; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} value the number in question. |
||||
|
* @return {Long} the corresponding Long value. |
||||
|
*/ |
||||
|
Long.fromNumber = function(value) { |
||||
|
if (isNaN(value) || !isFinite(value)) { |
||||
|
return Long.ZERO; |
||||
|
} else if (value <= -Long.TWO_PWR_63_DBL_) { |
||||
|
return Long.MIN_VALUE; |
||||
|
} else if (value + 1 >= Long.TWO_PWR_63_DBL_) { |
||||
|
return Long.MAX_VALUE; |
||||
|
} else if (value < 0) { |
||||
|
return Long.fromNumber(-value).negate(); |
||||
|
} else { |
||||
|
return new Long((value % Long.TWO_PWR_32_DBL_) | 0, (value / Long.TWO_PWR_32_DBL_) | 0); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} lowBits the low 32-bits. |
||||
|
* @param {number} highBits the high 32-bits. |
||||
|
* @return {Long} the corresponding Long value. |
||||
|
*/ |
||||
|
Long.fromBits = function(lowBits, highBits) { |
||||
|
return new Long(lowBits, highBits); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Long representation of the given string, written using the given radix. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {string} str the textual representation of the Long. |
||||
|
* @param {number} opt_radix the radix in which the text is written. |
||||
|
* @return {Long} the corresponding Long value. |
||||
|
*/ |
||||
|
Long.fromString = function(str, opt_radix) { |
||||
|
if (str.length === 0) { |
||||
|
throw Error('number format error: empty string'); |
||||
|
} |
||||
|
|
||||
|
var radix = opt_radix || 10; |
||||
|
if (radix < 2 || 36 < radix) { |
||||
|
throw Error('radix out of range: ' + radix); |
||||
|
} |
||||
|
|
||||
|
if (str.charAt(0) === '-') { |
||||
|
return Long.fromString(str.substring(1), radix).negate(); |
||||
|
} else if (str.indexOf('-') >= 0) { |
||||
|
throw Error('number format error: interior "-" character: ' + str); |
||||
|
} |
||||
|
|
||||
|
// Do several (8) digits each time through the loop, so as to
|
||||
|
// minimize the calls to the very expensive emulated div.
|
||||
|
var radixToPower = Long.fromNumber(Math.pow(radix, 8)); |
||||
|
|
||||
|
var result = Long.ZERO; |
||||
|
for (var i = 0; i < str.length; i += 8) { |
||||
|
var size = Math.min(8, str.length - i); |
||||
|
var value = parseInt(str.substring(i, i + size), radix); |
||||
|
if (size < 8) { |
||||
|
var power = Long.fromNumber(Math.pow(radix, size)); |
||||
|
result = result.multiply(power).add(Long.fromNumber(value)); |
||||
|
} else { |
||||
|
result = result.multiply(radixToPower); |
||||
|
result = result.add(Long.fromNumber(value)); |
||||
|
} |
||||
|
} |
||||
|
return result; |
||||
|
}; |
||||
|
|
||||
|
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
|
// from* methods on which they depend.
|
||||
|
|
||||
|
/** |
||||
|
* A cache of the Long representations of small integer values. |
||||
|
* @type {Object} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.INT_CACHE_ = {}; |
||||
|
|
||||
|
// NOTE: the compiler should inline these constant values below and then remove
|
||||
|
// these variables, so there should be no runtime penalty for these.
|
||||
|
|
||||
|
/** |
||||
|
* Number used repeated below in calculations. This must appear before the |
||||
|
* first call to any from* function below. |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_16_DBL_ = 1 << 16; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_24_DBL_ = 1 << 24; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; |
||||
|
|
||||
|
/** @type {Long} */ |
||||
|
Long.ZERO = Long.fromInt(0); |
||||
|
|
||||
|
/** @type {Long} */ |
||||
|
Long.ONE = Long.fromInt(1); |
||||
|
|
||||
|
/** @type {Long} */ |
||||
|
Long.NEG_ONE = Long.fromInt(-1); |
||||
|
|
||||
|
/** @type {Long} */ |
||||
|
Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0); |
||||
|
|
||||
|
/** @type {Long} */ |
||||
|
Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); |
||||
|
|
||||
|
/** |
||||
|
* @type {Long} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Long.TWO_PWR_24_ = Long.fromInt(1 << 24); |
||||
|
|
||||
|
/** |
||||
|
* Expose. |
||||
|
*/ |
||||
|
module.exports = Long; |
||||
|
module.exports.Long = Long; |
@ -0,0 +1,128 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
// We have an ES6 Map available, return the native instance
|
||||
|
if (typeof global.Map !== 'undefined') { |
||||
|
module.exports = global.Map; |
||||
|
module.exports.Map = global.Map; |
||||
|
} else { |
||||
|
// We will return a polyfill
|
||||
|
var Map = function(array) { |
||||
|
this._keys = []; |
||||
|
this._values = {}; |
||||
|
|
||||
|
for (var i = 0; i < array.length; i++) { |
||||
|
if (array[i] == null) continue; // skip null and undefined
|
||||
|
var entry = array[i]; |
||||
|
var key = entry[0]; |
||||
|
var value = entry[1]; |
||||
|
// Add the key to the list of keys in order
|
||||
|
this._keys.push(key); |
||||
|
// Add the key and value to the values dictionary with a point
|
||||
|
// to the location in the ordered keys list
|
||||
|
this._values[key] = { v: value, i: this._keys.length - 1 }; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.clear = function() { |
||||
|
this._keys = []; |
||||
|
this._values = {}; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.delete = function(key) { |
||||
|
var value = this._values[key]; |
||||
|
if (value == null) return false; |
||||
|
// Delete entry
|
||||
|
delete this._values[key]; |
||||
|
// Remove the key from the ordered keys list
|
||||
|
this._keys.splice(value.i, 1); |
||||
|
return true; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.entries = function() { |
||||
|
var self = this; |
||||
|
var index = 0; |
||||
|
|
||||
|
return { |
||||
|
next: function() { |
||||
|
var key = self._keys[index++]; |
||||
|
return { |
||||
|
value: key !== undefined ? [key, self._values[key].v] : undefined, |
||||
|
done: key !== undefined ? false : true |
||||
|
}; |
||||
|
} |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.forEach = function(callback, self) { |
||||
|
self = self || this; |
||||
|
|
||||
|
for (var i = 0; i < this._keys.length; i++) { |
||||
|
var key = this._keys[i]; |
||||
|
// Call the forEach callback
|
||||
|
callback.call(self, this._values[key].v, key, self); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.get = function(key) { |
||||
|
return this._values[key] ? this._values[key].v : undefined; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.has = function(key) { |
||||
|
return this._values[key] != null; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.keys = function() { |
||||
|
var self = this; |
||||
|
var index = 0; |
||||
|
|
||||
|
return { |
||||
|
next: function() { |
||||
|
var key = self._keys[index++]; |
||||
|
return { |
||||
|
value: key !== undefined ? key : undefined, |
||||
|
done: key !== undefined ? false : true |
||||
|
}; |
||||
|
} |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.set = function(key, value) { |
||||
|
if (this._values[key]) { |
||||
|
this._values[key].v = value; |
||||
|
return this; |
||||
|
} |
||||
|
|
||||
|
// Add the key to the list of keys in order
|
||||
|
this._keys.push(key); |
||||
|
// Add the key and value to the values dictionary with a point
|
||||
|
// to the location in the ordered keys list
|
||||
|
this._values[key] = { v: value, i: this._keys.length - 1 }; |
||||
|
return this; |
||||
|
}; |
||||
|
|
||||
|
Map.prototype.values = function() { |
||||
|
var self = this; |
||||
|
var index = 0; |
||||
|
|
||||
|
return { |
||||
|
next: function() { |
||||
|
var key = self._keys[index++]; |
||||
|
return { |
||||
|
value: key !== undefined ? self._values[key].v : undefined, |
||||
|
done: key !== undefined ? false : true |
||||
|
}; |
||||
|
} |
||||
|
}; |
||||
|
}; |
||||
|
|
||||
|
// Last ismaster
|
||||
|
Object.defineProperty(Map.prototype, 'size', { |
||||
|
enumerable: true, |
||||
|
get: function() { |
||||
|
return this._keys.length; |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
module.exports = Map; |
||||
|
module.exports.Map = Map; |
||||
|
} |
@ -0,0 +1,14 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON MaxKey type. |
||||
|
* |
||||
|
* @class |
||||
|
* @return {MaxKey} A MaxKey instance |
||||
|
*/ |
||||
|
function MaxKey() { |
||||
|
if (!(this instanceof MaxKey)) return new MaxKey(); |
||||
|
|
||||
|
this._bsontype = 'MaxKey'; |
||||
|
} |
||||
|
|
||||
|
module.exports = MaxKey; |
||||
|
module.exports.MaxKey = MaxKey; |
@ -0,0 +1,14 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON MinKey type. |
||||
|
* |
||||
|
* @class |
||||
|
* @return {MinKey} A MinKey instance |
||||
|
*/ |
||||
|
function MinKey() { |
||||
|
if (!(this instanceof MinKey)) return new MinKey(); |
||||
|
|
||||
|
this._bsontype = 'MinKey'; |
||||
|
} |
||||
|
|
||||
|
module.exports = MinKey; |
||||
|
module.exports.MinKey = MinKey; |
@ -0,0 +1,389 @@ |
|||||
|
// Custom inspect property name / symbol.
|
||||
|
var inspect = 'inspect'; |
||||
|
|
||||
|
var utils = require('./parser/utils'); |
||||
|
|
||||
|
/** |
||||
|
* Machine id. |
||||
|
* |
||||
|
* Create a random 3-byte value (i.e. unique for this |
||||
|
* process). Other drivers use a md5 of the machine id here, but |
||||
|
* that would mean an asyc call to gethostname, so we don't bother. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
var MACHINE_ID = parseInt(Math.random() * 0xffffff, 10); |
||||
|
|
||||
|
// Regular expression that checks for hex value
|
||||
|
var checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); |
||||
|
|
||||
|
// Check if buffer exists
|
||||
|
try { |
||||
|
if (Buffer && Buffer.from) { |
||||
|
var hasBufferType = true; |
||||
|
inspect = require('util').inspect.custom || 'inspect'; |
||||
|
} |
||||
|
} catch (err) { |
||||
|
hasBufferType = false; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Create a new ObjectID instance |
||||
|
* |
||||
|
* @class |
||||
|
* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. |
||||
|
* @property {number} generationTime The generation time of this ObjectId instance |
||||
|
* @return {ObjectID} instance of ObjectID. |
||||
|
*/ |
||||
|
var ObjectID = function ObjectID(id) { |
||||
|
// Duck-typing to support ObjectId from different npm packages
|
||||
|
if (id instanceof ObjectID) return id; |
||||
|
if (!(this instanceof ObjectID)) return new ObjectID(id); |
||||
|
|
||||
|
this._bsontype = 'ObjectID'; |
||||
|
|
||||
|
// The most common usecase (blank id, new objectId instance)
|
||||
|
if (id == null || typeof id === 'number') { |
||||
|
// Generate a new id
|
||||
|
this.id = this.generate(id); |
||||
|
// If we are caching the hex string
|
||||
|
if (ObjectID.cacheHexString) this.__id = this.toString('hex'); |
||||
|
// Return the object
|
||||
|
return; |
||||
|
} |
||||
|
|
||||
|
// Check if the passed in id is valid
|
||||
|
var valid = ObjectID.isValid(id); |
||||
|
|
||||
|
// Throw an error if it's not a valid setup
|
||||
|
if (!valid && id != null) { |
||||
|
throw new Error( |
||||
|
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' |
||||
|
); |
||||
|
} else if (valid && typeof id === 'string' && id.length === 24 && hasBufferType) { |
||||
|
return new ObjectID(utils.toBuffer(id, 'hex')); |
||||
|
} else if (valid && typeof id === 'string' && id.length === 24) { |
||||
|
return ObjectID.createFromHexString(id); |
||||
|
} else if (id != null && id.length === 12) { |
||||
|
// assume 12 byte string
|
||||
|
this.id = id; |
||||
|
} else if (id != null && id.toHexString) { |
||||
|
// Duck-typing to support ObjectId from different npm packages
|
||||
|
return id; |
||||
|
} else { |
||||
|
throw new Error( |
||||
|
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
if (ObjectID.cacheHexString) this.__id = this.toString('hex'); |
||||
|
}; |
||||
|
|
||||
|
// Allow usage of ObjectId as well as ObjectID
|
||||
|
// var ObjectId = ObjectID;
|
||||
|
|
||||
|
// Precomputed hex table enables speedy hex string conversion
|
||||
|
var hexTable = []; |
||||
|
for (var i = 0; i < 256; i++) { |
||||
|
hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Return the ObjectID id as a 24 byte hex string representation |
||||
|
* |
||||
|
* @method |
||||
|
* @return {string} return the 24 byte hex string representation. |
||||
|
*/ |
||||
|
ObjectID.prototype.toHexString = function() { |
||||
|
if (ObjectID.cacheHexString && this.__id) return this.__id; |
||||
|
|
||||
|
var hexString = ''; |
||||
|
if (!this.id || !this.id.length) { |
||||
|
throw new Error( |
||||
|
'invalid ObjectId, ObjectId.id must be either a string or a Buffer, but is [' + |
||||
|
JSON.stringify(this.id) + |
||||
|
']' |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
if (this.id instanceof _Buffer) { |
||||
|
hexString = convertToHex(this.id); |
||||
|
if (ObjectID.cacheHexString) this.__id = hexString; |
||||
|
return hexString; |
||||
|
} |
||||
|
|
||||
|
for (var i = 0; i < this.id.length; i++) { |
||||
|
hexString += hexTable[this.id.charCodeAt(i)]; |
||||
|
} |
||||
|
|
||||
|
if (ObjectID.cacheHexString) this.__id = hexString; |
||||
|
return hexString; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Update the ObjectID index used in generating new ObjectID's on the driver |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} returns next index value. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.prototype.get_inc = function() { |
||||
|
return (ObjectID.index = (ObjectID.index + 1) % 0xffffff); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Update the ObjectID index used in generating new ObjectID's on the driver |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} returns next index value. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.prototype.getInc = function() { |
||||
|
return this.get_inc(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Generate a 12 byte id buffer used in ObjectID's |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} [time] optional parameter allowing to pass in a second based timestamp. |
||||
|
* @return {Buffer} return the 12 byte id buffer string. |
||||
|
*/ |
||||
|
ObjectID.prototype.generate = function(time) { |
||||
|
if ('number' !== typeof time) { |
||||
|
time = ~~(Date.now() / 1000); |
||||
|
} |
||||
|
|
||||
|
// Use pid
|
||||
|
var pid = |
||||
|
(typeof process === 'undefined' || process.pid === 1 |
||||
|
? Math.floor(Math.random() * 100000) |
||||
|
: process.pid) % 0xffff; |
||||
|
var inc = this.get_inc(); |
||||
|
// Buffer used
|
||||
|
var buffer = utils.allocBuffer(12); |
||||
|
// Encode time
|
||||
|
buffer[3] = time & 0xff; |
||||
|
buffer[2] = (time >> 8) & 0xff; |
||||
|
buffer[1] = (time >> 16) & 0xff; |
||||
|
buffer[0] = (time >> 24) & 0xff; |
||||
|
// Encode machine
|
||||
|
buffer[6] = MACHINE_ID & 0xff; |
||||
|
buffer[5] = (MACHINE_ID >> 8) & 0xff; |
||||
|
buffer[4] = (MACHINE_ID >> 16) & 0xff; |
||||
|
// Encode pid
|
||||
|
buffer[8] = pid & 0xff; |
||||
|
buffer[7] = (pid >> 8) & 0xff; |
||||
|
// Encode index
|
||||
|
buffer[11] = inc & 0xff; |
||||
|
buffer[10] = (inc >> 8) & 0xff; |
||||
|
buffer[9] = (inc >> 16) & 0xff; |
||||
|
// Return the buffer
|
||||
|
return buffer; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Converts the id into a 24 byte hex string for printing |
||||
|
* |
||||
|
* @param {String} format The Buffer toString format parameter. |
||||
|
* @return {String} return the 24 byte hex string representation. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.prototype.toString = function(format) { |
||||
|
// Is the id a buffer then use the buffer toString method to return the format
|
||||
|
if (this.id && this.id.copy) { |
||||
|
return this.id.toString(typeof format === 'string' ? format : 'hex'); |
||||
|
} |
||||
|
|
||||
|
// if(this.buffer )
|
||||
|
return this.toHexString(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Converts to a string representation of this Id. |
||||
|
* |
||||
|
* @return {String} return the 24 byte hex string representation. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.prototype[inspect] = ObjectID.prototype.toString; |
||||
|
|
||||
|
/** |
||||
|
* Converts to its JSON representation. |
||||
|
* |
||||
|
* @return {String} return the 24 byte hex string representation. |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.prototype.toJSON = function() { |
||||
|
return this.toHexString(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Compares the equality of this ObjectID with `otherID`. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {object} otherID ObjectID instance to compare against. |
||||
|
* @return {boolean} the result of comparing two ObjectID's |
||||
|
*/ |
||||
|
ObjectID.prototype.equals = function equals(otherId) { |
||||
|
// var id;
|
||||
|
|
||||
|
if (otherId instanceof ObjectID) { |
||||
|
return this.toString() === otherId.toString(); |
||||
|
} else if ( |
||||
|
typeof otherId === 'string' && |
||||
|
ObjectID.isValid(otherId) && |
||||
|
otherId.length === 12 && |
||||
|
this.id instanceof _Buffer |
||||
|
) { |
||||
|
return otherId === this.id.toString('binary'); |
||||
|
} else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 24) { |
||||
|
return otherId.toLowerCase() === this.toHexString(); |
||||
|
} else if (typeof otherId === 'string' && ObjectID.isValid(otherId) && otherId.length === 12) { |
||||
|
return otherId === this.id; |
||||
|
} else if (otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) { |
||||
|
return otherId.toHexString() === this.toHexString(); |
||||
|
} else { |
||||
|
return false; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the generation date (accurate up to the second) that this ID was generated. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {date} the generation date |
||||
|
*/ |
||||
|
ObjectID.prototype.getTimestamp = function() { |
||||
|
var timestamp = new Date(); |
||||
|
var time = this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); |
||||
|
timestamp.setTime(Math.floor(time) * 1000); |
||||
|
return timestamp; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.index = ~~(Math.random() * 0xffffff); |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
ObjectID.createPk = function createPk() { |
||||
|
return new ObjectID(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} time an integer number representing a number of seconds. |
||||
|
* @return {ObjectID} return the created ObjectID |
||||
|
*/ |
||||
|
ObjectID.createFromTime = function createFromTime(time) { |
||||
|
var buffer = utils.toBuffer([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); |
||||
|
// Encode time into first 4 bytes
|
||||
|
buffer[3] = time & 0xff; |
||||
|
buffer[2] = (time >> 8) & 0xff; |
||||
|
buffer[1] = (time >> 16) & 0xff; |
||||
|
buffer[0] = (time >> 24) & 0xff; |
||||
|
// Return the new objectId
|
||||
|
return new ObjectID(buffer); |
||||
|
}; |
||||
|
|
||||
|
// Lookup tables
|
||||
|
//var encodeLookup = '0123456789abcdef'.split('');
|
||||
|
var decodeLookup = []; |
||||
|
i = 0; |
||||
|
while (i < 10) decodeLookup[0x30 + i] = i++; |
||||
|
while (i < 16) decodeLookup[0x41 - 10 + i] = decodeLookup[0x61 - 10 + i] = i++; |
||||
|
|
||||
|
var _Buffer = Buffer; |
||||
|
var convertToHex = function(bytes) { |
||||
|
return bytes.toString('hex'); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Creates an ObjectID from a hex string representation of an ObjectID. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. |
||||
|
* @return {ObjectID} return the created ObjectID |
||||
|
*/ |
||||
|
ObjectID.createFromHexString = function createFromHexString(string) { |
||||
|
// Throw an error if it's not a valid setup
|
||||
|
if (typeof string === 'undefined' || (string != null && string.length !== 24)) { |
||||
|
throw new Error( |
||||
|
'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' |
||||
|
); |
||||
|
} |
||||
|
|
||||
|
// Use Buffer.from method if available
|
||||
|
if (hasBufferType) return new ObjectID(utils.toBuffer(string, 'hex')); |
||||
|
|
||||
|
// Calculate lengths
|
||||
|
var array = new _Buffer(12); |
||||
|
var n = 0; |
||||
|
var i = 0; |
||||
|
|
||||
|
while (i < 24) { |
||||
|
array[n++] = (decodeLookup[string.charCodeAt(i++)] << 4) | decodeLookup[string.charCodeAt(i++)]; |
||||
|
} |
||||
|
|
||||
|
return new ObjectID(array); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Checks if a value is a valid bson ObjectId |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. |
||||
|
*/ |
||||
|
ObjectID.isValid = function isValid(id) { |
||||
|
if (id == null) return false; |
||||
|
|
||||
|
if (typeof id === 'number') { |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
if (typeof id === 'string') { |
||||
|
return id.length === 12 || (id.length === 24 && checkForHexRegExp.test(id)); |
||||
|
} |
||||
|
|
||||
|
if (id instanceof ObjectID) { |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
if (id instanceof _Buffer) { |
||||
|
return true; |
||||
|
} |
||||
|
|
||||
|
// Duck-Typing detection of ObjectId like objects
|
||||
|
if (id.toHexString) { |
||||
|
return id.id.length === 12 || (id.id.length === 24 && checkForHexRegExp.test(id.id)); |
||||
|
} |
||||
|
|
||||
|
return false; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Object.defineProperty(ObjectID.prototype, 'generationTime', { |
||||
|
enumerable: true, |
||||
|
get: function() { |
||||
|
return this.id[3] | (this.id[2] << 8) | (this.id[1] << 16) | (this.id[0] << 24); |
||||
|
}, |
||||
|
set: function(value) { |
||||
|
// Encode time into first 4 bytes
|
||||
|
this.id[3] = value & 0xff; |
||||
|
this.id[2] = (value >> 8) & 0xff; |
||||
|
this.id[1] = (value >> 16) & 0xff; |
||||
|
this.id[0] = (value >> 24) & 0xff; |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
/** |
||||
|
* Expose. |
||||
|
*/ |
||||
|
module.exports = ObjectID; |
||||
|
module.exports.ObjectID = ObjectID; |
||||
|
module.exports.ObjectId = ObjectID; |
@ -0,0 +1,255 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
var Long = require('../long').Long, |
||||
|
Double = require('../double').Double, |
||||
|
Timestamp = require('../timestamp').Timestamp, |
||||
|
ObjectID = require('../objectid').ObjectID, |
||||
|
Symbol = require('../symbol').Symbol, |
||||
|
BSONRegExp = require('../regexp').BSONRegExp, |
||||
|
Code = require('../code').Code, |
||||
|
Decimal128 = require('../decimal128'), |
||||
|
MinKey = require('../min_key').MinKey, |
||||
|
MaxKey = require('../max_key').MaxKey, |
||||
|
DBRef = require('../db_ref').DBRef, |
||||
|
Binary = require('../binary').Binary; |
||||
|
|
||||
|
var normalizedFunctionString = require('./utils').normalizedFunctionString; |
||||
|
|
||||
|
// To ensure that 0.4 of node works correctly
|
||||
|
var isDate = function isDate(d) { |
||||
|
return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; |
||||
|
}; |
||||
|
|
||||
|
var calculateObjectSize = function calculateObjectSize( |
||||
|
object, |
||||
|
serializeFunctions, |
||||
|
ignoreUndefined |
||||
|
) { |
||||
|
var totalLength = 4 + 1; |
||||
|
|
||||
|
if (Array.isArray(object)) { |
||||
|
for (var i = 0; i < object.length; i++) { |
||||
|
totalLength += calculateElement( |
||||
|
i.toString(), |
||||
|
object[i], |
||||
|
serializeFunctions, |
||||
|
true, |
||||
|
ignoreUndefined |
||||
|
); |
||||
|
} |
||||
|
} else { |
||||
|
// If we have toBSON defined, override the current object
|
||||
|
if (object.toBSON) { |
||||
|
object = object.toBSON(); |
||||
|
} |
||||
|
|
||||
|
// Calculate size
|
||||
|
for (var key in object) { |
||||
|
totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return totalLength; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { |
||||
|
// If we have toBSON defined, override the current object
|
||||
|
if (value && value.toBSON) { |
||||
|
value = value.toBSON(); |
||||
|
} |
||||
|
|
||||
|
switch (typeof value) { |
||||
|
case 'string': |
||||
|
return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; |
||||
|
case 'number': |
||||
|
if (Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { |
||||
|
if (value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { |
||||
|
// 32 bit
|
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (4 + 1); |
||||
|
} else { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); |
||||
|
} |
||||
|
} else { |
||||
|
// 64 bit
|
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); |
||||
|
} |
||||
|
case 'undefined': |
||||
|
if (isArray || !ignoreUndefined) |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; |
||||
|
return 0; |
||||
|
case 'boolean': |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 1); |
||||
|
case 'object': |
||||
|
if ( |
||||
|
value == null || |
||||
|
value instanceof MinKey || |
||||
|
value instanceof MaxKey || |
||||
|
value['_bsontype'] === 'MinKey' || |
||||
|
value['_bsontype'] === 'MaxKey' |
||||
|
) { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + 1; |
||||
|
} else if (value instanceof ObjectID || value['_bsontype'] === 'ObjectID' || value['_bsontype'] === 'ObjectId') { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (12 + 1); |
||||
|
} else if (value instanceof Date || isDate(value)) { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); |
||||
|
} else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (1 + 4 + 1) + value.length |
||||
|
); |
||||
|
} else if ( |
||||
|
value instanceof Long || |
||||
|
value instanceof Double || |
||||
|
value instanceof Timestamp || |
||||
|
value['_bsontype'] === 'Long' || |
||||
|
value['_bsontype'] === 'Double' || |
||||
|
value['_bsontype'] === 'Timestamp' |
||||
|
) { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (8 + 1); |
||||
|
} else if (value instanceof Decimal128 || value['_bsontype'] === 'Decimal128') { |
||||
|
return (name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (16 + 1); |
||||
|
} else if (value instanceof Code || value['_bsontype'] === 'Code') { |
||||
|
// Calculate size depending on the availability of a scope
|
||||
|
if (value.scope != null && Object.keys(value.scope).length > 0) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
4 + |
||||
|
4 + |
||||
|
Buffer.byteLength(value.code.toString(), 'utf8') + |
||||
|
1 + |
||||
|
calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) |
||||
|
); |
||||
|
} else { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
4 + |
||||
|
Buffer.byteLength(value.code.toString(), 'utf8') + |
||||
|
1 |
||||
|
); |
||||
|
} |
||||
|
} else if (value instanceof Binary || value['_bsontype'] === 'Binary') { |
||||
|
// Check what kind of subtype we have
|
||||
|
if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
(value.position + 1 + 4 + 1 + 4) |
||||
|
); |
||||
|
} else { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + (value.position + 1 + 4 + 1) |
||||
|
); |
||||
|
} |
||||
|
} else if (value instanceof Symbol || value['_bsontype'] === 'Symbol') { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
Buffer.byteLength(value.value, 'utf8') + |
||||
|
4 + |
||||
|
1 + |
||||
|
1 |
||||
|
); |
||||
|
} else if (value instanceof DBRef || value['_bsontype'] === 'DBRef') { |
||||
|
// Set up correct object for serialization
|
||||
|
var ordered_values = { |
||||
|
$ref: value.namespace, |
||||
|
$id: value.oid |
||||
|
}; |
||||
|
|
||||
|
// Add db reference if it exists
|
||||
|
if (null != value.db) { |
||||
|
ordered_values['$db'] = value.db; |
||||
|
} |
||||
|
|
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) |
||||
|
); |
||||
|
} else if ( |
||||
|
value instanceof RegExp || |
||||
|
Object.prototype.toString.call(value) === '[object RegExp]' |
||||
|
) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
Buffer.byteLength(value.source, 'utf8') + |
||||
|
1 + |
||||
|
(value.global ? 1 : 0) + |
||||
|
(value.ignoreCase ? 1 : 0) + |
||||
|
(value.multiline ? 1 : 0) + |
||||
|
1 |
||||
|
); |
||||
|
} else if (value instanceof BSONRegExp || value['_bsontype'] === 'BSONRegExp') { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
Buffer.byteLength(value.pattern, 'utf8') + |
||||
|
1 + |
||||
|
Buffer.byteLength(value.options, 'utf8') + |
||||
|
1 |
||||
|
); |
||||
|
} else { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
calculateObjectSize(value, serializeFunctions, ignoreUndefined) + |
||||
|
1 |
||||
|
); |
||||
|
} |
||||
|
case 'function': |
||||
|
// WTF for 0.4.X where typeof /someregexp/ === 'function'
|
||||
|
if ( |
||||
|
value instanceof RegExp || |
||||
|
Object.prototype.toString.call(value) === '[object RegExp]' || |
||||
|
String.call(value) === '[object RegExp]' |
||||
|
) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
Buffer.byteLength(value.source, 'utf8') + |
||||
|
1 + |
||||
|
(value.global ? 1 : 0) + |
||||
|
(value.ignoreCase ? 1 : 0) + |
||||
|
(value.multiline ? 1 : 0) + |
||||
|
1 |
||||
|
); |
||||
|
} else { |
||||
|
if (serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
4 + |
||||
|
4 + |
||||
|
Buffer.byteLength(normalizedFunctionString(value), 'utf8') + |
||||
|
1 + |
||||
|
calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) |
||||
|
); |
||||
|
} else if (serializeFunctions) { |
||||
|
return ( |
||||
|
(name != null ? Buffer.byteLength(name, 'utf8') + 1 : 0) + |
||||
|
1 + |
||||
|
4 + |
||||
|
Buffer.byteLength(normalizedFunctionString(value), 'utf8') + |
||||
|
1 |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
return 0; |
||||
|
} |
||||
|
|
||||
|
var BSON = {}; |
||||
|
|
||||
|
// BSON MAX VALUES
|
||||
|
BSON.BSON_INT32_MAX = 0x7fffffff; |
||||
|
BSON.BSON_INT32_MIN = -0x80000000; |
||||
|
|
||||
|
// JS MAX PRECISE VALUES
|
||||
|
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
module.exports = calculateObjectSize; |
@ -0,0 +1,782 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
var Long = require('../long').Long, |
||||
|
Double = require('../double').Double, |
||||
|
Timestamp = require('../timestamp').Timestamp, |
||||
|
ObjectID = require('../objectid').ObjectID, |
||||
|
Symbol = require('../symbol').Symbol, |
||||
|
Code = require('../code').Code, |
||||
|
MinKey = require('../min_key').MinKey, |
||||
|
MaxKey = require('../max_key').MaxKey, |
||||
|
Decimal128 = require('../decimal128'), |
||||
|
Int32 = require('../int_32'), |
||||
|
DBRef = require('../db_ref').DBRef, |
||||
|
BSONRegExp = require('../regexp').BSONRegExp, |
||||
|
Binary = require('../binary').Binary; |
||||
|
|
||||
|
var utils = require('./utils'); |
||||
|
|
||||
|
var deserialize = function(buffer, options, isArray) { |
||||
|
options = options == null ? {} : options; |
||||
|
var index = options && options.index ? options.index : 0; |
||||
|
// Read the document size
|
||||
|
var size = |
||||
|
buffer[index] | |
||||
|
(buffer[index + 1] << 8) | |
||||
|
(buffer[index + 2] << 16) | |
||||
|
(buffer[index + 3] << 24); |
||||
|
|
||||
|
// Ensure buffer is valid size
|
||||
|
if (size < 5 || buffer.length < size || size + index > buffer.length) { |
||||
|
throw new Error('corrupt bson message'); |
||||
|
} |
||||
|
|
||||
|
// Illegal end value
|
||||
|
if (buffer[index + size - 1] !== 0) { |
||||
|
throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); |
||||
|
} |
||||
|
|
||||
|
// Start deserializtion
|
||||
|
return deserializeObject(buffer, index, options, isArray); |
||||
|
}; |
||||
|
|
||||
|
var deserializeObject = function(buffer, index, options, isArray) { |
||||
|
var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; |
||||
|
var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; |
||||
|
var cacheFunctionsCrc32 = |
||||
|
options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; |
||||
|
|
||||
|
if (!cacheFunctionsCrc32) var crc32 = null; |
||||
|
|
||||
|
var fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; |
||||
|
|
||||
|
// Return raw bson buffer instead of parsing it
|
||||
|
var raw = options['raw'] == null ? false : options['raw']; |
||||
|
|
||||
|
// Return BSONRegExp objects instead of native regular expressions
|
||||
|
var bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; |
||||
|
|
||||
|
// Controls the promotion of values vs wrapper classes
|
||||
|
var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers']; |
||||
|
var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; |
||||
|
var promoteValues = options['promoteValues'] == null ? true : options['promoteValues']; |
||||
|
|
||||
|
// Set the start index
|
||||
|
var startIndex = index; |
||||
|
|
||||
|
// Validate that we have at least 4 bytes of buffer
|
||||
|
if (buffer.length < 5) throw new Error('corrupt bson message < 5 bytes long'); |
||||
|
|
||||
|
// Read the document size
|
||||
|
var size = |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); |
||||
|
|
||||
|
// Ensure buffer is valid size
|
||||
|
if (size < 5 || size > buffer.length) throw new Error('corrupt bson message'); |
||||
|
|
||||
|
// Create holding object
|
||||
|
var object = isArray ? [] : {}; |
||||
|
// Used for arrays to skip having to perform utf8 decoding
|
||||
|
var arrayIndex = 0; |
||||
|
|
||||
|
var done = false; |
||||
|
|
||||
|
// While we have more left data left keep parsing
|
||||
|
// while (buffer[index + 1] !== 0) {
|
||||
|
while (!done) { |
||||
|
// Read the type
|
||||
|
var elementType = buffer[index++]; |
||||
|
// If we get a zero it's the last byte, exit
|
||||
|
if (elementType === 0) break; |
||||
|
|
||||
|
// Get the start search index
|
||||
|
var i = index; |
||||
|
// Locate the end of the c string
|
||||
|
while (buffer[i] !== 0x00 && i < buffer.length) { |
||||
|
i++; |
||||
|
} |
||||
|
|
||||
|
// If are at the end of the buffer there is a problem with the document
|
||||
|
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); |
||||
|
var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i); |
||||
|
|
||||
|
index = i + 1; |
||||
|
|
||||
|
if (elementType === BSON.BSON_DATA_STRING) { |
||||
|
var stringSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
if ( |
||||
|
stringSize <= 0 || |
||||
|
stringSize > buffer.length - index || |
||||
|
buffer[index + stringSize - 1] !== 0 |
||||
|
) |
||||
|
throw new Error('bad string length in bson'); |
||||
|
object[name] = buffer.toString('utf8', index, index + stringSize - 1); |
||||
|
index = index + stringSize; |
||||
|
} else if (elementType === BSON.BSON_DATA_OID) { |
||||
|
var oid = utils.allocBuffer(12); |
||||
|
buffer.copy(oid, 0, index, index + 12); |
||||
|
object[name] = new ObjectID(oid); |
||||
|
index = index + 12; |
||||
|
} else if (elementType === BSON.BSON_DATA_INT && promoteValues === false) { |
||||
|
object[name] = new Int32( |
||||
|
buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24) |
||||
|
); |
||||
|
} else if (elementType === BSON.BSON_DATA_INT) { |
||||
|
object[name] = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
} else if (elementType === BSON.BSON_DATA_NUMBER && promoteValues === false) { |
||||
|
object[name] = new Double(buffer.readDoubleLE(index)); |
||||
|
index = index + 8; |
||||
|
} else if (elementType === BSON.BSON_DATA_NUMBER) { |
||||
|
object[name] = buffer.readDoubleLE(index); |
||||
|
index = index + 8; |
||||
|
} else if (elementType === BSON.BSON_DATA_DATE) { |
||||
|
var lowBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
var highBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
object[name] = new Date(new Long(lowBits, highBits).toNumber()); |
||||
|
} else if (elementType === BSON.BSON_DATA_BOOLEAN) { |
||||
|
if (buffer[index] !== 0 && buffer[index] !== 1) throw new Error('illegal boolean type value'); |
||||
|
object[name] = buffer[index++] === 1; |
||||
|
} else if (elementType === BSON.BSON_DATA_OBJECT) { |
||||
|
var _index = index; |
||||
|
var objectSize = |
||||
|
buffer[index] | |
||||
|
(buffer[index + 1] << 8) | |
||||
|
(buffer[index + 2] << 16) | |
||||
|
(buffer[index + 3] << 24); |
||||
|
if (objectSize <= 0 || objectSize > buffer.length - index) |
||||
|
throw new Error('bad embedded document length in bson'); |
||||
|
|
||||
|
// We have a raw value
|
||||
|
if (raw) { |
||||
|
object[name] = buffer.slice(index, index + objectSize); |
||||
|
} else { |
||||
|
object[name] = deserializeObject(buffer, _index, options, false); |
||||
|
} |
||||
|
|
||||
|
index = index + objectSize; |
||||
|
} else if (elementType === BSON.BSON_DATA_ARRAY) { |
||||
|
_index = index; |
||||
|
objectSize = |
||||
|
buffer[index] | |
||||
|
(buffer[index + 1] << 8) | |
||||
|
(buffer[index + 2] << 16) | |
||||
|
(buffer[index + 3] << 24); |
||||
|
var arrayOptions = options; |
||||
|
|
||||
|
// Stop index
|
||||
|
var stopIndex = index + objectSize; |
||||
|
|
||||
|
// All elements of array to be returned as raw bson
|
||||
|
if (fieldsAsRaw && fieldsAsRaw[name]) { |
||||
|
arrayOptions = {}; |
||||
|
for (var n in options) arrayOptions[n] = options[n]; |
||||
|
arrayOptions['raw'] = true; |
||||
|
} |
||||
|
|
||||
|
object[name] = deserializeObject(buffer, _index, arrayOptions, true); |
||||
|
index = index + objectSize; |
||||
|
|
||||
|
if (buffer[index - 1] !== 0) throw new Error('invalid array terminator byte'); |
||||
|
if (index !== stopIndex) throw new Error('corrupted array bson'); |
||||
|
} else if (elementType === BSON.BSON_DATA_UNDEFINED) { |
||||
|
object[name] = undefined; |
||||
|
} else if (elementType === BSON.BSON_DATA_NULL) { |
||||
|
object[name] = null; |
||||
|
} else if (elementType === BSON.BSON_DATA_LONG) { |
||||
|
// Unpack the low and high bits
|
||||
|
lowBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
highBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
var long = new Long(lowBits, highBits); |
||||
|
// Promote the long if possible
|
||||
|
if (promoteLongs && promoteValues === true) { |
||||
|
object[name] = |
||||
|
long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) |
||||
|
? long.toNumber() |
||||
|
: long; |
||||
|
} else { |
||||
|
object[name] = long; |
||||
|
} |
||||
|
} else if (elementType === BSON.BSON_DATA_DECIMAL128) { |
||||
|
// Buffer to contain the decimal bytes
|
||||
|
var bytes = utils.allocBuffer(16); |
||||
|
// Copy the next 16 bytes into the bytes buffer
|
||||
|
buffer.copy(bytes, 0, index, index + 16); |
||||
|
// Update index
|
||||
|
index = index + 16; |
||||
|
// Assign the new Decimal128 value
|
||||
|
var decimal128 = new Decimal128(bytes); |
||||
|
// If we have an alternative mapper use that
|
||||
|
object[name] = decimal128.toObject ? decimal128.toObject() : decimal128; |
||||
|
} else if (elementType === BSON.BSON_DATA_BINARY) { |
||||
|
var binarySize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
var totalBinarySize = binarySize; |
||||
|
var subType = buffer[index++]; |
||||
|
|
||||
|
// Did we have a negative binary size, throw
|
||||
|
if (binarySize < 0) throw new Error('Negative binary type element size found'); |
||||
|
|
||||
|
// Is the length longer than the document
|
||||
|
if (binarySize > buffer.length) throw new Error('Binary type size larger than document size'); |
||||
|
|
||||
|
// Decode as raw Buffer object if options specifies it
|
||||
|
if (buffer['slice'] != null) { |
||||
|
// If we have subtype 2 skip the 4 bytes for the size
|
||||
|
if (subType === Binary.SUBTYPE_BYTE_ARRAY) { |
||||
|
binarySize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
if (binarySize < 0) |
||||
|
throw new Error('Negative binary type element size found for subtype 0x02'); |
||||
|
if (binarySize > totalBinarySize - 4) |
||||
|
throw new Error('Binary type with subtype 0x02 contains to long binary size'); |
||||
|
if (binarySize < totalBinarySize - 4) |
||||
|
throw new Error('Binary type with subtype 0x02 contains to short binary size'); |
||||
|
} |
||||
|
|
||||
|
if (promoteBuffers && promoteValues) { |
||||
|
object[name] = buffer.slice(index, index + binarySize); |
||||
|
} else { |
||||
|
object[name] = new Binary(buffer.slice(index, index + binarySize), subType); |
||||
|
} |
||||
|
} else { |
||||
|
var _buffer = |
||||
|
typeof Uint8Array !== 'undefined' |
||||
|
? new Uint8Array(new ArrayBuffer(binarySize)) |
||||
|
: new Array(binarySize); |
||||
|
// If we have subtype 2 skip the 4 bytes for the size
|
||||
|
if (subType === Binary.SUBTYPE_BYTE_ARRAY) { |
||||
|
binarySize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
if (binarySize < 0) |
||||
|
throw new Error('Negative binary type element size found for subtype 0x02'); |
||||
|
if (binarySize > totalBinarySize - 4) |
||||
|
throw new Error('Binary type with subtype 0x02 contains to long binary size'); |
||||
|
if (binarySize < totalBinarySize - 4) |
||||
|
throw new Error('Binary type with subtype 0x02 contains to short binary size'); |
||||
|
} |
||||
|
|
||||
|
// Copy the data
|
||||
|
for (i = 0; i < binarySize; i++) { |
||||
|
_buffer[i] = buffer[index + i]; |
||||
|
} |
||||
|
|
||||
|
if (promoteBuffers && promoteValues) { |
||||
|
object[name] = _buffer; |
||||
|
} else { |
||||
|
object[name] = new Binary(_buffer, subType); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Update the index
|
||||
|
index = index + binarySize; |
||||
|
} else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === false) { |
||||
|
// Get the start search index
|
||||
|
i = index; |
||||
|
// Locate the end of the c string
|
||||
|
while (buffer[i] !== 0x00 && i < buffer.length) { |
||||
|
i++; |
||||
|
} |
||||
|
// If are at the end of the buffer there is a problem with the document
|
||||
|
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); |
||||
|
// Return the C string
|
||||
|
var source = buffer.toString('utf8', index, i); |
||||
|
// Create the regexp
|
||||
|
index = i + 1; |
||||
|
|
||||
|
// Get the start search index
|
||||
|
i = index; |
||||
|
// Locate the end of the c string
|
||||
|
while (buffer[i] !== 0x00 && i < buffer.length) { |
||||
|
i++; |
||||
|
} |
||||
|
// If are at the end of the buffer there is a problem with the document
|
||||
|
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); |
||||
|
// Return the C string
|
||||
|
var regExpOptions = buffer.toString('utf8', index, i); |
||||
|
index = i + 1; |
||||
|
|
||||
|
// For each option add the corresponding one for javascript
|
||||
|
var optionsArray = new Array(regExpOptions.length); |
||||
|
|
||||
|
// Parse options
|
||||
|
for (i = 0; i < regExpOptions.length; i++) { |
||||
|
switch (regExpOptions[i]) { |
||||
|
case 'm': |
||||
|
optionsArray[i] = 'm'; |
||||
|
break; |
||||
|
case 's': |
||||
|
optionsArray[i] = 'g'; |
||||
|
break; |
||||
|
case 'i': |
||||
|
optionsArray[i] = 'i'; |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
object[name] = new RegExp(source, optionsArray.join('')); |
||||
|
} else if (elementType === BSON.BSON_DATA_REGEXP && bsonRegExp === true) { |
||||
|
// Get the start search index
|
||||
|
i = index; |
||||
|
// Locate the end of the c string
|
||||
|
while (buffer[i] !== 0x00 && i < buffer.length) { |
||||
|
i++; |
||||
|
} |
||||
|
// If are at the end of the buffer there is a problem with the document
|
||||
|
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); |
||||
|
// Return the C string
|
||||
|
source = buffer.toString('utf8', index, i); |
||||
|
index = i + 1; |
||||
|
|
||||
|
// Get the start search index
|
||||
|
i = index; |
||||
|
// Locate the end of the c string
|
||||
|
while (buffer[i] !== 0x00 && i < buffer.length) { |
||||
|
i++; |
||||
|
} |
||||
|
// If are at the end of the buffer there is a problem with the document
|
||||
|
if (i >= buffer.length) throw new Error('Bad BSON Document: illegal CString'); |
||||
|
// Return the C string
|
||||
|
regExpOptions = buffer.toString('utf8', index, i); |
||||
|
index = i + 1; |
||||
|
|
||||
|
// Set the object
|
||||
|
object[name] = new BSONRegExp(source, regExpOptions); |
||||
|
} else if (elementType === BSON.BSON_DATA_SYMBOL) { |
||||
|
stringSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
if ( |
||||
|
stringSize <= 0 || |
||||
|
stringSize > buffer.length - index || |
||||
|
buffer[index + stringSize - 1] !== 0 |
||||
|
) |
||||
|
throw new Error('bad string length in bson'); |
||||
|
object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); |
||||
|
index = index + stringSize; |
||||
|
} else if (elementType === BSON.BSON_DATA_TIMESTAMP) { |
||||
|
lowBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
highBits = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
object[name] = new Timestamp(lowBits, highBits); |
||||
|
} else if (elementType === BSON.BSON_DATA_MIN_KEY) { |
||||
|
object[name] = new MinKey(); |
||||
|
} else if (elementType === BSON.BSON_DATA_MAX_KEY) { |
||||
|
object[name] = new MaxKey(); |
||||
|
} else if (elementType === BSON.BSON_DATA_CODE) { |
||||
|
stringSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
if ( |
||||
|
stringSize <= 0 || |
||||
|
stringSize > buffer.length - index || |
||||
|
buffer[index + stringSize - 1] !== 0 |
||||
|
) |
||||
|
throw new Error('bad string length in bson'); |
||||
|
var functionString = buffer.toString('utf8', index, index + stringSize - 1); |
||||
|
|
||||
|
// If we are evaluating the functions
|
||||
|
if (evalFunctions) { |
||||
|
// If we have cache enabled let's look for the md5 of the function in the cache
|
||||
|
if (cacheFunctions) { |
||||
|
var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; |
||||
|
// Got to do this to avoid V8 deoptimizing the call due to finding eval
|
||||
|
object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); |
||||
|
} else { |
||||
|
object[name] = isolateEval(functionString); |
||||
|
} |
||||
|
} else { |
||||
|
object[name] = new Code(functionString); |
||||
|
} |
||||
|
|
||||
|
// Update parse index position
|
||||
|
index = index + stringSize; |
||||
|
} else if (elementType === BSON.BSON_DATA_CODE_W_SCOPE) { |
||||
|
var totalSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
|
||||
|
// Element cannot be shorter than totalSize + stringSize + documentSize + terminator
|
||||
|
if (totalSize < 4 + 4 + 4 + 1) { |
||||
|
throw new Error('code_w_scope total size shorter minimum expected length'); |
||||
|
} |
||||
|
|
||||
|
// Get the code string size
|
||||
|
stringSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
// Check if we have a valid string
|
||||
|
if ( |
||||
|
stringSize <= 0 || |
||||
|
stringSize > buffer.length - index || |
||||
|
buffer[index + stringSize - 1] !== 0 |
||||
|
) |
||||
|
throw new Error('bad string length in bson'); |
||||
|
|
||||
|
// Javascript function
|
||||
|
functionString = buffer.toString('utf8', index, index + stringSize - 1); |
||||
|
// Update parse index position
|
||||
|
index = index + stringSize; |
||||
|
// Parse the element
|
||||
|
_index = index; |
||||
|
// Decode the size of the object document
|
||||
|
objectSize = |
||||
|
buffer[index] | |
||||
|
(buffer[index + 1] << 8) | |
||||
|
(buffer[index + 2] << 16) | |
||||
|
(buffer[index + 3] << 24); |
||||
|
// Decode the scope object
|
||||
|
var scopeObject = deserializeObject(buffer, _index, options, false); |
||||
|
// Adjust the index
|
||||
|
index = index + objectSize; |
||||
|
|
||||
|
// Check if field length is to short
|
||||
|
if (totalSize < 4 + 4 + objectSize + stringSize) { |
||||
|
throw new Error('code_w_scope total size is to short, truncating scope'); |
||||
|
} |
||||
|
|
||||
|
// Check if totalSize field is to long
|
||||
|
if (totalSize > 4 + 4 + objectSize + stringSize) { |
||||
|
throw new Error('code_w_scope total size is to long, clips outer document'); |
||||
|
} |
||||
|
|
||||
|
// If we are evaluating the functions
|
||||
|
if (evalFunctions) { |
||||
|
// If we have cache enabled let's look for the md5 of the function in the cache
|
||||
|
if (cacheFunctions) { |
||||
|
hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; |
||||
|
// Got to do this to avoid V8 deoptimizing the call due to finding eval
|
||||
|
object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); |
||||
|
} else { |
||||
|
object[name] = isolateEval(functionString); |
||||
|
} |
||||
|
|
||||
|
object[name].scope = scopeObject; |
||||
|
} else { |
||||
|
object[name] = new Code(functionString, scopeObject); |
||||
|
} |
||||
|
} else if (elementType === BSON.BSON_DATA_DBPOINTER) { |
||||
|
// Get the code string size
|
||||
|
stringSize = |
||||
|
buffer[index++] | |
||||
|
(buffer[index++] << 8) | |
||||
|
(buffer[index++] << 16) | |
||||
|
(buffer[index++] << 24); |
||||
|
// Check if we have a valid string
|
||||
|
if ( |
||||
|
stringSize <= 0 || |
||||
|
stringSize > buffer.length - index || |
||||
|
buffer[index + stringSize - 1] !== 0 |
||||
|
) |
||||
|
throw new Error('bad string length in bson'); |
||||
|
// Namespace
|
||||
|
var namespace = buffer.toString('utf8', index, index + stringSize - 1); |
||||
|
// Update parse index position
|
||||
|
index = index + stringSize; |
||||
|
|
||||
|
// Read the oid
|
||||
|
var oidBuffer = utils.allocBuffer(12); |
||||
|
buffer.copy(oidBuffer, 0, index, index + 12); |
||||
|
oid = new ObjectID(oidBuffer); |
||||
|
|
||||
|
// Update the index
|
||||
|
index = index + 12; |
||||
|
|
||||
|
// Split the namespace
|
||||
|
var parts = namespace.split('.'); |
||||
|
var db = parts.shift(); |
||||
|
var collection = parts.join('.'); |
||||
|
// Upgrade to DBRef type
|
||||
|
object[name] = new DBRef(collection, oid, db); |
||||
|
} else { |
||||
|
throw new Error( |
||||
|
'Detected unknown BSON type ' + |
||||
|
elementType.toString(16) + |
||||
|
' for fieldname "' + |
||||
|
name + |
||||
|
'", are you using the latest BSON parser' |
||||
|
); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Check if the deserialization was against a valid array/object
|
||||
|
if (size !== index - startIndex) { |
||||
|
if (isArray) throw new Error('corrupt array bson'); |
||||
|
throw new Error('corrupt object bson'); |
||||
|
} |
||||
|
|
||||
|
// Check if we have a db ref object
|
||||
|
if (object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); |
||||
|
return object; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Ensure eval is isolated. |
||||
|
* |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
var isolateEvalWithHash = function(functionCache, hash, functionString, object) { |
||||
|
// Contains the value we are going to set
|
||||
|
var value = null; |
||||
|
|
||||
|
// Check for cache hit, eval if missing and return cached function
|
||||
|
if (functionCache[hash] == null) { |
||||
|
eval('value = ' + functionString); |
||||
|
functionCache[hash] = value; |
||||
|
} |
||||
|
// Set the object
|
||||
|
return functionCache[hash].bind(object); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Ensure eval is isolated. |
||||
|
* |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
var isolateEval = function(functionString) { |
||||
|
// Contains the value we are going to set
|
||||
|
var value = null; |
||||
|
// Eval the function
|
||||
|
eval('value = ' + functionString); |
||||
|
return value; |
||||
|
}; |
||||
|
|
||||
|
var BSON = {}; |
||||
|
|
||||
|
/** |
||||
|
* Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 |
||||
|
* |
||||
|
* @ignore |
||||
|
* @api private |
||||
|
*/ |
||||
|
var functionCache = (BSON.functionCache = {}); |
||||
|
|
||||
|
/** |
||||
|
* Number BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_NUMBER |
||||
|
**/ |
||||
|
BSON.BSON_DATA_NUMBER = 1; |
||||
|
/** |
||||
|
* String BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_STRING |
||||
|
**/ |
||||
|
BSON.BSON_DATA_STRING = 2; |
||||
|
/** |
||||
|
* Object BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_OBJECT |
||||
|
**/ |
||||
|
BSON.BSON_DATA_OBJECT = 3; |
||||
|
/** |
||||
|
* Array BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_ARRAY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_ARRAY = 4; |
||||
|
/** |
||||
|
* Binary BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_BINARY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_BINARY = 5; |
||||
|
/** |
||||
|
* Binary BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_UNDEFINED |
||||
|
**/ |
||||
|
BSON.BSON_DATA_UNDEFINED = 6; |
||||
|
/** |
||||
|
* ObjectID BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_OID |
||||
|
**/ |
||||
|
BSON.BSON_DATA_OID = 7; |
||||
|
/** |
||||
|
* Boolean BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_BOOLEAN |
||||
|
**/ |
||||
|
BSON.BSON_DATA_BOOLEAN = 8; |
||||
|
/** |
||||
|
* Date BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_DATE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_DATE = 9; |
||||
|
/** |
||||
|
* null BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_NULL |
||||
|
**/ |
||||
|
BSON.BSON_DATA_NULL = 10; |
||||
|
/** |
||||
|
* RegExp BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_REGEXP |
||||
|
**/ |
||||
|
BSON.BSON_DATA_REGEXP = 11; |
||||
|
/** |
||||
|
* Code BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_DBPOINTER |
||||
|
**/ |
||||
|
BSON.BSON_DATA_DBPOINTER = 12; |
||||
|
/** |
||||
|
* Code BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_CODE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_CODE = 13; |
||||
|
/** |
||||
|
* Symbol BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_SYMBOL |
||||
|
**/ |
||||
|
BSON.BSON_DATA_SYMBOL = 14; |
||||
|
/** |
||||
|
* Code with Scope BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_CODE_W_SCOPE |
||||
|
**/ |
||||
|
BSON.BSON_DATA_CODE_W_SCOPE = 15; |
||||
|
/** |
||||
|
* 32 bit Integer BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_INT |
||||
|
**/ |
||||
|
BSON.BSON_DATA_INT = 16; |
||||
|
/** |
||||
|
* Timestamp BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_TIMESTAMP |
||||
|
**/ |
||||
|
BSON.BSON_DATA_TIMESTAMP = 17; |
||||
|
/** |
||||
|
* Long BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_LONG |
||||
|
**/ |
||||
|
BSON.BSON_DATA_LONG = 18; |
||||
|
/** |
||||
|
* Long BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_DECIMAL128 |
||||
|
**/ |
||||
|
BSON.BSON_DATA_DECIMAL128 = 19; |
||||
|
/** |
||||
|
* MinKey BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_MIN_KEY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_MIN_KEY = 0xff; |
||||
|
/** |
||||
|
* MaxKey BSON Type |
||||
|
* |
||||
|
* @classconstant BSON_DATA_MAX_KEY |
||||
|
**/ |
||||
|
BSON.BSON_DATA_MAX_KEY = 0x7f; |
||||
|
|
||||
|
/** |
||||
|
* Binary Default Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_DEFAULT |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; |
||||
|
/** |
||||
|
* Binary Function Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_FUNCTION |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; |
||||
|
/** |
||||
|
* Binary Byte Array Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; |
||||
|
/** |
||||
|
* Binary UUID Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_UUID |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_UUID = 3; |
||||
|
/** |
||||
|
* Binary MD5 Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_MD5 |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_MD5 = 4; |
||||
|
/** |
||||
|
* Binary User Defined Type |
||||
|
* |
||||
|
* @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED |
||||
|
**/ |
||||
|
BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; |
||||
|
|
||||
|
// BSON MAX VALUES
|
||||
|
BSON.BSON_INT32_MAX = 0x7fffffff; |
||||
|
BSON.BSON_INT32_MIN = -0x80000000; |
||||
|
|
||||
|
BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; |
||||
|
BSON.BSON_INT64_MIN = -Math.pow(2, 63); |
||||
|
|
||||
|
// JS MAX PRECISE VALUES
|
||||
|
BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
// Internal long versions
|
||||
|
var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
|
||||
|
var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
|
||||
|
|
||||
|
module.exports = deserialize; |
File diff suppressed because it is too large
@ -0,0 +1,28 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
/** |
||||
|
* Normalizes our expected stringified form of a function across versions of node |
||||
|
* @param {Function} fn The function to stringify |
||||
|
*/ |
||||
|
function normalizedFunctionString(fn) { |
||||
|
return fn.toString().replace(/function *\(/, 'function ('); |
||||
|
} |
||||
|
|
||||
|
function newBuffer(item, encoding) { |
||||
|
return new Buffer(item, encoding); |
||||
|
} |
||||
|
|
||||
|
function allocBuffer() { |
||||
|
return Buffer.alloc.apply(Buffer, arguments); |
||||
|
} |
||||
|
|
||||
|
function toBuffer() { |
||||
|
return Buffer.from.apply(Buffer, arguments); |
||||
|
} |
||||
|
|
||||
|
module.exports = { |
||||
|
normalizedFunctionString: normalizedFunctionString, |
||||
|
allocBuffer: typeof Buffer.alloc === 'function' ? allocBuffer : newBuffer, |
||||
|
toBuffer: typeof Buffer.from === 'function' ? toBuffer : newBuffer |
||||
|
}; |
||||
|
|
@ -0,0 +1,33 @@ |
|||||
|
/** |
||||
|
* A class representation of the BSON RegExp type. |
||||
|
* |
||||
|
* @class |
||||
|
* @return {BSONRegExp} A MinKey instance |
||||
|
*/ |
||||
|
function BSONRegExp(pattern, options) { |
||||
|
if (!(this instanceof BSONRegExp)) return new BSONRegExp(); |
||||
|
|
||||
|
// Execute
|
||||
|
this._bsontype = 'BSONRegExp'; |
||||
|
this.pattern = pattern || ''; |
||||
|
this.options = options || ''; |
||||
|
|
||||
|
// Validate options
|
||||
|
for (var i = 0; i < this.options.length; i++) { |
||||
|
if ( |
||||
|
!( |
||||
|
this.options[i] === 'i' || |
||||
|
this.options[i] === 'm' || |
||||
|
this.options[i] === 'x' || |
||||
|
this.options[i] === 'l' || |
||||
|
this.options[i] === 's' || |
||||
|
this.options[i] === 'u' |
||||
|
) |
||||
|
) { |
||||
|
throw new Error('the regular expression options [' + this.options[i] + '] is not supported'); |
||||
|
} |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
module.exports = BSONRegExp; |
||||
|
module.exports.BSONRegExp = BSONRegExp; |
@ -0,0 +1,50 @@ |
|||||
|
// Custom inspect property name / symbol.
|
||||
|
var inspect = Buffer ? require('util').inspect.custom || 'inspect' : 'inspect'; |
||||
|
|
||||
|
/** |
||||
|
* A class representation of the BSON Symbol type. |
||||
|
* |
||||
|
* @class |
||||
|
* @deprecated |
||||
|
* @param {string} value the string representing the symbol. |
||||
|
* @return {Symbol} |
||||
|
*/ |
||||
|
function Symbol(value) { |
||||
|
if (!(this instanceof Symbol)) return new Symbol(value); |
||||
|
this._bsontype = 'Symbol'; |
||||
|
this.value = value; |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Access the wrapped string value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {String} returns the wrapped string. |
||||
|
*/ |
||||
|
Symbol.prototype.valueOf = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Symbol.prototype.toString = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Symbol.prototype[inspect] = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Symbol.prototype.toJSON = function() { |
||||
|
return this.value; |
||||
|
}; |
||||
|
|
||||
|
module.exports = Symbol; |
||||
|
module.exports.Symbol = Symbol; |
@ -0,0 +1,854 @@ |
|||||
|
// 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.
|
||||
|
//
|
||||
|
// Copyright 2009 Google Inc. All Rights Reserved
|
||||
|
|
||||
|
/** |
||||
|
* This type is for INTERNAL use in MongoDB only and should not be used in applications. |
||||
|
* The appropriate corresponding type is the JavaScript Date type. |
||||
|
* |
||||
|
* Defines a Timestamp class for representing a 64-bit two's-complement |
||||
|
* integer value, which faithfully simulates the behavior of a Java "Timestamp". This |
||||
|
* implementation is derived from TimestampLib in GWT. |
||||
|
* |
||||
|
* Constructs a 64-bit two's-complement integer, given its low and high 32-bit |
||||
|
* values as *signed* integers. See the from* functions below for more |
||||
|
* convenient ways of constructing Timestamps. |
||||
|
* |
||||
|
* The internal representation of a Timestamp is the two given signed, 32-bit values. |
||||
|
* We use 32-bit pieces because these are the size of integers on which |
||||
|
* Javascript performs bit-operations. For operations like addition and |
||||
|
* multiplication, we split each number into 16-bit pieces, which can easily be |
||||
|
* multiplied within Javascript's floating-point representation without overflow |
||||
|
* or change in sign. |
||||
|
* |
||||
|
* In the algorithms below, we frequently reduce the negative case to the |
||||
|
* positive case by negating the input(s) and then post-processing the result. |
||||
|
* Note that we must ALWAYS check specially whether those values are MIN_VALUE |
||||
|
* (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as |
||||
|
* a positive number, it overflows back into a negative). Not handling this |
||||
|
* case would often result in infinite recursion. |
||||
|
* |
||||
|
* @class |
||||
|
* @param {number} low the low (signed) 32 bits of the Timestamp. |
||||
|
* @param {number} high the high (signed) 32 bits of the Timestamp. |
||||
|
*/ |
||||
|
function Timestamp(low, high) { |
||||
|
if (!(this instanceof Timestamp)) return new Timestamp(low, high); |
||||
|
this._bsontype = 'Timestamp'; |
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
this.low_ = low | 0; // force into 32 signed bits.
|
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
this.high_ = high | 0; // force into 32 signed bits.
|
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* Return the int value. |
||||
|
* |
||||
|
* @return {number} the value, assuming it is a 32-bit integer. |
||||
|
*/ |
||||
|
Timestamp.prototype.toInt = function() { |
||||
|
return this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the Number value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the closest floating-point representation to this value. |
||||
|
*/ |
||||
|
Timestamp.prototype.toNumber = function() { |
||||
|
return this.high_ * Timestamp.TWO_PWR_32_DBL_ + this.getLowBitsUnsigned(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the JSON value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {string} the JSON representation. |
||||
|
*/ |
||||
|
Timestamp.prototype.toJSON = function() { |
||||
|
return this.toString(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the String value. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} [opt_radix] the radix in which the text should be written. |
||||
|
* @return {string} the textual representation of this value. |
||||
|
*/ |
||||
|
Timestamp.prototype.toString = function(opt_radix) { |
||||
|
var radix = opt_radix || 10; |
||||
|
if (radix < 2 || 36 < radix) { |
||||
|
throw Error('radix out of range: ' + radix); |
||||
|
} |
||||
|
|
||||
|
if (this.isZero()) { |
||||
|
return '0'; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (this.equals(Timestamp.MIN_VALUE)) { |
||||
|
// We need to change the Timestamp value before it can be negated, so we remove
|
||||
|
// the bottom-most digit in this base and then recurse to do the rest.
|
||||
|
var radixTimestamp = Timestamp.fromNumber(radix); |
||||
|
var div = this.div(radixTimestamp); |
||||
|
var rem = div.multiply(radixTimestamp).subtract(this); |
||||
|
return div.toString(radix) + rem.toInt().toString(radix); |
||||
|
} else { |
||||
|
return '-' + this.negate().toString(radix); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
// Do several (6) digits each time through the loop, so as to
|
||||
|
// minimize the calls to the very expensive emulated div.
|
||||
|
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); |
||||
|
|
||||
|
rem = this; |
||||
|
var result = ''; |
||||
|
|
||||
|
while (!rem.isZero()) { |
||||
|
var remDiv = rem.div(radixToPower); |
||||
|
var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); |
||||
|
var digits = intval.toString(radix); |
||||
|
|
||||
|
rem = remDiv; |
||||
|
if (rem.isZero()) { |
||||
|
return digits + result; |
||||
|
} else { |
||||
|
while (digits.length < 6) { |
||||
|
digits = '0' + digits; |
||||
|
} |
||||
|
result = '' + digits + result; |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the high 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the high 32-bits as a signed value. |
||||
|
*/ |
||||
|
Timestamp.prototype.getHighBits = function() { |
||||
|
return this.high_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the low 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the low 32-bits as a signed value. |
||||
|
*/ |
||||
|
Timestamp.prototype.getLowBits = function() { |
||||
|
return this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return the low unsigned 32-bits value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} the low 32-bits as an unsigned value. |
||||
|
*/ |
||||
|
Timestamp.prototype.getLowBitsUnsigned = function() { |
||||
|
return this.low_ >= 0 ? this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the number of bits needed to represent the absolute value of this Timestamp. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. |
||||
|
*/ |
||||
|
Timestamp.prototype.getNumBitsAbs = function() { |
||||
|
if (this.isNegative()) { |
||||
|
if (this.equals(Timestamp.MIN_VALUE)) { |
||||
|
return 64; |
||||
|
} else { |
||||
|
return this.negate().getNumBitsAbs(); |
||||
|
} |
||||
|
} else { |
||||
|
var val = this.high_ !== 0 ? this.high_ : this.low_; |
||||
|
for (var bit = 31; bit > 0; bit--) { |
||||
|
if ((val & (1 << bit)) !== 0) { |
||||
|
break; |
||||
|
} |
||||
|
} |
||||
|
return this.high_ !== 0 ? bit + 33 : bit + 1; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is zero. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is zero. |
||||
|
*/ |
||||
|
Timestamp.prototype.isZero = function() { |
||||
|
return this.high_ === 0 && this.low_ === 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is negative. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is negative. |
||||
|
*/ |
||||
|
Timestamp.prototype.isNegative = function() { |
||||
|
return this.high_ < 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this value is odd. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {boolean} whether this value is odd. |
||||
|
*/ |
||||
|
Timestamp.prototype.isOdd = function() { |
||||
|
return (this.low_ & 1) === 1; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp equals the other |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp equals the other |
||||
|
*/ |
||||
|
Timestamp.prototype.equals = function(other) { |
||||
|
return this.high_ === other.high_ && this.low_ === other.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp does not equal the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp does not equal the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.notEquals = function(other) { |
||||
|
return this.high_ !== other.high_ || this.low_ !== other.low_; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp is less than the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp is less than the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.lessThan = function(other) { |
||||
|
return this.compare(other) < 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp is less than or equal to the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp is less than or equal to the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.lessThanOrEqual = function(other) { |
||||
|
return this.compare(other) <= 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp is greater than the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp is greater than the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.greaterThan = function(other) { |
||||
|
return this.compare(other) > 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Return whether this Timestamp is greater than or equal to the other. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} whether this Timestamp is greater than or equal to the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.greaterThanOrEqual = function(other) { |
||||
|
return this.compare(other) >= 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Compares this Timestamp with the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to compare against. |
||||
|
* @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. |
||||
|
*/ |
||||
|
Timestamp.prototype.compare = function(other) { |
||||
|
if (this.equals(other)) { |
||||
|
return 0; |
||||
|
} |
||||
|
|
||||
|
var thisNeg = this.isNegative(); |
||||
|
var otherNeg = other.isNegative(); |
||||
|
if (thisNeg && !otherNeg) { |
||||
|
return -1; |
||||
|
} |
||||
|
if (!thisNeg && otherNeg) { |
||||
|
return 1; |
||||
|
} |
||||
|
|
||||
|
// at this point, the signs are the same, so subtraction will not overflow
|
||||
|
if (this.subtract(other).isNegative()) { |
||||
|
return -1; |
||||
|
} else { |
||||
|
return 1; |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* The negation of this value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {Timestamp} the negation of this value. |
||||
|
*/ |
||||
|
Timestamp.prototype.negate = function() { |
||||
|
if (this.equals(Timestamp.MIN_VALUE)) { |
||||
|
return Timestamp.MIN_VALUE; |
||||
|
} else { |
||||
|
return this.not().add(Timestamp.ONE); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the sum of this and the given Timestamp. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to add to this one. |
||||
|
* @return {Timestamp} the sum of this and the given Timestamp. |
||||
|
*/ |
||||
|
Timestamp.prototype.add = function(other) { |
||||
|
// Divide each number into 4 chunks of 16 bits, and then sum the chunks.
|
||||
|
|
||||
|
var a48 = this.high_ >>> 16; |
||||
|
var a32 = this.high_ & 0xffff; |
||||
|
var a16 = this.low_ >>> 16; |
||||
|
var a00 = this.low_ & 0xffff; |
||||
|
|
||||
|
var b48 = other.high_ >>> 16; |
||||
|
var b32 = other.high_ & 0xffff; |
||||
|
var b16 = other.low_ >>> 16; |
||||
|
var b00 = other.low_ & 0xffff; |
||||
|
|
||||
|
var c48 = 0, |
||||
|
c32 = 0, |
||||
|
c16 = 0, |
||||
|
c00 = 0; |
||||
|
c00 += a00 + b00; |
||||
|
c16 += c00 >>> 16; |
||||
|
c00 &= 0xffff; |
||||
|
c16 += a16 + b16; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c32 += a32 + b32; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c48 += a48 + b48; |
||||
|
c48 &= 0xffff; |
||||
|
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the difference of this and the given Timestamp. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to subtract from this. |
||||
|
* @return {Timestamp} the difference of this and the given Timestamp. |
||||
|
*/ |
||||
|
Timestamp.prototype.subtract = function(other) { |
||||
|
return this.add(other.negate()); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the product of this and the given Timestamp. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp to multiply with this. |
||||
|
* @return {Timestamp} the product of this and the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.multiply = function(other) { |
||||
|
if (this.isZero()) { |
||||
|
return Timestamp.ZERO; |
||||
|
} else if (other.isZero()) { |
||||
|
return Timestamp.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.equals(Timestamp.MIN_VALUE)) { |
||||
|
return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; |
||||
|
} else if (other.equals(Timestamp.MIN_VALUE)) { |
||||
|
return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (other.isNegative()) { |
||||
|
return this.negate().multiply(other.negate()); |
||||
|
} else { |
||||
|
return this.negate() |
||||
|
.multiply(other) |
||||
|
.negate(); |
||||
|
} |
||||
|
} else if (other.isNegative()) { |
||||
|
return this.multiply(other.negate()).negate(); |
||||
|
} |
||||
|
|
||||
|
// If both Timestamps are small, use float multiplication
|
||||
|
if (this.lessThan(Timestamp.TWO_PWR_24_) && other.lessThan(Timestamp.TWO_PWR_24_)) { |
||||
|
return Timestamp.fromNumber(this.toNumber() * other.toNumber()); |
||||
|
} |
||||
|
|
||||
|
// Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products.
|
||||
|
// We can skip products that would overflow.
|
||||
|
|
||||
|
var a48 = this.high_ >>> 16; |
||||
|
var a32 = this.high_ & 0xffff; |
||||
|
var a16 = this.low_ >>> 16; |
||||
|
var a00 = this.low_ & 0xffff; |
||||
|
|
||||
|
var b48 = other.high_ >>> 16; |
||||
|
var b32 = other.high_ & 0xffff; |
||||
|
var b16 = other.low_ >>> 16; |
||||
|
var b00 = other.low_ & 0xffff; |
||||
|
|
||||
|
var c48 = 0, |
||||
|
c32 = 0, |
||||
|
c16 = 0, |
||||
|
c00 = 0; |
||||
|
c00 += a00 * b00; |
||||
|
c16 += c00 >>> 16; |
||||
|
c00 &= 0xffff; |
||||
|
c16 += a16 * b00; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c16 += a00 * b16; |
||||
|
c32 += c16 >>> 16; |
||||
|
c16 &= 0xffff; |
||||
|
c32 += a32 * b00; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c32 += a16 * b16; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c32 += a00 * b32; |
||||
|
c48 += c32 >>> 16; |
||||
|
c32 &= 0xffff; |
||||
|
c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; |
||||
|
c48 &= 0xffff; |
||||
|
return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Timestamp divided by the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp by which to divide. |
||||
|
* @return {Timestamp} this Timestamp divided by the given one. |
||||
|
*/ |
||||
|
Timestamp.prototype.div = function(other) { |
||||
|
if (other.isZero()) { |
||||
|
throw Error('division by zero'); |
||||
|
} else if (this.isZero()) { |
||||
|
return Timestamp.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.equals(Timestamp.MIN_VALUE)) { |
||||
|
if (other.equals(Timestamp.ONE) || other.equals(Timestamp.NEG_ONE)) { |
||||
|
return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE
|
||||
|
} else if (other.equals(Timestamp.MIN_VALUE)) { |
||||
|
return Timestamp.ONE; |
||||
|
} else { |
||||
|
// At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|.
|
||||
|
var halfThis = this.shiftRight(1); |
||||
|
var approx = halfThis.div(other).shiftLeft(1); |
||||
|
if (approx.equals(Timestamp.ZERO)) { |
||||
|
return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; |
||||
|
} else { |
||||
|
var rem = this.subtract(other.multiply(approx)); |
||||
|
var result = approx.add(rem.div(other)); |
||||
|
return result; |
||||
|
} |
||||
|
} |
||||
|
} else if (other.equals(Timestamp.MIN_VALUE)) { |
||||
|
return Timestamp.ZERO; |
||||
|
} |
||||
|
|
||||
|
if (this.isNegative()) { |
||||
|
if (other.isNegative()) { |
||||
|
return this.negate().div(other.negate()); |
||||
|
} else { |
||||
|
return this.negate() |
||||
|
.div(other) |
||||
|
.negate(); |
||||
|
} |
||||
|
} else if (other.isNegative()) { |
||||
|
return this.div(other.negate()).negate(); |
||||
|
} |
||||
|
|
||||
|
// Repeat the following until the remainder is less than other: find a
|
||||
|
// floating-point that approximates remainder / other *from below*, add this
|
||||
|
// into the result, and subtract it from the remainder. It is critical that
|
||||
|
// the approximate value is less than or equal to the real value so that the
|
||||
|
// remainder never becomes negative.
|
||||
|
var res = Timestamp.ZERO; |
||||
|
rem = this; |
||||
|
while (rem.greaterThanOrEqual(other)) { |
||||
|
// Approximate the result of division. This may be a little greater or
|
||||
|
// smaller than the actual value.
|
||||
|
approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); |
||||
|
|
||||
|
// We will tweak the approximate result by changing it in the 48-th digit or
|
||||
|
// the smallest non-fractional digit, whichever is larger.
|
||||
|
var log2 = Math.ceil(Math.log(approx) / Math.LN2); |
||||
|
var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); |
||||
|
|
||||
|
// Decrease the approximation until it is smaller than the remainder. Note
|
||||
|
// that if it is too large, the product overflows and is negative.
|
||||
|
var approxRes = Timestamp.fromNumber(approx); |
||||
|
var approxRem = approxRes.multiply(other); |
||||
|
while (approxRem.isNegative() || approxRem.greaterThan(rem)) { |
||||
|
approx -= delta; |
||||
|
approxRes = Timestamp.fromNumber(approx); |
||||
|
approxRem = approxRes.multiply(other); |
||||
|
} |
||||
|
|
||||
|
// We know the answer can't be zero... and actually, zero would cause
|
||||
|
// infinite recursion since we would make no progress.
|
||||
|
if (approxRes.isZero()) { |
||||
|
approxRes = Timestamp.ONE; |
||||
|
} |
||||
|
|
||||
|
res = res.add(approxRes); |
||||
|
rem = rem.subtract(approxRem); |
||||
|
} |
||||
|
return res; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Timestamp modulo the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other Timestamp by which to mod. |
||||
|
* @return {Timestamp} this Timestamp modulo the given one. |
||||
|
*/ |
||||
|
Timestamp.prototype.modulo = function(other) { |
||||
|
return this.subtract(this.div(other).multiply(other)); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* The bitwise-NOT of this value. |
||||
|
* |
||||
|
* @method |
||||
|
* @return {Timestamp} the bitwise-NOT of this value. |
||||
|
*/ |
||||
|
Timestamp.prototype.not = function() { |
||||
|
return Timestamp.fromBits(~this.low_, ~this.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-AND of this Timestamp and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other the Timestamp with which to AND. |
||||
|
* @return {Timestamp} the bitwise-AND of this and the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.and = function(other) { |
||||
|
return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-OR of this Timestamp and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other the Timestamp with which to OR. |
||||
|
* @return {Timestamp} the bitwise-OR of this and the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.or = function(other) { |
||||
|
return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the bitwise-XOR of this Timestamp and the given one. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {Timestamp} other the Timestamp with which to XOR. |
||||
|
* @return {Timestamp} the bitwise-XOR of this and the other. |
||||
|
*/ |
||||
|
Timestamp.prototype.xor = function(other) { |
||||
|
return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Timestamp with bits shifted to the left by the given amount. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Timestamp} this shifted to the left by the given amount. |
||||
|
*/ |
||||
|
Timestamp.prototype.shiftLeft = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var low = this.low_; |
||||
|
if (numBits < 32) { |
||||
|
var high = this.high_; |
||||
|
return Timestamp.fromBits(low << numBits, (high << numBits) | (low >>> (32 - numBits))); |
||||
|
} else { |
||||
|
return Timestamp.fromBits(0, low << (numBits - 32)); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Timestamp with bits shifted to the right by the given amount. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Timestamp} this shifted to the right by the given amount. |
||||
|
*/ |
||||
|
Timestamp.prototype.shiftRight = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var high = this.high_; |
||||
|
if (numBits < 32) { |
||||
|
var low = this.low_; |
||||
|
return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >> numBits); |
||||
|
} else { |
||||
|
return Timestamp.fromBits(high >> (numBits - 32), high >= 0 ? 0 : -1); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} numBits the number of bits by which to shift. |
||||
|
* @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. |
||||
|
*/ |
||||
|
Timestamp.prototype.shiftRightUnsigned = function(numBits) { |
||||
|
numBits &= 63; |
||||
|
if (numBits === 0) { |
||||
|
return this; |
||||
|
} else { |
||||
|
var high = this.high_; |
||||
|
if (numBits < 32) { |
||||
|
var low = this.low_; |
||||
|
return Timestamp.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits); |
||||
|
} else if (numBits === 32) { |
||||
|
return Timestamp.fromBits(high, 0); |
||||
|
} else { |
||||
|
return Timestamp.fromBits(high >>> (numBits - 32), 0); |
||||
|
} |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Timestamp representing the given (32-bit) integer value. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} value the 32-bit integer in question. |
||||
|
* @return {Timestamp} the corresponding Timestamp value. |
||||
|
*/ |
||||
|
Timestamp.fromInt = function(value) { |
||||
|
if (-128 <= value && value < 128) { |
||||
|
var cachedObj = Timestamp.INT_CACHE_[value]; |
||||
|
if (cachedObj) { |
||||
|
return cachedObj; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); |
||||
|
if (-128 <= value && value < 128) { |
||||
|
Timestamp.INT_CACHE_[value] = obj; |
||||
|
} |
||||
|
return obj; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} value the number in question. |
||||
|
* @return {Timestamp} the corresponding Timestamp value. |
||||
|
*/ |
||||
|
Timestamp.fromNumber = function(value) { |
||||
|
if (isNaN(value) || !isFinite(value)) { |
||||
|
return Timestamp.ZERO; |
||||
|
} else if (value <= -Timestamp.TWO_PWR_63_DBL_) { |
||||
|
return Timestamp.MIN_VALUE; |
||||
|
} else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { |
||||
|
return Timestamp.MAX_VALUE; |
||||
|
} else if (value < 0) { |
||||
|
return Timestamp.fromNumber(-value).negate(); |
||||
|
} else { |
||||
|
return new Timestamp( |
||||
|
(value % Timestamp.TWO_PWR_32_DBL_) | 0, |
||||
|
(value / Timestamp.TWO_PWR_32_DBL_) | 0 |
||||
|
); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {number} lowBits the low 32-bits. |
||||
|
* @param {number} highBits the high 32-bits. |
||||
|
* @return {Timestamp} the corresponding Timestamp value. |
||||
|
*/ |
||||
|
Timestamp.fromBits = function(lowBits, highBits) { |
||||
|
return new Timestamp(lowBits, highBits); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns a Timestamp representation of the given string, written using the given radix. |
||||
|
* |
||||
|
* @method |
||||
|
* @param {string} str the textual representation of the Timestamp. |
||||
|
* @param {number} opt_radix the radix in which the text is written. |
||||
|
* @return {Timestamp} the corresponding Timestamp value. |
||||
|
*/ |
||||
|
Timestamp.fromString = function(str, opt_radix) { |
||||
|
if (str.length === 0) { |
||||
|
throw Error('number format error: empty string'); |
||||
|
} |
||||
|
|
||||
|
var radix = opt_radix || 10; |
||||
|
if (radix < 2 || 36 < radix) { |
||||
|
throw Error('radix out of range: ' + radix); |
||||
|
} |
||||
|
|
||||
|
if (str.charAt(0) === '-') { |
||||
|
return Timestamp.fromString(str.substring(1), radix).negate(); |
||||
|
} else if (str.indexOf('-') >= 0) { |
||||
|
throw Error('number format error: interior "-" character: ' + str); |
||||
|
} |
||||
|
|
||||
|
// Do several (8) digits each time through the loop, so as to
|
||||
|
// minimize the calls to the very expensive emulated div.
|
||||
|
var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); |
||||
|
|
||||
|
var result = Timestamp.ZERO; |
||||
|
for (var i = 0; i < str.length; i += 8) { |
||||
|
var size = Math.min(8, str.length - i); |
||||
|
var value = parseInt(str.substring(i, i + size), radix); |
||||
|
if (size < 8) { |
||||
|
var power = Timestamp.fromNumber(Math.pow(radix, size)); |
||||
|
result = result.multiply(power).add(Timestamp.fromNumber(value)); |
||||
|
} else { |
||||
|
result = result.multiply(radixToPower); |
||||
|
result = result.add(Timestamp.fromNumber(value)); |
||||
|
} |
||||
|
} |
||||
|
return result; |
||||
|
}; |
||||
|
|
||||
|
// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the
|
||||
|
// from* methods on which they depend.
|
||||
|
|
||||
|
/** |
||||
|
* A cache of the Timestamp representations of small integer values. |
||||
|
* @type {Object} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.INT_CACHE_ = {}; |
||||
|
|
||||
|
// NOTE: the compiler should inline these constant values below and then remove
|
||||
|
// these variables, so there should be no runtime penalty for these.
|
||||
|
|
||||
|
/** |
||||
|
* Number used repeated below in calculations. This must appear before the |
||||
|
* first call to any from* function below. |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_16_DBL_ = 1 << 16; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_24_DBL_ = 1 << 24; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; |
||||
|
|
||||
|
/** |
||||
|
* @type {number} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; |
||||
|
|
||||
|
/** @type {Timestamp} */ |
||||
|
Timestamp.ZERO = Timestamp.fromInt(0); |
||||
|
|
||||
|
/** @type {Timestamp} */ |
||||
|
Timestamp.ONE = Timestamp.fromInt(1); |
||||
|
|
||||
|
/** @type {Timestamp} */ |
||||
|
Timestamp.NEG_ONE = Timestamp.fromInt(-1); |
||||
|
|
||||
|
/** @type {Timestamp} */ |
||||
|
Timestamp.MAX_VALUE = Timestamp.fromBits(0xffffffff | 0, 0x7fffffff | 0); |
||||
|
|
||||
|
/** @type {Timestamp} */ |
||||
|
Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); |
||||
|
|
||||
|
/** |
||||
|
* @type {Timestamp} |
||||
|
* @ignore |
||||
|
*/ |
||||
|
Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); |
||||
|
|
||||
|
/** |
||||
|
* Expose. |
||||
|
*/ |
||||
|
module.exports = Timestamp; |
||||
|
module.exports.Timestamp = Timestamp; |
@ -0,0 +1,118 @@ |
|||||
|
{ |
||||
|
"_args": [ |
||||
|
[ |
||||
|
"bson@~1.1.1", |
||||
|
"/home/art/Documents/API-REST-Etudiants/api/node_modules/mongoose" |
||||
|
] |
||||
|
], |
||||
|
"_from": "bson@>=1.1.1 <1.2.0", |
||||
|
"_hasShrinkwrap": false, |
||||
|
"_id": "bson@1.1.4", |
||||
|
"_inCache": true, |
||||
|
"_installable": true, |
||||
|
"_location": "/bson", |
||||
|
"_nodeVersion": "8.16.2", |
||||
|
"_npmOperationalInternal": { |
||||
|
"host": "s3://npm-registry-packages", |
||||
|
"tmp": "tmp/bson_1.1.4_1585050997763_0.1375353493086151" |
||||
|
}, |
||||
|
"_npmUser": { |
||||
|
"email": "mbroadst@gmail.com", |
||||
|
"name": "mbroadst" |
||||
|
}, |
||||
|
"_npmVersion": "6.4.1", |
||||
|
"_phantomChildren": {}, |
||||
|
"_requested": { |
||||
|
"name": "bson", |
||||
|
"raw": "bson@~1.1.1", |
||||
|
"rawSpec": "~1.1.1", |
||||
|
"scope": null, |
||||
|
"spec": ">=1.1.1 <1.2.0", |
||||
|
"type": "range" |
||||
|
}, |
||||
|
"_requiredBy": [ |
||||
|
"/mongodb", |
||||
|
"/mongoose" |
||||
|
], |
||||
|
"_resolved": "https://registry.npmjs.org/bson/-/bson-1.1.4.tgz", |
||||
|
"_shasum": "f76870d799f15b854dffb7ee32f0a874797f7e89", |
||||
|
"_shrinkwrap": null, |
||||
|
"_spec": "bson@~1.1.1", |
||||
|
"_where": "/home/art/Documents/API-REST-Etudiants/api/node_modules/mongoose", |
||||
|
"author": { |
||||
|
"email": "christkv@gmail.com", |
||||
|
"name": "Christian Amor Kvalheim" |
||||
|
}, |
||||
|
"browser": "lib/bson/bson.js", |
||||
|
"bugs": { |
||||
|
"url": "https://github.com/mongodb/js-bson/issues" |
||||
|
}, |
||||
|
"config": { |
||||
|
"native": false |
||||
|
}, |
||||
|
"contributors": [], |
||||
|
"dependencies": {}, |
||||
|
"description": "A bson parser for node.js and the browser", |
||||
|
"devDependencies": { |
||||
|
"babel-core": "^6.14.0", |
||||
|
"babel-loader": "^6.2.5", |
||||
|
"babel-polyfill": "^6.13.0", |
||||
|
"babel-preset-es2015": "^6.14.0", |
||||
|
"babel-preset-stage-0": "^6.5.0", |
||||
|
"babel-register": "^6.14.0", |
||||
|
"benchmark": "1.0.0", |
||||
|
"colors": "1.1.0", |
||||
|
"conventional-changelog-cli": "^1.3.5", |
||||
|
"nodeunit": "0.9.0", |
||||
|
"webpack": "^1.13.2", |
||||
|
"webpack-polyfills-plugin": "0.0.9" |
||||
|
}, |
||||
|
"directories": { |
||||
|
"lib": "./lib/bson" |
||||
|
}, |
||||
|
"dist": { |
||||
|
"fileCount": 28, |
||||
|
"integrity": "sha512-S/yKGU1syOMzO86+dGpg2qGoDL0zvzcb262G+gqEy6TgP6rt6z6qxSFX/8X6vLC91P7G7C3nLs0+bvDzmvBA3Q==", |
||||
|
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJeefV2CRA9TVsSAnZWagAAJJ4P+QG18fhYsP0vA6r6gSZr\ndtddBSk/0JWcmtXM2fuPqkcCbcX/roU7lbmxer20M0dJEwVu/iromoAV6u35\nEsiQ9LXYhy1KYeRkFRWDpsh2yVvXzhdn9DG16Dcmqk+3qpSn5lGMQvrQGzv0\ni6golLGxjcEBsSiw65OndWUsgVcihrHKI7J15w18UxR17aw4gCZIjoHVzC02\nkmGLtBGpYskqUb+fkV51l/ss7n4OkY8YojNGTbq4/NWMRqLhbbOCR0xuaYtU\nM5DQejOm32K64pBSjnAarEaGvIXVV9j3EusVyn8oGPJ9XWDp62HP+LwEMsQe\nE1Uh9syJEMqLY3z5U+KHNWGX3e4TJ3nDxcHpYWkGSdt5/Q4dnCKbKvgg8+uE\npJfQlZE2i9A57/oWwpYY8E68Ab1C09DyqwvwhziUGkm+XAMVJKKjTE8Tyrfa\nvvgKpzBbXZ3++y1ecSFq/IJJ/IjUVUZNTbWoGHne97Ndv0zODoubtNJZvuYS\nsmLvKOocZpe9uLz4qolH4RBut9emPMJtXpwe6iKoHe8Y0GZXxuaRZt+40Khc\nRVWm8QWRa9+Dtmmjp4/R0a++Tb/7KlRRguW+Z9QJglbg2bTgxEM8cA5WgQ++\nIBf+HC2dWXvyU2WWaeFXvnj+A0g3wmnWDZQbFKTo/pV3cEMDHup6hBC2u5Eo\n9jUl\r\n=Orm/\r\n-----END PGP SIGNATURE-----\r\n", |
||||
|
"shasum": "f76870d799f15b854dffb7ee32f0a874797f7e89", |
||||
|
"tarball": "https://registry.npmjs.org/bson/-/bson-1.1.4.tgz", |
||||
|
"unpackedSize": 772838 |
||||
|
}, |
||||
|
"engines": { |
||||
|
"node": ">=0.6.19" |
||||
|
}, |
||||
|
"gitHead": "6e782dac6a110509097077ee5edd311977f32522", |
||||
|
"homepage": "https://github.com/mongodb/js-bson#readme", |
||||
|
"keywords": [ |
||||
|
"bson", |
||||
|
"mongodb", |
||||
|
"parser" |
||||
|
], |
||||
|
"license": "Apache-2.0", |
||||
|
"main": "./index", |
||||
|
"maintainers": [ |
||||
|
{ |
||||
|
"name": "daprahamian", |
||||
|
"email": "dan.aprahamian@gmail.com" |
||||
|
}, |
||||
|
{ |
||||
|
"name": "mbroadst", |
||||
|
"email": "mbroadst@gmail.com" |
||||
|
} |
||||
|
], |
||||
|
"name": "bson", |
||||
|
"optionalDependencies": {}, |
||||
|
"readme": "ERROR: No README data found!", |
||||
|
"repository": { |
||||
|
"type": "git", |
||||
|
"url": "git+https://github.com/mongodb/js-bson.git" |
||||
|
}, |
||||
|
"scripts": { |
||||
|
"build": "webpack --config ./webpack.dist.config.js", |
||||
|
"changelog": "conventional-changelog -p angular -i HISTORY.md -s", |
||||
|
"format": "prettier --print-width 100 --tab-width 2 --single-quote --write 'test/**/*.js' 'lib/**/*.js'", |
||||
|
"lint": "eslint lib test", |
||||
|
"test": "nodeunit ./test/node" |
||||
|
}, |
||||
|
"version": "1.1.4" |
||||
|
} |
@ -0,0 +1,19 @@ |
|||||
|
Copyright Node.js contributors. All rights reserved. |
||||
|
|
||||
|
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. |
@ -0,0 +1,3 @@ |
|||||
|
# core-util-is |
||||
|
|
||||
|
The `util.is*` functions introduced in Node v0.12. |
@ -0,0 +1,604 @@ |
|||||
|
diff --git a/lib/util.js b/lib/util.js
|
||||
|
index a03e874..9074e8e 100644
|
||||
|
--- a/lib/util.js
|
||||
|
+++ b/lib/util.js
|
||||
|
@@ -19,430 +19,6 @@
|
||||
|
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE |
||||
|
// USE OR OTHER DEALINGS IN THE SOFTWARE. |
||||
|
|
||||
|
-var formatRegExp = /%[sdj%]/g;
|
||||
|
-exports.format = function(f) {
|
||||
|
- if (!isString(f)) {
|
||||
|
- var objects = [];
|
||||
|
- for (var i = 0; i < arguments.length; i++) {
|
||||
|
- objects.push(inspect(arguments[i]));
|
||||
|
- }
|
||||
|
- return objects.join(' ');
|
||||
|
- }
|
||||
|
-
|
||||
|
- var i = 1;
|
||||
|
- var args = arguments;
|
||||
|
- var len = args.length;
|
||||
|
- var str = String(f).replace(formatRegExp, function(x) {
|
||||
|
- if (x === '%%') return '%';
|
||||
|
- if (i >= len) return x;
|
||||
|
- switch (x) {
|
||||
|
- case '%s': return String(args[i++]);
|
||||
|
- case '%d': return Number(args[i++]);
|
||||
|
- case '%j':
|
||||
|
- try {
|
||||
|
- return JSON.stringify(args[i++]);
|
||||
|
- } catch (_) {
|
||||
|
- return '[Circular]';
|
||||
|
- }
|
||||
|
- default:
|
||||
|
- return x;
|
||||
|
- }
|
||||
|
- });
|
||||
|
- for (var x = args[i]; i < len; x = args[++i]) {
|
||||
|
- if (isNull(x) || !isObject(x)) {
|
||||
|
- str += ' ' + x;
|
||||
|
- } else {
|
||||
|
- str += ' ' + inspect(x);
|
||||
|
- }
|
||||
|
- }
|
||||
|
- return str;
|
||||
|
-};
|
||||
|
-
|
||||
|
-
|
||||
|
-// Mark that a method should not be used.
|
||||
|
-// Returns a modified function which warns once by default.
|
||||
|
-// If --no-deprecation is set, then it is a no-op.
|
||||
|
-exports.deprecate = function(fn, msg) {
|
||||
|
- // Allow for deprecating things in the process of starting up.
|
||||
|
- if (isUndefined(global.process)) {
|
||||
|
- return function() {
|
||||
|
- return exports.deprecate(fn, msg).apply(this, arguments);
|
||||
|
- };
|
||||
|
- }
|
||||
|
-
|
||||
|
- if (process.noDeprecation === true) {
|
||||
|
- return fn;
|
||||
|
- }
|
||||
|
-
|
||||
|
- var warned = false;
|
||||
|
- function deprecated() {
|
||||
|
- if (!warned) {
|
||||
|
- if (process.throwDeprecation) {
|
||||
|
- throw new Error(msg);
|
||||
|
- } else if (process.traceDeprecation) {
|
||||
|
- console.trace(msg);
|
||||
|
- } else {
|
||||
|
- console.error(msg);
|
||||
|
- }
|
||||
|
- warned = true;
|
||||
|
- }
|
||||
|
- return fn.apply(this, arguments);
|
||||
|
- }
|
||||
|
-
|
||||
|
- return deprecated;
|
||||
|
-};
|
||||
|
-
|
||||
|
-
|
||||
|
-var debugs = {};
|
||||
|
-var debugEnviron;
|
||||
|
-exports.debuglog = function(set) {
|
||||
|
- if (isUndefined(debugEnviron))
|
||||
|
- debugEnviron = process.env.NODE_DEBUG || '';
|
||||
|
- set = set.toUpperCase();
|
||||
|
- if (!debugs[set]) {
|
||||
|
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
|
||||
|
- var pid = process.pid;
|
||||
|
- debugs[set] = function() {
|
||||
|
- var msg = exports.format.apply(exports, arguments);
|
||||
|
- console.error('%s %d: %s', set, pid, msg);
|
||||
|
- };
|
||||
|
- } else {
|
||||
|
- debugs[set] = function() {};
|
||||
|
- }
|
||||
|
- }
|
||||
|
- return debugs[set];
|
||||
|
-};
|
||||
|
-
|
||||
|
-
|
||||
|
-/**
|
||||
|
- * Echos the value of a value. Trys to print the value out
|
||||
|
- * in the best way possible given the different types.
|
||||
|
- *
|
||||
|
- * @param {Object} obj The object to print out.
|
||||
|
- * @param {Object} opts Optional options object that alters the output.
|
||||
|
- */
|
||||
|
-/* legacy: obj, showHidden, depth, colors*/
|
||||
|
-function inspect(obj, opts) {
|
||||
|
- // default options
|
||||
|
- var ctx = {
|
||||
|
- seen: [],
|
||||
|
- stylize: stylizeNoColor
|
||||
|
- };
|
||||
|
- // legacy...
|
||||
|
- if (arguments.length >= 3) ctx.depth = arguments[2];
|
||||
|
- if (arguments.length >= 4) ctx.colors = arguments[3];
|
||||
|
- if (isBoolean(opts)) {
|
||||
|
- // legacy...
|
||||
|
- ctx.showHidden = opts;
|
||||
|
- } else if (opts) {
|
||||
|
- // got an "options" object
|
||||
|
- exports._extend(ctx, opts);
|
||||
|
- }
|
||||
|
- // set default options
|
||||
|
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
|
||||
|
- if (isUndefined(ctx.depth)) ctx.depth = 2;
|
||||
|
- if (isUndefined(ctx.colors)) ctx.colors = false;
|
||||
|
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
|
||||
|
- if (ctx.colors) ctx.stylize = stylizeWithColor;
|
||||
|
- return formatValue(ctx, obj, ctx.depth);
|
||||
|
-}
|
||||
|
-exports.inspect = inspect;
|
||||
|
-
|
||||
|
-
|
||||
|
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
|
||||
|
-inspect.colors = {
|
||||
|
- 'bold' : [1, 22],
|
||||
|
- 'italic' : [3, 23],
|
||||
|
- 'underline' : [4, 24],
|
||||
|
- 'inverse' : [7, 27],
|
||||
|
- 'white' : [37, 39],
|
||||
|
- 'grey' : [90, 39],
|
||||
|
- 'black' : [30, 39],
|
||||
|
- 'blue' : [34, 39],
|
||||
|
- 'cyan' : [36, 39],
|
||||
|
- 'green' : [32, 39],
|
||||
|
- 'magenta' : [35, 39],
|
||||
|
- 'red' : [31, 39],
|
||||
|
- 'yellow' : [33, 39]
|
||||
|
-};
|
||||
|
-
|
||||
|
-// Don't use 'blue' not visible on cmd.exe
|
||||
|
-inspect.styles = {
|
||||
|
- 'special': 'cyan',
|
||||
|
- 'number': 'yellow',
|
||||
|
- 'boolean': 'yellow',
|
||||
|
- 'undefined': 'grey',
|
||||
|
- 'null': 'bold',
|
||||
|
- 'string': 'green',
|
||||
|
- 'date': 'magenta',
|
||||
|
- // "name": intentionally not styling
|
||||
|
- 'regexp': 'red'
|
||||
|
-};
|
||||
|
-
|
||||
|
-
|
||||
|
-function stylizeWithColor(str, styleType) {
|
||||
|
- var style = inspect.styles[styleType];
|
||||
|
-
|
||||
|
- if (style) {
|
||||
|
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
|
||||
|
- '\u001b[' + inspect.colors[style][1] + 'm';
|
||||
|
- } else {
|
||||
|
- return str;
|
||||
|
- }
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function stylizeNoColor(str, styleType) {
|
||||
|
- return str;
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function arrayToHash(array) {
|
||||
|
- var hash = {};
|
||||
|
-
|
||||
|
- array.forEach(function(val, idx) {
|
||||
|
- hash[val] = true;
|
||||
|
- });
|
||||
|
-
|
||||
|
- return hash;
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function formatValue(ctx, value, recurseTimes) {
|
||||
|
- // Provide a hook for user-specified inspect functions.
|
||||
|
- // Check that value is an object with an inspect function on it
|
||||
|
- if (ctx.customInspect &&
|
||||
|
- value &&
|
||||
|
- isFunction(value.inspect) &&
|
||||
|
- // Filter out the util module, it's inspect function is special
|
||||
|
- value.inspect !== exports.inspect &&
|
||||
|
- // Also filter out any prototype objects using the circular check.
|
||||
|
- !(value.constructor && value.constructor.prototype === value)) {
|
||||
|
- var ret = value.inspect(recurseTimes, ctx);
|
||||
|
- if (!isString(ret)) {
|
||||
|
- ret = formatValue(ctx, ret, recurseTimes);
|
||||
|
- }
|
||||
|
- return ret;
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Primitive types cannot have properties
|
||||
|
- var primitive = formatPrimitive(ctx, value);
|
||||
|
- if (primitive) {
|
||||
|
- return primitive;
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Look up the keys of the object.
|
||||
|
- var keys = Object.keys(value);
|
||||
|
- var visibleKeys = arrayToHash(keys);
|
||||
|
-
|
||||
|
- if (ctx.showHidden) {
|
||||
|
- keys = Object.getOwnPropertyNames(value);
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Some type of object without properties can be shortcutted.
|
||||
|
- if (keys.length === 0) {
|
||||
|
- if (isFunction(value)) {
|
||||
|
- var name = value.name ? ': ' + value.name : '';
|
||||
|
- return ctx.stylize('[Function' + name + ']', 'special');
|
||||
|
- }
|
||||
|
- if (isRegExp(value)) {
|
||||
|
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
|
||||
|
- }
|
||||
|
- if (isDate(value)) {
|
||||
|
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
|
||||
|
- }
|
||||
|
- if (isError(value)) {
|
||||
|
- return formatError(value);
|
||||
|
- }
|
||||
|
- }
|
||||
|
-
|
||||
|
- var base = '', array = false, braces = ['{', '}'];
|
||||
|
-
|
||||
|
- // Make Array say that they are Array
|
||||
|
- if (isArray(value)) {
|
||||
|
- array = true;
|
||||
|
- braces = ['[', ']'];
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Make functions say that they are functions
|
||||
|
- if (isFunction(value)) {
|
||||
|
- var n = value.name ? ': ' + value.name : '';
|
||||
|
- base = ' [Function' + n + ']';
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Make RegExps say that they are RegExps
|
||||
|
- if (isRegExp(value)) {
|
||||
|
- base = ' ' + RegExp.prototype.toString.call(value);
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Make dates with properties first say the date
|
||||
|
- if (isDate(value)) {
|
||||
|
- base = ' ' + Date.prototype.toUTCString.call(value);
|
||||
|
- }
|
||||
|
-
|
||||
|
- // Make error with message first say the error
|
||||
|
- if (isError(value)) {
|
||||
|
- base = ' ' + formatError(value);
|
||||
|
- }
|
||||
|
-
|
||||
|
- if (keys.length === 0 && (!array || value.length == 0)) {
|
||||
|
- return braces[0] + base + braces[1];
|
||||
|
- }
|
||||
|
-
|
||||
|
- if (recurseTimes < 0) {
|
||||
|
- if (isRegExp(value)) {
|
||||
|
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
|
||||
|
- } else {
|
||||
|
- return ctx.stylize('[Object]', 'special');
|
||||
|
- }
|
||||
|
- }
|
||||
|
-
|
||||
|
- ctx.seen.push(value);
|
||||
|
-
|
||||
|
- var output;
|
||||
|
- if (array) {
|
||||
|
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
|
||||
|
- } else {
|
||||
|
- output = keys.map(function(key) {
|
||||
|
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
|
||||
|
- });
|
||||
|
- }
|
||||
|
-
|
||||
|
- ctx.seen.pop();
|
||||
|
-
|
||||
|
- return reduceToSingleString(output, base, braces);
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function formatPrimitive(ctx, value) {
|
||||
|
- if (isUndefined(value))
|
||||
|
- return ctx.stylize('undefined', 'undefined');
|
||||
|
- if (isString(value)) {
|
||||
|
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
|
||||
|
- .replace(/'/g, "\\'")
|
||||
|
- .replace(/\\"/g, '"') + '\'';
|
||||
|
- return ctx.stylize(simple, 'string');
|
||||
|
- }
|
||||
|
- if (isNumber(value)) {
|
||||
|
- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
|
||||
|
- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
|
||||
|
- if (value === 0 && 1 / value < 0)
|
||||
|
- return ctx.stylize('-0', 'number');
|
||||
|
- return ctx.stylize('' + value, 'number');
|
||||
|
- }
|
||||
|
- if (isBoolean(value))
|
||||
|
- return ctx.stylize('' + value, 'boolean');
|
||||
|
- // For some reason typeof null is "object", so special case here.
|
||||
|
- if (isNull(value))
|
||||
|
- return ctx.stylize('null', 'null');
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function formatError(value) {
|
||||
|
- return '[' + Error.prototype.toString.call(value) + ']';
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
|
||||
|
- var output = [];
|
||||
|
- for (var i = 0, l = value.length; i < l; ++i) {
|
||||
|
- if (hasOwnProperty(value, String(i))) {
|
||||
|
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
|
||||
|
- String(i), true));
|
||||
|
- } else {
|
||||
|
- output.push('');
|
||||
|
- }
|
||||
|
- }
|
||||
|
- keys.forEach(function(key) {
|
||||
|
- if (!key.match(/^\d+$/)) {
|
||||
|
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
|
||||
|
- key, true));
|
||||
|
- }
|
||||
|
- });
|
||||
|
- return output;
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
|
||||
|
- var name, str, desc;
|
||||
|
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
|
||||
|
- if (desc.get) {
|
||||
|
- if (desc.set) {
|
||||
|
- str = ctx.stylize('[Getter/Setter]', 'special');
|
||||
|
- } else {
|
||||
|
- str = ctx.stylize('[Getter]', 'special');
|
||||
|
- }
|
||||
|
- } else {
|
||||
|
- if (desc.set) {
|
||||
|
- str = ctx.stylize('[Setter]', 'special');
|
||||
|
- }
|
||||
|
- }
|
||||
|
- if (!hasOwnProperty(visibleKeys, key)) {
|
||||
|
- name = '[' + key + ']';
|
||||
|
- }
|
||||
|
- if (!str) {
|
||||
|
- if (ctx.seen.indexOf(desc.value) < 0) {
|
||||
|
- if (isNull(recurseTimes)) {
|
||||
|
- str = formatValue(ctx, desc.value, null);
|
||||
|
- } else {
|
||||
|
- str = formatValue(ctx, desc.value, recurseTimes - 1);
|
||||
|
- }
|
||||
|
- if (str.indexOf('\n') > -1) {
|
||||
|
- if (array) {
|
||||
|
- str = str.split('\n').map(function(line) {
|
||||
|
- return ' ' + line;
|
||||
|
- }).join('\n').substr(2);
|
||||
|
- } else {
|
||||
|
- str = '\n' + str.split('\n').map(function(line) {
|
||||
|
- return ' ' + line;
|
||||
|
- }).join('\n');
|
||||
|
- }
|
||||
|
- }
|
||||
|
- } else {
|
||||
|
- str = ctx.stylize('[Circular]', 'special');
|
||||
|
- }
|
||||
|
- }
|
||||
|
- if (isUndefined(name)) {
|
||||
|
- if (array && key.match(/^\d+$/)) {
|
||||
|
- return str;
|
||||
|
- }
|
||||
|
- name = JSON.stringify('' + key);
|
||||
|
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
|
||||
|
- name = name.substr(1, name.length - 2);
|
||||
|
- name = ctx.stylize(name, 'name');
|
||||
|
- } else {
|
||||
|
- name = name.replace(/'/g, "\\'")
|
||||
|
- .replace(/\\"/g, '"')
|
||||
|
- .replace(/(^"|"$)/g, "'");
|
||||
|
- name = ctx.stylize(name, 'string');
|
||||
|
- }
|
||||
|
- }
|
||||
|
-
|
||||
|
- return name + ': ' + str;
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function reduceToSingleString(output, base, braces) {
|
||||
|
- var numLinesEst = 0;
|
||||
|
- var length = output.reduce(function(prev, cur) {
|
||||
|
- numLinesEst++;
|
||||
|
- if (cur.indexOf('\n') >= 0) numLinesEst++;
|
||||
|
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
|
||||
|
- }, 0);
|
||||
|
-
|
||||
|
- if (length > 60) {
|
||||
|
- return braces[0] +
|
||||
|
- (base === '' ? '' : base + '\n ') +
|
||||
|
- ' ' +
|
||||
|
- output.join(',\n ') +
|
||||
|
- ' ' +
|
||||
|
- braces[1];
|
||||
|
- }
|
||||
|
-
|
||||
|
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
// NOTE: These type checking functions intentionally don't use `instanceof` |
||||
|
// because it is fragile and can be easily faked with `Object.create()`. |
||||
|
function isArray(ar) { |
||||
|
@@ -522,166 +98,10 @@ function isPrimitive(arg) {
|
||||
|
exports.isPrimitive = isPrimitive; |
||||
|
|
||||
|
function isBuffer(arg) { |
||||
|
- return arg instanceof Buffer;
|
||||
|
+ return Buffer.isBuffer(arg);
|
||||
|
} |
||||
|
exports.isBuffer = isBuffer; |
||||
|
|
||||
|
function objectToString(o) { |
||||
|
return Object.prototype.toString.call(o); |
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-function pad(n) {
|
||||
|
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
|
||||
|
- 'Oct', 'Nov', 'Dec'];
|
||||
|
-
|
||||
|
-// 26 Feb 16:19:34
|
||||
|
-function timestamp() {
|
||||
|
- var d = new Date();
|
||||
|
- var time = [pad(d.getHours()),
|
||||
|
- pad(d.getMinutes()),
|
||||
|
- pad(d.getSeconds())].join(':');
|
||||
|
- return [d.getDate(), months[d.getMonth()], time].join(' ');
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-// log is just a thin wrapper to console.log that prepends a timestamp
|
||||
|
-exports.log = function() {
|
||||
|
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
|
||||
|
-};
|
||||
|
-
|
||||
|
-
|
||||
|
-/**
|
||||
|
- * Inherit the prototype methods from one constructor into another.
|
||||
|
- *
|
||||
|
- * The Function.prototype.inherits from lang.js rewritten as a standalone
|
||||
|
- * function (not on Function.prototype). NOTE: If this file is to be loaded
|
||||
|
- * during bootstrapping this function needs to be rewritten using some native
|
||||
|
- * functions as prototype setup using normal JavaScript does not work as
|
||||
|
- * expected during bootstrapping (see mirror.js in r114903).
|
||||
|
- *
|
||||
|
- * @param {function} ctor Constructor function which needs to inherit the
|
||||
|
- * prototype.
|
||||
|
- * @param {function} superCtor Constructor function to inherit prototype from.
|
||||
|
- */
|
||||
|
-exports.inherits = function(ctor, superCtor) {
|
||||
|
- ctor.super_ = superCtor;
|
||||
|
- ctor.prototype = Object.create(superCtor.prototype, {
|
||||
|
- constructor: {
|
||||
|
- value: ctor,
|
||||
|
- enumerable: false,
|
||||
|
- writable: true,
|
||||
|
- configurable: true
|
||||
|
- }
|
||||
|
- });
|
||||
|
-};
|
||||
|
-
|
||||
|
-exports._extend = function(origin, add) {
|
||||
|
- // Don't do anything if add isn't an object
|
||||
|
- if (!add || !isObject(add)) return origin;
|
||||
|
-
|
||||
|
- var keys = Object.keys(add);
|
||||
|
- var i = keys.length;
|
||||
|
- while (i--) {
|
||||
|
- origin[keys[i]] = add[keys[i]];
|
||||
|
- }
|
||||
|
- return origin;
|
||||
|
-};
|
||||
|
-
|
||||
|
-function hasOwnProperty(obj, prop) {
|
||||
|
- return Object.prototype.hasOwnProperty.call(obj, prop);
|
||||
|
-}
|
||||
|
-
|
||||
|
-
|
||||
|
-// Deprecated old stuff.
|
||||
|
-
|
||||
|
-exports.p = exports.deprecate(function() {
|
||||
|
- for (var i = 0, len = arguments.length; i < len; ++i) {
|
||||
|
- console.error(exports.inspect(arguments[i]));
|
||||
|
- }
|
||||
|
-}, 'util.p: Use console.error() instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.exec = exports.deprecate(function() {
|
||||
|
- return require('child_process').exec.apply(this, arguments);
|
||||
|
-}, 'util.exec is now called `child_process.exec`.');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.print = exports.deprecate(function() {
|
||||
|
- for (var i = 0, len = arguments.length; i < len; ++i) {
|
||||
|
- process.stdout.write(String(arguments[i]));
|
||||
|
- }
|
||||
|
-}, 'util.print: Use console.log instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.puts = exports.deprecate(function() {
|
||||
|
- for (var i = 0, len = arguments.length; i < len; ++i) {
|
||||
|
- process.stdout.write(arguments[i] + '\n');
|
||||
|
- }
|
||||
|
-}, 'util.puts: Use console.log instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.debug = exports.deprecate(function(x) {
|
||||
|
- process.stderr.write('DEBUG: ' + x + '\n');
|
||||
|
-}, 'util.debug: Use console.error instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.error = exports.deprecate(function(x) {
|
||||
|
- for (var i = 0, len = arguments.length; i < len; ++i) {
|
||||
|
- process.stderr.write(arguments[i] + '\n');
|
||||
|
- }
|
||||
|
-}, 'util.error: Use console.error instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
|
||||
|
- var callbackCalled = false;
|
||||
|
-
|
||||
|
- function call(a, b, c) {
|
||||
|
- if (callback && !callbackCalled) {
|
||||
|
- callback(a, b, c);
|
||||
|
- callbackCalled = true;
|
||||
|
- }
|
||||
|
- }
|
||||
|
-
|
||||
|
- readStream.addListener('data', function(chunk) {
|
||||
|
- if (writeStream.write(chunk) === false) readStream.pause();
|
||||
|
- });
|
||||
|
-
|
||||
|
- writeStream.addListener('drain', function() {
|
||||
|
- readStream.resume();
|
||||
|
- });
|
||||
|
-
|
||||
|
- readStream.addListener('end', function() {
|
||||
|
- writeStream.end();
|
||||
|
- });
|
||||
|
-
|
||||
|
- readStream.addListener('close', function() {
|
||||
|
- call();
|
||||
|
- });
|
||||
|
-
|
||||
|
- readStream.addListener('error', function(err) {
|
||||
|
- writeStream.end();
|
||||
|
- call(err);
|
||||
|
- });
|
||||
|
-
|
||||
|
- writeStream.addListener('error', function(err) {
|
||||
|
- readStream.destroy();
|
||||
|
- call(err);
|
||||
|
- });
|
||||
|
-}, 'util.pump(): Use readableStream.pipe() instead');
|
||||
|
-
|
||||
|
-
|
||||
|
-var uv;
|
||||
|
-exports._errnoException = function(err, syscall) {
|
||||
|
- if (isUndefined(uv)) uv = process.binding('uv');
|
||||
|
- var errname = uv.errname(err);
|
||||
|
- var e = new Error(syscall + ' ' + errname);
|
||||
|
- e.code = errname;
|
||||
|
- e.errno = errname;
|
||||
|
- e.syscall = syscall;
|
||||
|
- return e;
|
||||
|
-};
|
||||
|
+}
|
@ -0,0 +1,107 @@ |
|||||
|
// Copyright Joyent, Inc. and other Node contributors.
|
||||
|
//
|
||||
|
// 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.
|
||||
|
|
||||
|
// NOTE: These type checking functions intentionally don't use `instanceof`
|
||||
|
// because it is fragile and can be easily faked with `Object.create()`.
|
||||
|
|
||||
|
function isArray(arg) { |
||||
|
if (Array.isArray) { |
||||
|
return Array.isArray(arg); |
||||
|
} |
||||
|
return objectToString(arg) === '[object Array]'; |
||||
|
} |
||||
|
exports.isArray = isArray; |
||||
|
|
||||
|
function isBoolean(arg) { |
||||
|
return typeof arg === 'boolean'; |
||||
|
} |
||||
|
exports.isBoolean = isBoolean; |
||||
|
|
||||
|
function isNull(arg) { |
||||
|
return arg === null; |
||||
|
} |
||||
|
exports.isNull = isNull; |
||||
|
|
||||
|
function isNullOrUndefined(arg) { |
||||
|
return arg == null; |
||||
|
} |
||||
|
exports.isNullOrUndefined = isNullOrUndefined; |
||||
|
|
||||
|
function isNumber(arg) { |
||||
|
return typeof arg === 'number'; |
||||
|
} |
||||
|
exports.isNumber = isNumber; |
||||
|
|
||||
|
function isString(arg) { |
||||
|
return typeof arg === 'string'; |
||||
|
} |
||||
|
exports.isString = isString; |
||||
|
|
||||
|
function isSymbol(arg) { |
||||
|
return typeof arg === 'symbol'; |
||||
|
} |
||||
|
exports.isSymbol = isSymbol; |
||||
|
|
||||
|
function isUndefined(arg) { |
||||
|
return arg === void 0; |
||||
|
} |
||||
|
exports.isUndefined = isUndefined; |
||||
|
|
||||
|
function isRegExp(re) { |
||||
|
return objectToString(re) === '[object RegExp]'; |
||||
|
} |
||||
|
exports.isRegExp = isRegExp; |
||||
|
|
||||
|
function isObject(arg) { |
||||
|
return typeof arg === 'object' && arg !== null; |
||||
|
} |
||||
|
exports.isObject = isObject; |
||||
|
|
||||
|
function isDate(d) { |
||||
|
return objectToString(d) === '[object Date]'; |
||||
|
} |
||||
|
exports.isDate = isDate; |
||||
|
|
||||
|
function isError(e) { |
||||
|
return (objectToString(e) === '[object Error]' || e instanceof Error); |
||||
|
} |
||||
|
exports.isError = isError; |
||||
|
|
||||
|
function isFunction(arg) { |
||||
|
return typeof arg === 'function'; |
||||
|
} |
||||
|
exports.isFunction = isFunction; |
||||
|
|
||||
|
function isPrimitive(arg) { |
||||
|
return arg === null || |
||||
|
typeof arg === 'boolean' || |
||||
|
typeof arg === 'number' || |
||||
|
typeof arg === 'string' || |
||||
|
typeof arg === 'symbol' || // ES6 symbol
|
||||
|
typeof arg === 'undefined'; |
||||
|
} |
||||
|
exports.isPrimitive = isPrimitive; |
||||
|
|
||||
|
exports.isBuffer = Buffer.isBuffer; |
||||
|
|
||||
|
function objectToString(o) { |
||||
|
return Object.prototype.toString.call(o); |
||||
|
} |
@ -0,0 +1,86 @@ |
|||||
|
{ |
||||
|
"_args": [ |
||||
|
[ |
||||
|
"core-util-is@~1.0.0", |
||||
|
"/home/art/Documents/API-REST-Etudiants/api/node_modules/readable-stream" |
||||
|
] |
||||
|
], |
||||
|
"_from": "core-util-is@>=1.0.0 <1.1.0", |
||||
|
"_id": "core-util-is@1.0.2", |
||||
|
"_inCache": true, |
||||
|
"_installable": true, |
||||
|
"_location": "/core-util-is", |
||||
|
"_nodeVersion": "4.0.0", |
||||
|
"_npmUser": { |
||||
|
"email": "i@izs.me", |
||||
|
"name": "isaacs" |
||||
|
}, |
||||
|
"_npmVersion": "3.3.2", |
||||
|
"_phantomChildren": {}, |
||||
|
"_requested": { |
||||
|
"name": "core-util-is", |
||||
|
"raw": "core-util-is@~1.0.0", |
||||
|
"rawSpec": "~1.0.0", |
||||
|
"scope": null, |
||||
|
"spec": ">=1.0.0 <1.1.0", |
||||
|
"type": "range" |
||||
|
}, |
||||
|
"_requiredBy": [ |
||||
|
"/readable-stream" |
||||
|
], |
||||
|
"_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", |
||||
|
"_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", |
||||
|
"_shrinkwrap": null, |
||||
|
"_spec": "core-util-is@~1.0.0", |
||||
|
"_where": "/home/art/Documents/API-REST-Etudiants/api/node_modules/readable-stream", |
||||
|
"author": { |
||||
|
"email": "i@izs.me", |
||||
|
"name": "Isaac Z. Schlueter", |
||||
|
"url": "http://blog.izs.me/" |
||||
|
}, |
||||
|
"bugs": { |
||||
|
"url": "https://github.com/isaacs/core-util-is/issues" |
||||
|
}, |
||||
|
"dependencies": {}, |
||||
|
"description": "The `util.is*` functions introduced in Node v0.12.", |
||||
|
"devDependencies": { |
||||
|
"tap": "^2.3.0" |
||||
|
}, |
||||
|
"directories": {}, |
||||
|
"dist": { |
||||
|
"shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7", |
||||
|
"tarball": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz" |
||||
|
}, |
||||
|
"gitHead": "a177da234df5638b363ddc15fa324619a38577c8", |
||||
|
"homepage": "https://github.com/isaacs/core-util-is#readme", |
||||
|
"keywords": [ |
||||
|
"isArray", |
||||
|
"isBuffer", |
||||
|
"isNumber", |
||||
|
"isRegExp", |
||||
|
"isString", |
||||
|
"isThat", |
||||
|
"isThis", |
||||
|
"polyfill", |
||||
|
"util" |
||||
|
], |
||||
|
"license": "MIT", |
||||
|
"main": "lib/util.js", |
||||
|
"maintainers": [ |
||||
|
{ |
||||
|
"name": "isaacs", |
||||
|
"email": "i@izs.me" |
||||
|
} |
||||
|
], |
||||
|
"name": "core-util-is", |
||||
|
"optionalDependencies": {}, |
||||
|
"readme": "ERROR: No README data found!", |
||||
|
"repository": { |
||||
|
"type": "git", |
||||
|
"url": "git://github.com/isaacs/core-util-is.git" |
||||
|
}, |
||||
|
"scripts": { |
||||
|
"test": "tap test.js" |
||||
|
}, |
||||
|
"version": "1.0.2" |
||||
|
} |
@ -0,0 +1,68 @@ |
|||||
|
var assert = require('tap'); |
||||
|
|
||||
|
var t = require('./lib/util'); |
||||
|
|
||||
|
assert.equal(t.isArray([]), true); |
||||
|
assert.equal(t.isArray({}), false); |
||||
|
|
||||
|
assert.equal(t.isBoolean(null), false); |
||||
|
assert.equal(t.isBoolean(true), true); |
||||
|
assert.equal(t.isBoolean(false), true); |
||||
|
|
||||
|
assert.equal(t.isNull(null), true); |
||||
|
assert.equal(t.isNull(undefined), false); |
||||
|
assert.equal(t.isNull(false), false); |
||||
|
assert.equal(t.isNull(), false); |
||||
|
|
||||
|
assert.equal(t.isNullOrUndefined(null), true); |
||||
|
assert.equal(t.isNullOrUndefined(undefined), true); |
||||
|
assert.equal(t.isNullOrUndefined(false), false); |
||||
|
assert.equal(t.isNullOrUndefined(), true); |
||||
|
|
||||
|
assert.equal(t.isNumber(null), false); |
||||
|
assert.equal(t.isNumber('1'), false); |
||||
|
assert.equal(t.isNumber(1), true); |
||||
|
|
||||
|
assert.equal(t.isString(null), false); |
||||
|
assert.equal(t.isString('1'), true); |
||||
|
assert.equal(t.isString(1), false); |
||||
|
|
||||
|
assert.equal(t.isSymbol(null), false); |
||||
|
assert.equal(t.isSymbol('1'), false); |
||||
|
assert.equal(t.isSymbol(1), false); |
||||
|
assert.equal(t.isSymbol(Symbol()), true); |
||||
|
|
||||
|
assert.equal(t.isUndefined(null), false); |
||||
|
assert.equal(t.isUndefined(undefined), true); |
||||
|
assert.equal(t.isUndefined(false), false); |
||||
|
assert.equal(t.isUndefined(), true); |
||||
|
|
||||
|
assert.equal(t.isRegExp(null), false); |
||||
|
assert.equal(t.isRegExp('1'), false); |
||||
|
assert.equal(t.isRegExp(new RegExp()), true); |
||||
|
|
||||
|
assert.equal(t.isObject({}), true); |
||||
|
assert.equal(t.isObject([]), true); |
||||
|
assert.equal(t.isObject(new RegExp()), true); |
||||
|
assert.equal(t.isObject(new Date()), true); |
||||
|
|
||||
|
assert.equal(t.isDate(null), false); |
||||
|
assert.equal(t.isDate('1'), false); |
||||
|
assert.equal(t.isDate(new Date()), true); |
||||
|
|
||||
|
assert.equal(t.isError(null), false); |
||||
|
assert.equal(t.isError({ err: true }), false); |
||||
|
assert.equal(t.isError(new Error()), true); |
||||
|
|
||||
|
assert.equal(t.isFunction(null), false); |
||||
|
assert.equal(t.isFunction({ }), false); |
||||
|
assert.equal(t.isFunction(function() {}), true); |
||||
|
|
||||
|
assert.equal(t.isPrimitive(null), true); |
||||
|
assert.equal(t.isPrimitive(''), true); |
||||
|
assert.equal(t.isPrimitive(0), true); |
||||
|
assert.equal(t.isPrimitive(new Date()), false); |
||||
|
|
||||
|
assert.equal(t.isBuffer(null), false); |
||||
|
assert.equal(t.isBuffer({}), false); |
||||
|
assert.equal(t.isBuffer(new Buffer(0)), true); |
@ -0,0 +1,13 @@ |
|||||
|
Copyright (c) 2018 Mike Diarmid (Salakar) <mike.diarmid@gmail.com> |
||||
|
|
||||
|
Licensed under the Apache License, Version 2.0 (the "License"); |
||||
|
you may not use this library 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. |
@ -0,0 +1,362 @@ |
|||||
|
<p align="center"> |
||||
|
<a href="https://invertase.io"> |
||||
|
<img src="https://static.invertase.io/assets/invertase-logo-small.png"><br/> |
||||
|
</a> |
||||
|
<h2 align="center">Denque</h2> |
||||
|
</p> |
||||
|
|
||||
|
<p align="center"> |
||||
|
<a href="https://www.npmjs.com/package/denque"><img src="https://img.shields.io/npm/dm/denque.svg?style=flat-square" alt="NPM downloads"></a> |
||||
|
<a href="https://www.npmjs.com/package/denque"><img src="https://img.shields.io/npm/v/denque.svg?style=flat-square" alt="NPM version"></a> |
||||
|
<a href="https://travis-ci.org/Salakar/denque"><img src="https://travis-ci.org/invertase/denque.svg" alt="Build version"></a> |
||||
|
<a href="https://coveralls.io/github/invertase/denque?branch=master"><img src="https://coveralls.io/repos/github/invertase/denque/badge.svg?branch=master" alt="Build version"></a> |
||||
|
<a href="/LICENSE"><img src="https://img.shields.io/npm/l/denque.svg?style=flat-square" alt="License"></a> |
||||
|
<a href="https://discord.gg/C9aK28N"><img src="https://img.shields.io/discord/295953187817521152.svg?logo=discord&style=flat-square&colorA=7289da&label=discord" alt="Chat"></a> |
||||
|
<a href="https://twitter.com/invertaseio"><img src="https://img.shields.io/twitter/follow/invertaseio.svg?style=social&label=Follow" alt="Follow on Twitter"></a> |
||||
|
</p> |
||||
|
|
||||
|
Extremely fast and lightweight [double-ended queue](http://en.wikipedia.org/wiki/Double-ended_queue) implementation with zero dependencies. |
||||
|
|
||||
|
Double-ended queues can also be used as a: |
||||
|
|
||||
|
- [Stack](http://en.wikipedia.org/wiki/Stack_\(abstract_data_type\)) |
||||
|
- [Queue](http://en.wikipedia.org/wiki/Queue_\(data_structure\)) |
||||
|
|
||||
|
This implementation is currently the fastest available, even faster than `double-ended-queue`, see the [benchmarks](#benchmarks) |
||||
|
|
||||
|
Every queue operation is done at a constant `O(1)` - including random access from `.peekAt(index)`. |
||||
|
|
||||
|
**Works on all node versions >= v0.10** |
||||
|
|
||||
|
# Quick Start |
||||
|
|
||||
|
npm install denque |
||||
|
|
||||
|
```js |
||||
|
const Denque = require("denque"); |
||||
|
|
||||
|
const denque = new Denque([1,2,3,4]); |
||||
|
denque.shift(); // 1 |
||||
|
denque.pop(); // 4 |
||||
|
``` |
||||
|
|
||||
|
|
||||
|
# API |
||||
|
|
||||
|
- [`new Denque()`](#new-denque---denque) |
||||
|
- [`new Denque(Array items)`](#new-denquearray-items---denque) |
||||
|
- [`push(item)`](#pushitem---int) |
||||
|
- [`unshift(item)`](#unshiftitem---int) |
||||
|
- [`pop()`](#pop---dynamic) |
||||
|
- [`shift()`](#shift---dynamic) |
||||
|
- [`toArray()`](#toarray---array) |
||||
|
- [`peekBack()`](#peekback---dynamic) |
||||
|
- [`peekFront()`](#peekfront---dynamic) |
||||
|
- [`peekAt(int index)`](#peekAtint-index---dynamic) |
||||
|
- [`remove(int index, int count)`](#remove) |
||||
|
- [`removeOne(int index)`](#removeOne) |
||||
|
- [`splice(int index, int count, item1, item2, ...)`](#splice) |
||||
|
- [`isEmpty()`](#isempty---boolean) |
||||
|
- [`clear()`](#clear---void) |
||||
|
|
||||
|
#### `new Denque()` -> `Denque` |
||||
|
|
||||
|
Creates an empty double-ended queue with initial capacity of 4. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque(); |
||||
|
denque.push(1); |
||||
|
denque.push(2); |
||||
|
denque.push(3); |
||||
|
denque.shift(); //1 |
||||
|
denque.pop(); //3 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `new Denque(Array items)` -> `Denque` |
||||
|
|
||||
|
Creates a double-ended queue from `items`. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3,4]); |
||||
|
denque.shift(); // 1 |
||||
|
denque.pop(); // 4 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
|
||||
|
#### `push(item)` -> `int` |
||||
|
|
||||
|
Push an item to the back of this queue. Returns the amount of items currently in the queue after the operation. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque(); |
||||
|
denque.push(1); |
||||
|
denque.pop(); // 1 |
||||
|
denque.push(2); |
||||
|
denque.push(3); |
||||
|
denque.shift(); // 2 |
||||
|
denque.shift(); // 3 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `unshift(item)` -> `int` |
||||
|
|
||||
|
Unshift an item to the front of this queue. Returns the amount of items currently in the queue after the operation. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([2,3]); |
||||
|
denque.unshift(1); |
||||
|
denque.toString(); // "1,2,3" |
||||
|
denque.unshift(-2); |
||||
|
denque.toString(); // "-2,-1,0,1,2,3" |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
|
||||
|
#### `pop()` -> `dynamic` |
||||
|
|
||||
|
Pop off the item at the back of this queue. |
||||
|
|
||||
|
Note: The item will be removed from the queue. If you simply want to see what's at the back of the queue use [`peekBack()`](#peekback---dynamic) or [`.peekAt(-1)`](#peekAtint-index---dynamic). |
||||
|
|
||||
|
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `pop()` return value - |
||||
|
check the queue `.length` before popping. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.pop(); // 3 |
||||
|
denque.pop(); // 2 |
||||
|
denque.pop(); // 1 |
||||
|
denque.pop(); // undefined |
||||
|
``` |
||||
|
|
||||
|
**Aliases:** `removeBack` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `shift()` -> `dynamic` |
||||
|
|
||||
|
Shifts off the item at the front of this queue. |
||||
|
|
||||
|
Note: The item will be removed from the queue. If you simply want to see what's at the front of the queue use [`peekFront()`](#peekfront---dynamic) or [`.peekAt(0)`](#peekAtint-index---dynamic). |
||||
|
|
||||
|
If the queue is empty, `undefined` is returned. If you need to differentiate between `undefined` values in the queue and `shift()` return value - |
||||
|
check the queue `.length` before shifting. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.shift(); // 1 |
||||
|
denque.shift(); // 2 |
||||
|
denque.shift(); // 3 |
||||
|
denque.shift(); // undefined |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `toArray()` -> `Array` |
||||
|
|
||||
|
Returns the items in the queue as an array. Starting from the item in the front of the queue and ending to the item at the back of the queue. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.push(4); |
||||
|
denque.unshift(0); |
||||
|
denque.toArray(); // [0,1,2,3,4] |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `peekBack()` -> `dynamic` |
||||
|
|
||||
|
Returns the item that is at the back of this queue without removing it. |
||||
|
|
||||
|
If the queue is empty, `undefined` is returned. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.push(4); |
||||
|
denque.peekBack(); // 4 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `peekFront()` -> `dynamic` |
||||
|
|
||||
|
Returns the item that is at the front of this queue without removing it. |
||||
|
|
||||
|
If the queue is empty, `undefined` is returned. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.push(4); |
||||
|
denque.peekFront(); // 1 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `peekAt(int index)` -> `dynamic` |
||||
|
|
||||
|
Returns the item that is at the given `index` of this queue without removing it. |
||||
|
|
||||
|
The index is zero-based, so `.peekAt(0)` will return the item that is at the front, `.peekAt(1)` will return |
||||
|
the item that comes after and so on. |
||||
|
|
||||
|
The index can be negative to read items at the back of the queue. `.peekAt(-1)` returns the item that is at the back of the queue, |
||||
|
`.peekAt(-2)` will return the item that comes before and so on. |
||||
|
|
||||
|
Returns `undefined` if `index` is not a valid index into the queue. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.peekAt(0); //1 |
||||
|
denque.peekAt(1); //2 |
||||
|
denque.peekAt(2); //3 |
||||
|
|
||||
|
denque.peekAt(-1); // 3 |
||||
|
denque.peekAt(-2); // 2 |
||||
|
denque.peekAt(-3); // 1 |
||||
|
``` |
||||
|
|
||||
|
**Note**: The implementation has O(1) random access using `.peekAt()`. |
||||
|
|
||||
|
**Aliases:** `get` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `remove(int index, int count)` -> `array` |
||||
|
|
||||
|
Remove number of items from the specified index from the list. |
||||
|
|
||||
|
Returns array of removed items. |
||||
|
|
||||
|
Returns undefined if the list is empty. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3,4,5,6,7]); |
||||
|
denque.remove(0,3); //[1,2,3] |
||||
|
denque.remove(1,2); //[5,6] |
||||
|
var denque1 = new Denque([1,2,3,4,5,6,7]); |
||||
|
denque1.remove(4, 100); //[5,6,7] |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `removeOne(int index)` -> `dynamic` |
||||
|
|
||||
|
Remove and return the item at the specified index from the list. |
||||
|
|
||||
|
Returns undefined if the list is empty. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3,4,5,6,7]); |
||||
|
denque.removeOne(4); // 5 |
||||
|
denque.removeOne(3); // 4 |
||||
|
denque1.removeOne(1); // 2 |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `splice(int index, int count, item1, item2, ...)` -> `array` |
||||
|
|
||||
|
Native splice implementation. |
||||
|
|
||||
|
Remove number of items from the specified index from the list and/or add new elements. |
||||
|
|
||||
|
Returns array of removed items or empty array if count == 0. |
||||
|
|
||||
|
Returns undefined if the list is empty. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3,4,5,6,7]); |
||||
|
denque.splice(denque.length, 0, 8, 9, 10); // [] |
||||
|
denque.toArray() // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] |
||||
|
denque.splice(3, 3, 44, 55, 66); // [4,5,6] |
||||
|
denque.splice(5,4, 666,667,668,669); // [ 66, 7, 8, 9 ] |
||||
|
denque.toArray() // [ 1, 2, 3, 44, 55, 666, 667, 668, 669, 10 ] |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `isEmpty()` -> `boolean` |
||||
|
|
||||
|
Return `true` if this queue is empty, `false` otherwise. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque(); |
||||
|
denque.isEmpty(); // true |
||||
|
denque.push(1); |
||||
|
denque.isEmpty(); // false |
||||
|
``` |
||||
|
|
||||
|
<hr> |
||||
|
|
||||
|
#### `clear()` -> `void` |
||||
|
|
||||
|
Remove all items from this queue. Does not change the queue's capacity. |
||||
|
|
||||
|
```js |
||||
|
var denque = new Denque([1,2,3]); |
||||
|
denque.toString(); // "1,2,3" |
||||
|
denque.clear(); |
||||
|
denque.toString(); // "" |
||||
|
``` |
||||
|
<hr> |
||||
|
|
||||
|
|
||||
|
## Benchmarks |
||||
|
|
||||
|
#### Platform info: |
||||
|
``` |
||||
|
Darwin 17.0.0 x64 |
||||
|
Node.JS 9.4.0 |
||||
|
V8 6.2.414.46-node.17 |
||||
|
Intel(R) Core(TM) i7-7700K CPU @ 4.20GHz × 8 |
||||
|
``` |
||||
|
|
||||
|
#### 1000 items in queue |
||||
|
|
||||
|
(3 x shift + 3 x push ops per 'op') |
||||
|
|
||||
|
denque x 64,365,425 ops/sec ±0.69% (92 runs sampled) |
||||
|
double-ended-queue x 26,646,882 ops/sec ±0.47% (94 runs sampled) |
||||
|
|
||||
|
#### 2 million items in queue |
||||
|
|
||||
|
(3 x shift + 3 x push ops per 'op') |
||||
|
|
||||
|
denque x 61,994,249 ops/sec ±0.26% (95 runs sampled) |
||||
|
double-ended-queue x 26,363,500 ops/sec ±0.42% (91 runs sampled) |
||||
|
|
||||
|
#### Splice |
||||
|
|
||||
|
(1 x splice per 'op') - initial size of 100,000 items |
||||
|
|
||||
|
denque.splice x 925,749 ops/sec ±22.29% (77 runs sampled) |
||||
|
native array splice x 7,777 ops/sec ±8.35% (50 runs sampled) |
||||
|
|
||||
|
#### Remove |
||||
|
|
||||
|
(1 x remove + 10 x push per 'op') - initial size of 100,000 items |
||||
|
|
||||
|
denque.remove x 2,635,275 ops/sec ±0.37% (95 runs sampled) |
||||
|
native array splice - Fails to complete: "JavaScript heap out of memory" |
||||
|
|
||||
|
#### Remove One |
||||
|
|
||||
|
(1 x removeOne + 10 x push per 'op') - initial size of 100,000 items |
||||
|
|
||||
|
denque.removeOne x 1,088,240 ops/sec ±0.21% (93 runs sampled) |
||||
|
native array splice x 5,300 ops/sec ±0.41% (96 runs sampled) |
||||
|
|
||||
|
--- |
||||
|
|
||||
|
Built and maintained with 💛 by [Invertase](https://invertase.io). |
||||
|
|
||||
|
- [💼 Hire Us](https://invertase.io/hire-us) |
||||
|
- [☕️ Sponsor Us](https://opencollective.com/react-native-firebase) |
||||
|
- [👩💻 Work With Us](https://invertase.io/jobs) |
@ -0,0 +1,26 @@ |
|||||
|
declare class Denque<T = any> { |
||||
|
constructor(); |
||||
|
constructor(array: T[]); |
||||
|
|
||||
|
push(item: T): number; |
||||
|
unshift(item: T): number; |
||||
|
pop(): T | undefined; |
||||
|
removeBack(): T | undefined; |
||||
|
shift(): T | undefined; |
||||
|
peekBack(): T | undefined; |
||||
|
peekFront(): T | undefined; |
||||
|
peekAt(index: number): T | undefined; |
||||
|
get(index: number): T | undefined; |
||||
|
remove(index: number, count: number): T[]; |
||||
|
removeOne(index: number): T | undefined; |
||||
|
splice(index: number, count: number, ...item: T[]): T[] | undefined; |
||||
|
isEmpty(): boolean; |
||||
|
clear(): void; |
||||
|
|
||||
|
toString(): string; |
||||
|
toArray(): T[]; |
||||
|
|
||||
|
length: number; |
||||
|
} |
||||
|
|
||||
|
export = Denque; |
@ -0,0 +1,437 @@ |
|||||
|
'use strict'; |
||||
|
|
||||
|
/** |
||||
|
* Custom implementation of a double ended queue. |
||||
|
*/ |
||||
|
function Denque(array) { |
||||
|
this._head = 0; |
||||
|
this._tail = 0; |
||||
|
this._capacityMask = 0x3; |
||||
|
this._list = new Array(4); |
||||
|
if (Array.isArray(array)) { |
||||
|
this._fromArray(array); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
/** |
||||
|
* ------------- |
||||
|
* PUBLIC API |
||||
|
* ------------- |
||||
|
*/ |
||||
|
|
||||
|
/** |
||||
|
* Returns the item at the specified index from the list. |
||||
|
* 0 is the first element, 1 is the second, and so on... |
||||
|
* Elements at negative values are that many from the end: -1 is one before the end |
||||
|
* (the last element), -2 is two before the end (one before last), etc. |
||||
|
* @param index |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.peekAt = function peekAt(index) { |
||||
|
var i = index; |
||||
|
// expect a number or return undefined
|
||||
|
if ((i !== (i | 0))) { |
||||
|
return void 0; |
||||
|
} |
||||
|
var len = this.size(); |
||||
|
if (i >= len || i < -len) return undefined; |
||||
|
if (i < 0) i += len; |
||||
|
i = (this._head + i) & this._capacityMask; |
||||
|
return this._list[i]; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Alias for peakAt() |
||||
|
* @param i |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.get = function get(i) { |
||||
|
return this.peekAt(i); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the first item in the list without removing it. |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.peek = function peek() { |
||||
|
if (this._head === this._tail) return undefined; |
||||
|
return this._list[this._head]; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Alias for peek() |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.peekFront = function peekFront() { |
||||
|
return this.peek(); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the item that is at the back of the queue without removing it. |
||||
|
* Uses peekAt(-1) |
||||
|
*/ |
||||
|
Denque.prototype.peekBack = function peekBack() { |
||||
|
return this.peekAt(-1); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns the current length of the queue |
||||
|
* @return {Number} |
||||
|
*/ |
||||
|
Object.defineProperty(Denque.prototype, 'length', { |
||||
|
get: function length() { |
||||
|
return this.size(); |
||||
|
} |
||||
|
}); |
||||
|
|
||||
|
/** |
||||
|
* Return the number of items on the list, or 0 if empty. |
||||
|
* @returns {number} |
||||
|
*/ |
||||
|
Denque.prototype.size = function size() { |
||||
|
if (this._head === this._tail) return 0; |
||||
|
if (this._head < this._tail) return this._tail - this._head; |
||||
|
else return this._capacityMask + 1 - (this._head - this._tail); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Add an item at the beginning of the list. |
||||
|
* @param item |
||||
|
*/ |
||||
|
Denque.prototype.unshift = function unshift(item) { |
||||
|
if (item === undefined) return this.size(); |
||||
|
var len = this._list.length; |
||||
|
this._head = (this._head - 1 + len) & this._capacityMask; |
||||
|
this._list[this._head] = item; |
||||
|
if (this._tail === this._head) this._growArray(); |
||||
|
if (this._head < this._tail) return this._tail - this._head; |
||||
|
else return this._capacityMask + 1 - (this._head - this._tail); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Remove and return the first item on the list, |
||||
|
* Returns undefined if the list is empty. |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.shift = function shift() { |
||||
|
var head = this._head; |
||||
|
if (head === this._tail) return undefined; |
||||
|
var item = this._list[head]; |
||||
|
this._list[head] = undefined; |
||||
|
this._head = (head + 1) & this._capacityMask; |
||||
|
if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); |
||||
|
return item; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Add an item to the bottom of the list. |
||||
|
* @param item |
||||
|
*/ |
||||
|
Denque.prototype.push = function push(item) { |
||||
|
if (item === undefined) return this.size(); |
||||
|
var tail = this._tail; |
||||
|
this._list[tail] = item; |
||||
|
this._tail = (tail + 1) & this._capacityMask; |
||||
|
if (this._tail === this._head) { |
||||
|
this._growArray(); |
||||
|
} |
||||
|
|
||||
|
if (this._head < this._tail) return this._tail - this._head; |
||||
|
else return this._capacityMask + 1 - (this._head - this._tail); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Remove and return the last item on the list. |
||||
|
* Returns undefined if the list is empty. |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.pop = function pop() { |
||||
|
var tail = this._tail; |
||||
|
if (tail === this._head) return undefined; |
||||
|
var len = this._list.length; |
||||
|
this._tail = (tail - 1 + len) & this._capacityMask; |
||||
|
var item = this._list[this._tail]; |
||||
|
this._list[this._tail] = undefined; |
||||
|
if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); |
||||
|
return item; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Remove and return the item at the specified index from the list. |
||||
|
* Returns undefined if the list is empty. |
||||
|
* @param index |
||||
|
* @returns {*} |
||||
|
*/ |
||||
|
Denque.prototype.removeOne = function removeOne(index) { |
||||
|
var i = index; |
||||
|
// expect a number or return undefined
|
||||
|
if ((i !== (i | 0))) { |
||||
|
return void 0; |
||||
|
} |
||||
|
if (this._head === this._tail) return void 0; |
||||
|
var size = this.size(); |
||||
|
var len = this._list.length; |
||||
|
if (i >= size || i < -size) return void 0; |
||||
|
if (i < 0) i += size; |
||||
|
i = (this._head + i) & this._capacityMask; |
||||
|
var item = this._list[i]; |
||||
|
var k; |
||||
|
if (index < size / 2) { |
||||
|
for (k = index; k > 0; k--) { |
||||
|
this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; |
||||
|
} |
||||
|
this._list[i] = void 0; |
||||
|
this._head = (this._head + 1 + len) & this._capacityMask; |
||||
|
} else { |
||||
|
for (k = size - 1 - index; k > 0; k--) { |
||||
|
this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; |
||||
|
} |
||||
|
this._list[i] = void 0; |
||||
|
this._tail = (this._tail - 1 + len) & this._capacityMask; |
||||
|
} |
||||
|
return item; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Remove number of items from the specified index from the list. |
||||
|
* Returns array of removed items. |
||||
|
* Returns undefined if the list is empty. |
||||
|
* @param index |
||||
|
* @param count |
||||
|
* @returns {array} |
||||
|
*/ |
||||
|
Denque.prototype.remove = function remove(index, count) { |
||||
|
var i = index; |
||||
|
var removed; |
||||
|
var del_count = count; |
||||
|
// expect a number or return undefined
|
||||
|
if ((i !== (i | 0))) { |
||||
|
return void 0; |
||||
|
} |
||||
|
if (this._head === this._tail) return void 0; |
||||
|
var size = this.size(); |
||||
|
var len = this._list.length; |
||||
|
if (i >= size || i < -size || count < 1) return void 0; |
||||
|
if (i < 0) i += size; |
||||
|
if (count === 1 || !count) { |
||||
|
removed = new Array(1); |
||||
|
removed[0] = this.removeOne(i); |
||||
|
return removed; |
||||
|
} |
||||
|
if (i === 0 && i + count >= size) { |
||||
|
removed = this.toArray(); |
||||
|
this.clear(); |
||||
|
return removed; |
||||
|
} |
||||
|
if (i + count > size) count = size - i; |
||||
|
var k; |
||||
|
removed = new Array(count); |
||||
|
for (k = 0; k < count; k++) { |
||||
|
removed[k] = this._list[(this._head + i + k) & this._capacityMask]; |
||||
|
} |
||||
|
i = (this._head + i) & this._capacityMask; |
||||
|
if (index + count === size) { |
||||
|
this._tail = (this._tail - count + len) & this._capacityMask; |
||||
|
for (k = count; k > 0; k--) { |
||||
|
this._list[i = (i + 1 + len) & this._capacityMask] = void 0; |
||||
|
} |
||||
|
return removed; |
||||
|
} |
||||
|
if (index === 0) { |
||||
|
this._head = (this._head + count + len) & this._capacityMask; |
||||
|
for (k = count - 1; k > 0; k--) { |
||||
|
this._list[i = (i + 1 + len) & this._capacityMask] = void 0; |
||||
|
} |
||||
|
return removed; |
||||
|
} |
||||
|
if (i < size / 2) { |
||||
|
this._head = (this._head + index + count + len) & this._capacityMask; |
||||
|
for (k = index; k > 0; k--) { |
||||
|
this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); |
||||
|
} |
||||
|
i = (this._head - 1 + len) & this._capacityMask; |
||||
|
while (del_count > 0) { |
||||
|
this._list[i = (i - 1 + len) & this._capacityMask] = void 0; |
||||
|
del_count--; |
||||
|
} |
||||
|
if (index < 0) this._tail = i; |
||||
|
} else { |
||||
|
this._tail = i; |
||||
|
i = (i + count + len) & this._capacityMask; |
||||
|
for (k = size - (count + index); k > 0; k--) { |
||||
|
this.push(this._list[i++]); |
||||
|
} |
||||
|
i = this._tail; |
||||
|
while (del_count > 0) { |
||||
|
this._list[i = (i + 1 + len) & this._capacityMask] = void 0; |
||||
|
del_count--; |
||||
|
} |
||||
|
} |
||||
|
if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); |
||||
|
return removed; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Native splice implementation. |
||||
|
* Remove number of items from the specified index from the list and/or add new elements. |
||||
|
* Returns array of removed items or empty array if count == 0. |
||||
|
* Returns undefined if the list is empty. |
||||
|
* |
||||
|
* @param index |
||||
|
* @param count |
||||
|
* @param {...*} [elements] |
||||
|
* @returns {array} |
||||
|
*/ |
||||
|
Denque.prototype.splice = function splice(index, count) { |
||||
|
var i = index; |
||||
|
// expect a number or return undefined
|
||||
|
if ((i !== (i | 0))) { |
||||
|
return void 0; |
||||
|
} |
||||
|
var size = this.size(); |
||||
|
if (i < 0) i += size; |
||||
|
if (i > size) return void 0; |
||||
|
if (arguments.length > 2) { |
||||
|
var k; |
||||
|
var temp; |
||||
|
var removed; |
||||
|
var arg_len = arguments.length; |
||||
|
var len = this._list.length; |
||||
|
var arguments_index = 2; |
||||
|
if (!size || i < size / 2) { |
||||
|
temp = new Array(i); |
||||
|
for (k = 0; k < i; k++) { |
||||
|
temp[k] = this._list[(this._head + k) & this._capacityMask]; |
||||
|
} |
||||
|
if (count === 0) { |
||||
|
removed = []; |
||||
|
if (i > 0) { |
||||
|
this._head = (this._head + i + len) & this._capacityMask; |
||||
|
} |
||||
|
} else { |
||||
|
removed = this.remove(i, count); |
||||
|
this._head = (this._head + i + len) & this._capacityMask; |
||||
|
} |
||||
|
while (arg_len > arguments_index) { |
||||
|
this.unshift(arguments[--arg_len]); |
||||
|
} |
||||
|
for (k = i; k > 0; k--) { |
||||
|
this.unshift(temp[k - 1]); |
||||
|
} |
||||
|
} else { |
||||
|
temp = new Array(size - (i + count)); |
||||
|
var leng = temp.length; |
||||
|
for (k = 0; k < leng; k++) { |
||||
|
temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; |
||||
|
} |
||||
|
if (count === 0) { |
||||
|
removed = []; |
||||
|
if (i != size) { |
||||
|
this._tail = (this._head + i + len) & this._capacityMask; |
||||
|
} |
||||
|
} else { |
||||
|
removed = this.remove(i, count); |
||||
|
this._tail = (this._tail - leng + len) & this._capacityMask; |
||||
|
} |
||||
|
while (arguments_index < arg_len) { |
||||
|
this.push(arguments[arguments_index++]); |
||||
|
} |
||||
|
for (k = 0; k < leng; k++) { |
||||
|
this.push(temp[k]); |
||||
|
} |
||||
|
} |
||||
|
return removed; |
||||
|
} else { |
||||
|
return this.remove(i, count); |
||||
|
} |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Soft clear - does not reset capacity. |
||||
|
*/ |
||||
|
Denque.prototype.clear = function clear() { |
||||
|
this._head = 0; |
||||
|
this._tail = 0; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns true or false whether the list is empty. |
||||
|
* @returns {boolean} |
||||
|
*/ |
||||
|
Denque.prototype.isEmpty = function isEmpty() { |
||||
|
return this._head === this._tail; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Returns an array of all queue items. |
||||
|
* @returns {Array} |
||||
|
*/ |
||||
|
Denque.prototype.toArray = function toArray() { |
||||
|
return this._copyArray(false); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* ------------- |
||||
|
* INTERNALS |
||||
|
* ------------- |
||||
|
*/ |
||||
|
|
||||
|
/** |
||||
|
* Fills the queue with items from an array |
||||
|
* For use in the constructor |
||||
|
* @param array |
||||
|
* @private |
||||
|
*/ |
||||
|
Denque.prototype._fromArray = function _fromArray(array) { |
||||
|
for (var i = 0; i < array.length; i++) this.push(array[i]); |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* |
||||
|
* @param fullCopy |
||||
|
* @returns {Array} |
||||
|
* @private |
||||
|
*/ |
||||
|
Denque.prototype._copyArray = function _copyArray(fullCopy) { |
||||
|
var newArray = []; |
||||
|
var list = this._list; |
||||
|
var len = list.length; |
||||
|
var i; |
||||
|
if (fullCopy || this._head > this._tail) { |
||||
|
for (i = this._head; i < len; i++) newArray.push(list[i]); |
||||
|
for (i = 0; i < this._tail; i++) newArray.push(list[i]); |
||||
|
} else { |
||||
|
for (i = this._head; i < this._tail; i++) newArray.push(list[i]); |
||||
|
} |
||||
|
return newArray; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Grows the internal list array. |
||||
|
* @private |
||||
|
*/ |
||||
|
Denque.prototype._growArray = function _growArray() { |
||||
|
if (this._head) { |
||||
|
// copy existing data, head to end, then beginning to tail.
|
||||
|
this._list = this._copyArray(true); |
||||
|
this._head = 0; |
||||
|
} |
||||
|
|
||||
|
// head is at 0 and array is now full, safe to extend
|
||||
|
this._tail = this._list.length; |
||||
|
|
||||
|
this._list.length *= 2; |
||||
|
this._capacityMask = (this._capacityMask << 1) | 1; |
||||
|
}; |
||||
|
|
||||
|
/** |
||||
|
* Shrinks the internal list array. |
||||
|
* @private |
||||
|
*/ |
||||
|
Denque.prototype._shrinkArray = function _shrinkArray() { |
||||
|
this._list.length >>>= 1; |
||||
|
this._capacityMask >>>= 1; |
||||
|
}; |
||||
|
|
||||
|
|
||||
|
module.exports = Denque; |
@ -0,0 +1,117 @@ |
|||||
|
{ |
||||
|
"_args": [ |
||||
|
[ |
||||
|
"denque@^1.4.1", |
||||
|
"/home/art/Documents/API-REST-Etudiants/api/node_modules/mongodb" |
||||
|
] |
||||
|
], |
||||
|
"_from": "denque@>=1.4.1 <2.0.0", |
||||
|
"_hasShrinkwrap": false, |
||||
|
"_id": "denque@1.4.1", |
||||
|
"_inCache": true, |
||||
|
"_installable": true, |
||||
|
"_location": "/denque", |
||||
|
"_nodeVersion": "10.8.0", |
||||
|
"_npmOperationalInternal": { |
||||
|
"host": "s3://npm-registry-packages", |
||||
|
"tmp": "tmp/denque_1.4.1_1554250885281_0.0009501203863016006" |
||||
|
}, |
||||
|
"_npmUser": { |
||||
|
"email": "mike.diarmid@gmail.com", |
||||
|
"name": "salakar" |
||||
|
}, |
||||
|
"_npmVersion": "6.2.0", |
||||
|
"_phantomChildren": {}, |
||||
|
"_requested": { |
||||
|
"name": "denque", |
||||
|
"raw": "denque@^1.4.1", |
||||
|
"rawSpec": "^1.4.1", |
||||
|
"scope": null, |
||||
|
"spec": ">=1.4.1 <2.0.0", |
||||
|
"type": "range" |
||||
|
}, |
||||
|
"_requiredBy": [ |
||||
|
"/mongodb" |
||||
|
], |
||||
|
"_resolved": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", |
||||
|
"_shasum": "6744ff7641c148c3f8a69c307e51235c1f4a37cf", |
||||
|
"_shrinkwrap": null, |
||||
|
"_spec": "denque@^1.4.1", |
||||
|
"_where": "/home/art/Documents/API-REST-Etudiants/api/node_modules/mongodb", |
||||
|
"author": { |
||||
|
"email": "oss@invertase.io", |
||||
|
"name": "Invertase", |
||||
|
"url": "http://github.com/invertase/" |
||||
|
}, |
||||
|
"bugs": { |
||||
|
"url": "https://github.com/invertase/denque/issues" |
||||
|
}, |
||||
|
"contributors": [ |
||||
|
{ |
||||
|
"name": "Mike Diarmid", |
||||
|
"email": "mike@invertase.io", |
||||
|
"url": "Salakar" |
||||
|
} |
||||
|
], |
||||
|
"dependencies": {}, |
||||
|
"description": "The fastest javascript implementation of a double-ended queue. Maintains compatability with deque.", |
||||
|
"devDependencies": { |
||||
|
"benchmark": "^2.1.4", |
||||
|
"coveralls": "^2.13.3", |
||||
|
"double-ended-queue": "^2.1.0-0", |
||||
|
"istanbul": "^0.4.5", |
||||
|
"mocha": "^3.5.3", |
||||
|
"typescript": "^3.4.1" |
||||
|
}, |
||||
|
"directories": {}, |
||||
|
"dist": { |
||||
|
"fileCount": 5, |
||||
|
"integrity": "sha512-OfzPuSZKGcgr96rf1oODnfjqBFmr1DVoc/TrItj3Ohe0Ah1C5WX5Baquw/9U9KovnQ88EqmJbD66rKYUQYN1tQ==", |
||||
|
"npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJco/yGCRA9TVsSAnZWagAA53YP/27mhVsPmYA19Ul/zVI5\nNU5yt5glUVpFRDC4lyBk5I5PTRhwYDd8btnOUiRdjMhTRk9m0uS3nTobwnUW\nnydvNUXe/TvSAqeh6AxXD4pdRpj35aYvYB/OL9EcGm2RIOeEDlaENB9sCKMU\nTW5VE5PvbpNeHjwmYYVU3rgHzjVh0ZqSUVEnSIiysSl7dicGNi/73yTvJcvv\nzgBj9OLotLjX7diBrODLWpKlHszyJo0dhNoYPYIeKsUqU7Y+weRQIHHcuNZL\naOrb5INdTtAwEfJBaspl87pzBUNZKJhIyXEFoQiQz1he7UNSfyq5lXhziCnh\nHDRYJlEqVZyFkHmVX1NZ+eb79MewkFVYh/IRS2Ooxs0kFc2m2vw3B3mantsX\neqp7xmicEN9N7Fn1aj8IPkmwae2Jy/47IGsqV8KLAXkjnORahulBVJ8MJY+Q\nyOu/T/gGhsVHcMDCuZvjIqp+w7+6PGLCBj4LNAThNSsq1o2Udk1Yj/Ef/Nta\nHj3Sb4PJd2n6o9SCDe0FrBdBVQBu5xrwzxng6TToGyoBVIk8UZCAm2j9RPvQ\njBnDvKKFnH6fOefQ9LKztuwhbaRY2ZVBykRUesay2bdPWp42sHiJ9tJz1wl+\nv9Mi5yXWgdP5vLVAIkzM3vKD8FW0t7Jp5hxEnBT+ddm4L/F0UKkDtr6CLwOt\n1X2o\r\n=J2eQ\r\n-----END PGP SIGNATURE-----\r\n", |
||||
|
"shasum": "6744ff7641c148c3f8a69c307e51235c1f4a37cf", |
||||
|
"tarball": "https://registry.npmjs.org/denque/-/denque-1.4.1.tgz", |
||||
|
"unpackedSize": 23644 |
||||
|
}, |
||||
|
"engines": { |
||||
|
"node": ">=0.10" |
||||
|
}, |
||||
|
"gitHead": "05c0264385cce864bf5ac2811fad3e85a9f7fe37", |
||||
|
"homepage": "https://github.com/invertase/denque#readme", |
||||
|
"keywords": [ |
||||
|
"data-structure", |
||||
|
"data-structures", |
||||
|
"denque", |
||||
|
"deque", |
||||
|
"double", |
||||
|
"double-ended-queue", |
||||
|
"end", |
||||
|
"ended", |
||||
|
"queue" |
||||
|
], |
||||
|
"license": "Apache-2.0", |
||||
|
"main": "index.js", |
||||
|
"maintainers": [ |
||||
|
{ |
||||
|
"name": "salakar", |
||||
|
"email": "mike.diarmid@gmail.com" |
||||
|
} |
||||
|
], |
||||
|
"name": "denque", |
||||
|
"optionalDependencies": {}, |
||||
|
"readme": "ERROR: No README data found!", |
||||
|
"repository": { |
||||
|
"type": "git", |
||||
|
"url": "git+https://github.com/invertase/denque.git" |
||||
|
}, |
||||
|
"scripts": { |
||||
|
"benchmark_2mil": "node benchmark/two_million", |
||||
|
"benchmark_remove": "node benchmark/remove", |
||||
|
"benchmark_removeOne": "node benchmark/removeOne", |
||||
|
"benchmark_splice": "node benchmark/splice", |
||||
|
"benchmark_thousand": "node benchmark/thousand", |
||||
|
"coveralls": "cat ./coverage/lcov.info | coveralls", |
||||
|
"test": "istanbul cover --report lcov _mocha && npm run typescript", |
||||
|
"typescript": "tsc --project ./test/type/tsconfig.json" |
||||
|
}, |
||||
|
"version": "1.4.1" |
||||
|
} |
@ -0,0 +1 @@ |
|||||
|
node_modules |
Some files were not shown because too many files changed in this diff
Loading…
Reference in new issue