Initial work on the server

This commit is contained in:
Abhishek Das
2013-03-25 05:57:47 +05:30
parent 93400554fd
commit 0485272d93
626 changed files with 121311 additions and 1 deletions
+5
View File
@@ -0,0 +1,5 @@
*.un~
/node_modules
*.sublime-*
+5
View File
@@ -0,0 +1,5 @@
language: node_js
node_js:
- 0.4
- 0.6
- 0.8
+199
View File
@@ -0,0 +1,199 @@
# Changes
This file is a manually maintained list of changes for each release. Feel free
to add your changes here when sending pull requests. Also send corrections if
you spot any mistakes.
## v2.0.0-alpha6 (2013-01-31)
* Add supportBigNumbers option (#381, #382)
* Accept prebuilt Query object in connection.query
* Bug fixes
## v2.0.0-alpha5 (2012-12-03)
* Add mysql.escapeId to escape identifiers (closes #342)
* Allow custom escaping mode (config.queryFormat)
* Convert DATE columns to configured timezone instead of UTC (#332)
* Convert LONGLONG and NEWDECIMAL to numbers (#333)
* Fix Connection.escape() (fixes #330)
* Changed Readme ambiguity about custom type cast fallback
* Change typeCast to receive Connection instead of Connection.config.timezone
* Fix drain event having useless err parameter
* Add Connection.statistics() back from v0.9
* Add Connection.ping() back from v0.9
## v2.0.0-alpha4 (2012-10-03)
* Fix some OOB errors on resume()
* Fix quick pause() / resume() usage
* Properly parse host denied / similar errors
* Add Connection.ChangeUser functionality
* Make sure changeUser errors are fatal
* Enable formatting nested arrays for bulk inserts
* Add Connection.escape functionality
* Renamed 'close' to 'end' event
* Return parsed object instead of Buffer for GEOMETRY types
* Allow nestTables inline (using a string instead of a boolean)
* Check for ZEROFILL_FLAG and format number accordingly
* Add timezone support (default: local)
* Add custom typeCast functionality
* Export mysql column types
* Add connection flags functionality (#237)
* Exports drain event when queue finishes processing (#272, #271, #306)
## v2.0.0-alpha3 (2012-06-12)
* Implement support for `LOAD DATA LOCAL INFILE` queries (#182).
* Support OLD\_PASSWORD() accounts like 0.9.x did. You should still upgrade any
user accounts in your your MySQL user table that has short (16 byte) Password
values. Connecting to those accounts is not secure. (#204)
* Ignore function values when escaping objects, allows to use RowDataPacket
objects as query arguments. (Alex Gorbatchev, #213)
* Handle initial error packets from server such as `ER_HOST_NOT_PRIVILEGED`.
* Treat `utf8\_bin` as a String, not Buffer. (#214)
* Handle empty strings in first row column value. (#222)
* Honor Connection#nestTables setting for queries. (#221)
* Remove `CLIENT_INTERACTIVE` flag from config. Improves #225.
* Improve docs for connections settings.
* Implement url string support for Connection configs.
## v2.0.0-alpha2 (2012-05-31)
* Specify escaping before for NaN / Infinity (they are as unquoted constants).
* Support for unix domain socket connections (use: {socketPath: '...'}).
* Fix type casting for NULL values for Date/Number fields
* Add `fields` argument to `query()` as well as `'fields'` event. This is
similar to what was available in 0.9.x.
* Support connecting to the sphinx searchd daemon as well as MariaDB (#199).
* Implement long stack trace support, will be removed / disabled if the node
core ever supports it natively.
* Implement `nestTables` option for queries, allows fetching JOIN result sets
with overlapping column names.
* Fix ? placeholder mechanism for values containing '?' characters (#205).
* Detect when `connect()` is called more than once on a connection and provide
the user with a good error message for it (#204).
* Switch to `UTF8_GENERAL_CI` (previously `UTF8_UNICODE_CI`) as the default
charset for all connections to avoid strange MySQL performance issues (#200),
and also make the charset user configurable.
* Fix BLOB type casting for `TINY_BLOG`, `MEDIUM_BLOB` and `LONG_BLOB`.
* Add support for sending and receiving large (> 16 MB) packets.
## v2.0.0-alpha (2012-05-15)
This release is a rewrite. You should carefully test your application after
upgrading to avoid problems. This release features many improvements, most
importantly:
* ~5x faster than v0.9.x for parsing query results
* Support for pause() / resume() (for streaming rows)
* Support for multiple statement queries
* Support for stored procedures
* Support for transactions
* Support for binary columns (as blobs)
* Consistent & well documented error handling
* A new Connection class that has well defined semantics (unlike the old Client class).
* Convenient escaping of objects / arrays that allows for simpler query construction
* A significantly simpler code base
* Many bug fixes & other small improvements (Closed 62 out of 66 GitHub issues)
Below are a few notes on the upgrade process itself:
The first thing you will run into is that the old `Client` class is gone and
has been replaced with a less ambitious `Connection` class. So instead of
`mysql.createClient()`, you now have to:
```js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
});
connection.query('SELECT 1', function(err, rows) {
if (err) throw err;
console.log('Query result: ', rows);
});
connection.end();
```
The new `Connection` class does not try to handle re-connects, please study the
`Server disconnects` section in the new Readme.
Other than that, the interface has stayed very similar. Here are a few things
to check out so:
* BIGINT's are now cast into strings
* Binary data is now cast to buffers
* The `'row'` event on the `Query` object is now called `'result'` and will
also be emitted for queries that produce an OK/Error response.
* Error handling is consistently defined now, check the Readme
* Escaping has become more powerful which may break your code if you are
currently using objects to fill query placeholders.
* Connections can now be established explicitly again, so you may wish to do so
if you want to handle connection errors specifically.
That should be most of it, if you run into anything else, please send a patch
or open an issue to improve this document.
## v0.9.6 (2012-03-12)
* Escape array values so they produce sql arrays (Roger Castells, Colin Smith)
* docs: mention mysql transaction stop gap solution (Blake Miner)
* docs: Mention affectedRows in FAQ (Michael Baldwin)
## v0.9.5 (2011-11-26)
* Fix #142 Driver stalls upon reconnect attempt that's immediately closed
* Add travis build
* Switch to urun as a test runner
* Switch to utest for unit tests
* Remove fast-or-slow dependency for tests
* Split integration tests into individual files again
## v0.9.4 (2011-08-31)
* Expose package.json as `mysql.PACKAGE` (#104)
## v0.9.3 (2011-08-22)
* Set default `client.user` to root
* Fix #91: Client#format should not mutate params array
* Fix #94: TypeError in client.js
* Parse decimals as string (vadimg)
## v0.9.2 (2011-08-07)
* The underlaying socket connection is now managed implicitly rather than explicitly.
* Check the [upgrading guide][] for a full list of changes.
## v0.9.1 (2011-02-20)
* Fix issue #49 / `client.escape()` throwing exceptions on objects. (Nick Payne)
* Drop < v0.4.x compatibility. From now on you need node v0.4.x to use this module.
## Older releases
These releases were done before maintaining this file:
* [v0.9.0](https://github.com/felixge/node-mysql/compare/v0.8.0...v0.9.0)
(2011-01-04)
* [v0.8.0](https://github.com/felixge/node-mysql/compare/v0.7.0...v0.8.0)
(2010-10-30)
* [v0.7.0](https://github.com/felixge/node-mysql/compare/v0.6.0...v0.7.0)
(2010-10-14)
* [v0.6.0](https://github.com/felixge/node-mysql/compare/v0.5.0...v0.6.0)
(2010-09-28)
* [v0.5.0](https://github.com/felixge/node-mysql/compare/v0.4.0...v0.5.0)
(2010-09-17)
* [v0.4.0](https://github.com/felixge/node-mysql/compare/v0.3.0...v0.4.0)
(2010-09-02)
* [v0.3.0](https://github.com/felixge/node-mysql/compare/v0.2.0...v0.3.0)
(2010-08-25)
* [v0.2.0](https://github.com/felixge/node-mysql/compare/v0.1.0...v0.2.0)
(2010-08-22)
* [v0.1.0](https://github.com/felixge/node-mysql/commits/v0.1.0)
(2010-08-22)
Generated Vendored
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2012 Felix Geisendörfer (felix@debuggable.com) and 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.
+4
View File
@@ -0,0 +1,4 @@
test:
node test/run.js
.PHONY: test
+822
View File
@@ -0,0 +1,822 @@
# node-mysql
[![Build Status](https://secure.travis-ci.org/felixge/node-mysql.png)](http://travis-ci.org/felixge/node-mysql)
## Install
```bash
npm install mysql@2.0.0-alpha7
```
Despite the alpha tag, this is the recommended version for new applications.
For information about the previous 0.9.x releases, visit the [v0.9 branch][].
Sometimes I may also ask you to install the latest version from Github to check
if a bugfix is working. In this case, please do:
```
npm install git://github.com/felixge/node-mysql.git
```
[v0.9 branch]: https://github.com/felixge/node-mysql/tree/v0.9
## Introduction
This is a node.js driver for mysql. It is written in JavaScript, does not
require compiling, and is 100% MIT licensed.
Here is an example on how to use it:
```js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
```
From this example, you can learn the following:
* Every method you invoke on a connection is queued and executed in sequence.
* Closing the connection is done using `end()` which makes sure all remaining
queries are executed before sending a quit packet to the mysql server.
## Contributors
Thanks goes to the people who have contributed code to this module, see the
[GitHub Contributors page][].
[GitHub Contributors page]: https://github.com/felixge/node-mysql/graphs/contributors
Additionally I'd like to thank the following people:
* [Andrey Hristov][] (Oracle) - for helping me with protocol questions.
* [Ulf Wendel][] (Oracle) - for helping me with protocol questions.
[Ulf Wendel]: http://blog.ulf-wendel.de/
[Andrey Hristov]: http://andrey.hristov.com/
## Sponsors
The following companies have supported this project financially, allowing me to
spend more time on it (ordered by time of contribution):
* [Transloadit](http://transloadit.com) (my startup, we do file uploading &
video encoding as a service, check it out)
* [Joyent](http://www.joyent.com/)
* [pinkbike.com](http://pinkbike.com/)
* [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/vacancy/senior-web-technologist/))
* [Newscope](http://newscope.com/) (they are [hiring](http://www.newscope.com/stellenangebote))
If you are interested in sponsoring a day or more of my time, please
[get in touch][].
[get in touch]: http://felixge.de/consulting
## Community
If you'd like to discuss this module, or ask questions about it, please use one
of the following:
* **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql
* **IRC Channel**: #node.js (on freenode.net, I pay attention to any message
including the term `mysql`)
## Establishing connections
The recommended way to establish a connection is this:
```js
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'example.org',
user : 'bob',
password : 'secret',
});
connection.connect(function(err) {
// connected! (unless `err` is set)
});
```
However, a connection can also be implicitly established by invoking a query:
```js
var mysql = require('mysql');
var connection = mysql.createConnection(...);
connection.query('SELECT 1', function(err, rows) {
// connected! (unless `err` is set)
});
```
Depending on how you like to handle your errors, either method may be
appropriate. Any type of connection error (handshake or network) is considered
a fatal error, see the [Error Handling](#error-handling) section for more
information.
## Connection options
When establishing a connection, you can set the following options:
* `host`: The hostname of the database you are connecting to. (Default:
`localhost`)
* `port`: The port number to connect to. (Default: `3306`)
* `socketPath`: The path to a unix domain socket to connect to. When used `host`
and `port` are ignored.
* `user`: The MySQL user to authenticate as.
* `password`: The password of that MySQL user.
* `database`: Name of the database to use for this connection (Optional).
* `charset`: The charset for the connection. (Default: `'UTF8_GENERAL_CI'`)
* `timezone`: The timezone used to store local dates. (Default: `'local'`)
* `insecureAuth`: Allow connecting to MySQL instances that ask for the old
(insecure) authentication method. (Default: `false`)
* `typeCast`: Determines if column values should be converted to native
JavaScript types. (Default: `true`)
* `queryFormat`: A custom query format function. See [Custom format](#custom-format).
* `supportBigNumbers`: When dealing with big numbers in the database, you should enable this option.
* `debug`: Prints protocol details to stdout. (Default: `false`)
* `multipleStatements`: Allow multiple mysql statements per query. Be careful
with this, it exposes you to SQL injection attacks. (Default: `false`)
* `flags`: List of connection flags to use other than the default ones. It is
also possible to blacklist default ones. For more information, check [Connection Flags](#connection-flags).
In addition to passing these options as an object, you can also use a url
string. For example:
```js
var connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');
```
Note: The query values are first attempted to be parsed as JSON, and if that
fails assumed to be plaintext strings.
## Terminating connections
There are two ways to end a connection. Terminating a connection gracefully is
done by calling the `end()` method:
```js
connection.end(function(err) {
// The connection is terminated now
});
```
This will make sure all previously enqueued queries are still before sending a
`COM_QUIT` packet to the MySQL server. If a fatal error occurs before the
`COM_QUIT` packet can be sent, an `err` argument will be provided to the
callback, but the connection will be terminated regardless of that.
An alternative way to end the connection is to call the `destroy()` method.
This will cause an immediate termination of the underlying socket.
Additionally `destroy()` guarantees that no more events or callbacks will be
triggered for the connection.
```js
connection.destroy();
```
Unlike `end()` the `destroy()` method does not take a callback argument.
## Pooling connections
Connections can be pooled to ease sharing a single connection, or managing
multiple connections.
```js
var mysql = require('mysql');
var pool = mysql.createPool({
host : 'example.org',
user : 'bob',
password : 'secret'
});
pool.getConnection(function(err, connection) {
// connected! (unless `err` is set)
});
```
When you are done with a connection, just call `connection.end()` and the
connection will return to the pool, ready to be used again by someone else.
```js
var mysql = require('mysql');
var pool = mysql.createPool(...);
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT something FROM sometable', function(err, rows) {
// And done with the connection.
connection.end();
// Don't use the connection here, it has been returned to the pool.
});
});
```
If you would like to close the connection and remove it from the pool, use
`connection.destroy()` instead. The pool will create a new connection the next
time one is needed.
Connections are lazily created by the pool. If you configure the pool to allow
up to 100 connections, but only ever use 5 simultaneously, only 5 connections
will be made. Connections are also cycled round-robin style, with connections
being taken from the top of the pool and returning to the bottom.
## Pool options
Pools accept all the same options as a connection. When creating a new
connection, the options are simply passed to the connection constructor. In
addition to those options pools accept a few extras:
* `createConnection`: The function to use to create the connection. (Default:
`mysql.createConnection`)
* `waitForConnections`: Determines the pool's action when no connections are
available and the limit has been reached. If `true`, the pool will queue the
connection request and call it when one becomes available. If `false`, the
pool will immediately call back with an error. (Default: `true`)
* `connectionLimit`: The maximum number of connections to create at once.
(Default: `10`)
## Switching users / altering connection state
MySQL offers a changeUser command that allows you to alter the current user and
other aspects of the connection without shutting down the underlying socket:
```js
connection.changeUser({user : 'john'}, function(err) {
if (err) throw err;
});
```
The available options for this feature are:
* `user`: The name of the new user (defaults to the previous one).
* `password`: The password of the new user (defaults to the previous one).
* `charset`: The new charset (defaults to the previous one).
* `database`: The new database (defaults to the previous one).
A sometimes useful side effect of this functionality is that this function also
resets any connection state (variables, transactions, etc.).
Errors encountered during this operation are treated as fatal connection errors
by this module.
## Server disconnects
You may lose the connection to a MySQL server due to network problems, the
server timing you out, or the server crashing. All of these events are
considered fatal errors, and will have the `err.code =
'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section
for more information.
The best way to handle such unexpected disconnects is shown below:
```js
function handleDisconnect(connection) {
connection.on('error', function(err) {
if (!err.fatal) {
return;
}
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
throw err;
}
console.log('Re-connecting lost connection: ' + err.stack);
connection = mysql.createConnection(connection.config);
handleDisconnect(connection);
connection.connect();
});
}
handleDisconnect(connection);
```
As you can see in the example above, re-connecting a connection is done by
establishing a new connection. Once terminated, an existing connection object
cannot be re-connected by design.
With Pool, disconnected connections will be removed from the pool freeing up
space for a new connection to be created on the next getConnection call.
## Escaping query values
In order to avoid SQL Injection attacks, you should always escape any user
provided data before using it inside a SQL query. You can do so using the
`connection.escape()` method:
```js
var userId = 'some user provided value';
var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);
connection.query(sql, function(err, results) {
// ...
});
```
Alternatively, you can use `?` characters as placeholders for values you would
like to have escaped like this:
```js
connection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {
// ...
});
```
This looks similar to prepared statements in MySQL, however it really just uses
the same `connection.escape()` method internally.
Different value types are escaped differently, here is how:
* Numbers are left untouched
* Booleans are converted to `true` / `false` strings
* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings
* Buffers are converted to hex strings, e.g. `X'0fa5'`
* Strings are safely escaped
* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'`
* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a',
'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')`
* Objects are turned into `key = 'val'` pairs. Nested objects are cast to
strings.
* `undefined` / `null` are converted to `NULL`
* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying
to insert them as values will trigger MySQL errors until they implement
support.
If you paid attention, you may have noticed that this escaping allows you
to do neat things like this:
```js
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
```
If you feel the need to escape queries by yourself, you can also use the escaping
function directly:
```js
var query = "SELECT * FROM posts WHERE title=" + mysql.escape("Hello MySQL");
console.log(query); // SELECT * FROM posts WHERE title='Hello MySQL'
```
## Escaping query identifiers
If you can't trust an SQL identifier (database / table / column name) because it is
provided by a user, you should escape it with `mysql.escapeId(identifier)` like this:
```js
var sorter = 'date';
var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId(sorter);
console.log(query); // SELECT * FROM posts ORDER BY `date`
```
It also supports adding qualified identifiers. It will escape both parts.
```js
var sorter = 'date';
var query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId('posts.' + sorter);
console.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`
```
When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL
injection in object keys.
### Custom format
If you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function.
Here's an example of how to implement another format:
```js
connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/\:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};
connection.query("UPDATE posts SET title = :title", { title: "Hello MySQL" });
```
## Getting the id of an inserted row
If you are inserting a row into a table with an auto increment primary key, you
can retrieve the insert id like this:
```js
connection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {
if (err) throw err;
console.log(result.insertId);
});
```
When dealing with big numbers (above JavaScript Number precision limit), you should
consider enabling `supportBigNumbers` option to be able to read the insert id as a
string, otherwise it will throw.
This option is also required when fetching big numbers from the database, otherwise
you will get values rounded to hundreds or thousands due to the precision limit.
## Executing queries in parallel
The MySQL protocol is sequential, this means that you need multiple connections
to execute queries in parallel. You can use a Pool to manage connections, one
simple approach is to create one connection per incoming http request.
## Streaming query rows
Sometimes you may want to select large quantities of rows and process each of
them as they are received. This can be done like this:
```js
var query = connection.query('SELECT * FROM posts');
query
.on('error', function(err) {
// Handle error, an 'end' event will be emitted after this as well
})
.on('fields', function(fields) {
// the field packets for the rows to follow
})
.on('result', function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();
processRow(row, function() {
connection.resume();
});
})
.on('end', function() {
// all rows have been received
});
```
Please note a few things about the example above:
* Usually you will want to receive a certain amount of rows before starting to
throttle the connection using `pause()`. This number will depend on the
amount and size of your rows.
* `pause()` / `resume()` operate on the underlying socket and parser. You are
guaranteed that no more `'result'` events will fire after calling `pause()`.
* You MUST NOT provide a callback to the `query()` method when streaming rows.
* The `'result'` event will fire for both rows as well as OK packets
confirming the success of a INSERT/UPDATE query.
Additionally you may be interested to know that it is currently not possible to
stream individual row columns, they will always be buffered up entirely. If you
have a good use case for streaming large fields to and from MySQL, I'd love to
get your thoughts and contributions on this.
## Multiple statement queries
Support for multiple statements is disabled for security reasons (it allows for
SQL injection attacks if values are not properly escaped). To use this feature
you have to enable it for your connection:
```js
var connection = mysql.createConnection({multipleStatements: true});
```
Once enabled, you can execute multiple statement queries like any other query:
```js
connection.query('SELECT 1; SELECT 2', function(err, results) {
if (err) throw err;
// `results` is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
```
Additionally you can also stream the results of multiple statement queries:
```js
var query = connection.query('SELECT 1; SELECT 2');
query
.on('fields', function(fields, index) {
// the fields for the result rows that follow
})
.on('result', function(row, index) {
// index refers to the statement this result belongs to (starts at 0)
});
```
If one of the statements in your query causes an error, the resulting Error
object contains a `err.index` property which tells you which statement caused
it. MySQL will also stop executing any remaining statements when an error
occurs.
Please note that the interface for streaming multiple statement queries is
experimental and I am looking forward to feedback on it.
## Stored procedures
You can call stored procedures from your queries as with any other mysql driver.
If the stored procedure produces several result sets, they are exposed to you
the same way as the results for multiple statement queries.
## Joins with overlapping column names
When executing joins, you are likely to get result sets with overlapping column
names.
By default, node-mysql will overwrite colliding column names in the
order the columns are received from MySQL, causing some of the received values
to be unavailable.
However, you can also specify that you want your columns to be nested below
the table name like this:
```js
var options = {sql: '...', nestTables: true};
connection.query(options, function(err, results) {
/* results will be an array like this now:
[{
table1: {
fieldA: '...',
fieldB: '...',
},
table2: {
fieldA: '...',
fieldB: '...',
},
}, ...]
*/
});
```
Or use a string separator to have your results merged.
```js
var options = {sql: '...', nestTables: '_'};
connection.query(options, function(err, results) {
/* results will be an array like this now:
[{
table1_fieldA: '...',
table1_fieldB: '...',
table2_fieldA: '...',
table2_fieldB: '...'
}, ...]
*/
});
```
## Error handling
This module comes with a consistent approach to error handling that you should
review carefully in order to write solid applications.
All errors created by this module are instances of the JavaScript [Error][]
object. Additionally they come with two properties:
* `err.code`: Either a [MySQL server error][] (e.g.
`'ER_ACCESS_DENIED_ERROR'`), a node.js error (e.g. `'ECONNREFUSED'`) or an
internal error (e.g. `'PROTOCOL_CONNECTION_LOST'`).
* `err.fatal`: Boolean, indicating if this error is terminal to the connection
object.
[Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error
[MySQL server error]: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
Fatal errors are propagated to *all* pending callbacks. In the example below, a
fatal error is triggered by trying to connect to an invalid port. Therefore the
error object is propagated to both pending callbacks:
```js
var connection = require('mysql').createConnection({
port: 84943, // WRONG PORT
});
connection.connect(function(err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
connection.query('SELECT 1', function(err) {
console.log(err.code); // 'ECONNREFUSED'
console.log(err.fatal); // true
});
```
Normal errors however are only delegated to the callback they belong to. So in
the example below, only the first callback receives an error, the second query
works as expected:
```js
connection.query('USE name_of_db_that_does_not_exist', function(err, rows) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('SELECT 1', function(err, rows) {
console.log(err); // null
console.log(rows.length); // 1
});
```
Last but not least: If a fatal errors occurs and there are no pending
callbacks, or a normal error occurs which has no callback belonging to it, the
error is emitted as an `'error'` event on the connection object. This is
demonstrated in the example below:
```js
connection.on('error', function(err) {
console.log(err.code); // 'ER_BAD_DB_ERROR'
});
connection.query('USE name_of_db_that_does_not_exist');
```
Note: `'error'` are special in node. If they occur without an attached
listener, a stack trace is printed and your process is killed.
**tl;dr:** This module does not want you to deal with silent failures. You
should always provide callbacks to your method calls. If you want to ignore
this advice and suppress unhandled errors, you can do this:
```js
// I am Chuck Norris:
connection.on('error', function() {});
```
## Exception Safety
This module is exception safe. That means you can continue to use it, even if
one of your callback functions throws an error which you're catching using
'uncaughtException' or a domain.
## Type casting
For your convenience, this driver will cast mysql types into native JavaScript
types by default. The following mappings exist:
### Number
* TINYINT
* SMALLINT
* INT
* MEDIUMINT
* YEAR
* FLOAT
* DOUBLE
### Date
* TIMESTAMP
* DATE
* DATETIME
### Buffer
* TINYBLOB
* MEDIUMBLOB
* LONGBLOB
* BLOB
* BINARY
* VARBINARY
* BIT (last byte will be filled with 0 bits as necessary)
### String
* CHAR
* VARCHAR
* TINYTEXT
* MEDIUMTEXT
* LONGTEXT
* TEXT
* ENUM
* SET
* DECIMAL (may exceed float precision)
* BIGINT (may exceed float precision)
* TIME (could be mapped to Date, but what date would be set?)
* GEOMETRY (never used those, get in touch if you do)
It is not recommended (and may go away / change in the future) to disable type
casting, but you can currently do so on either the connection:
```js
var connection = require('mysql').createConnection({typeCast: false});
```
Or on the query level:
```js
var options = {sql: '...', typeCast: false};
var query = connection.query(options, function(err, results) {
}):
```
You can also pass a function and handle type casting yourself. You're given some
column information like database, table and name and also type and length. If you
just want to apply a custom type casting to a specific type you can do it and then
fallback to the default. Here's an example of converting `TINYINT(1)` to boolean:
```js
connection.query({
sql: '...',
typeCast: function (field, next) {
if (field.type == 'TINY' && field.length == 1) {
return (field.string() == '1'); // 1 = true, 0 = false
}
return next();
}
})
```
If you need a buffer there's also a `.buffer()` function and also a `.geometry()` one
both used by the default type cast that you can use.
## Connection Flags
If, for any reason, you would like to change the default connection flags, you
can use the connection option `flags`. Pass a string with a comma separated list
of items to add to the default flags. If you don't want a default flag to be used
prepend the flag with a minus sign. To add a flag that is not in the default list, don't prepend it with a plus sign, just write the flag name (case insensitive).
**Please note that some available flags that are not default are still not supported
(e.g.: SSL, Compression). Use at your own risk.**
### Example
The next example blacklists FOUND_ROWS flag from default connection flags.
```js
var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS")
```
### Default Flags
- LONG_PASSWORD
- FOUND_ROWS
- LONG_FLAG
- CONNECT_WITH_DB
- ODBC
- LOCAL_FILES
- IGNORE_SPACE
- PROTOCOL_41
- IGNORE_SIGPIPE
- TRANSACTIONS
- RESERVED
- SECURE_CONNECTION
- MULTI_RESULTS
- MULTI_STATEMENTS (used if `multipleStatements` option is activated)
### Other Available Flags
- NO_SCHEMA
- COMPRESS
- INTERACTIVE
- SSL
- PS_MULTI_RESULTS
- PLUGIN_AUTH
- SSL_VERIFY_SERVER_CERT
- REMEMBER_OPTIONS
## Debugging and reporting problems
If you are running into problems, one thing that may help is enabling the
`debug` mode for the connection:
```js
var connection = mysql.createConnection({debug: true});
```
This will print all incoming and outgoing packets on stdout.
If that does not help, feel free to open a GitHub issue. A good GitHub issue
will have:
* The minimal amount of code required to reproduce the problem (if possible)
* As much debugging output and information about your environment (mysql
version, node version, os, etc.) as you can gather.
## Todo
* Prepared statements
* setTimeout() for Connection / Query
* Support for encodings other than UTF-8 / ASCII
* API support for transactions, similar to [php](http://www.php.net/manual/en/mysqli.quickstart.transactions.php)
+96
View File
@@ -0,0 +1,96 @@
var script = process.cwd() + '/' + process.argv[2];
var spawn = require('child_process').spawn;
var numbers = [];
var boringResults = 0;
var scriptRuns = 0;
function runScript() {
scriptRuns++;
var child = spawn(process.execPath, [script]);
var buffer = '';
child.stdout.on('data', function(chunk) {
buffer += chunk;
var offset;
while ((offset = buffer.indexOf('\n')) > -1) {
var number = parseInt(buffer.substr(0, offset), 10);
buffer = buffer.substr(offset + 1);
var maxBefore = max();
var minBefore = min();
numbers.push(number);
if (maxBefore === max() && minBefore === min()) {
boringResults++;
}
if (boringResults > 10) {
boringResults = 0;
child.kill();
runScript();
}
}
});
}
function report() {
console.log(
'max: %s | median: %s | sdev: %s | last: %s | min: %s | runs: %s | results: %s',
max(),
median(),
sdev(),
numbers[numbers.length - 1],
min(),
scriptRuns,
numbers.length
);
}
function min() {
if (!numbers.length) return undefined;
return numbers.reduce(function(min, number) {
return (number < min)
? number
: min;
});
}
function max() {
if (!numbers.length) return undefined;
return numbers.reduce(function(max, number) {
return (number > max)
? number
: max;
});
}
function median() {
return numbers[Math.floor(numbers.length / 2)];
}
function sdev() {
if (!numbers.length) return undefined;
return Math.round(Math.sqrt(variance()));
}
function variance() {
var t = 0, squares = 0, len = numbers.length;
for (var i=0; i<len; i++) {
var obs = numbers[i];
t += obs;
squares += Math.pow(obs, 2);
}
return (squares/len) - Math.pow(t/len, 2);
}
setInterval(report, 1000);
runScript();
+112
View File
@@ -0,0 +1,112 @@
var lib = __dirname + '/../lib';
var Protocol = require(lib + '/protocol/protocol');
var Packets = require(lib + '/protocol/packets');
var PacketWriter = require(lib + '/protocol/PacketWriter');
var Parser = require(lib + '/protocol/Parser');
var options = {
rows : 100000,
bufferSize : 64 * 1024,
};
console.error('Config:', options);
function createBuffers() {
var parser = new Parser();
process.stderr.write('Creating row buffers ... ');
var number = 1;
var id = 0;
var start = Date.now();
var buffers = [
createPacketBuffer(parser, new Packets.ResultSetHeaderPacket({fieldCount: 2})),
createPacketBuffer(parser, new Packets.FieldPacket({catalog: 'foo', name: 'id'})),
createPacketBuffer(parser, new Packets.FieldPacket({catalog: 'foo', name: 'text'})),
createPacketBuffer(parser, new Packets.EofPacket()),
];
for (var i = 0; i < options.rows; i++) {
buffers.push(createRowDataPacketBuffer(parser, number++));
}
buffers.push(createPacketBuffer(parser, new Packets.EofPacket));
buffers = mergeBuffers(buffers);
var bytes = buffers.reduce(function(bytes, buffer) {
return bytes + buffer.length;
}, 0);
var mb = (bytes / 1024 / 1024).toFixed(2)
console.error('%s buffers (%s mb) in %s ms', buffers.length, mb, (Date.now() - start));
return buffers;
}
function createPacketBuffer(parser, packet) {
var writer = new PacketWriter();
packet.write(writer);
return writer.toBuffer(parser);
}
function createRowDataPacketBuffer(parser, number) {
var writer = new PacketWriter();
writer.writeLengthCodedString(parser._nextPacketNumber);
writer.writeLengthCodedString('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has sur');
return writer.toBuffer(parser);
}
function mergeBuffers(buffers) {
var mergeBuffer = new Buffer(options.bufferSize);
var mergeBuffers = [];
var offset = 0;
for (var i = 0; i < buffers.length; i++) {
var buffer = buffers[i];
var bytesRemaining = mergeBuffer.length - offset;
if (buffer.length < bytesRemaining) {
buffer.copy(mergeBuffer, offset);
offset += buffer.length;
} else {
buffer.copy(mergeBuffer, offset, 0, bytesRemaining);
mergeBuffers.push(mergeBuffer);
mergeBuffer = new Buffer(options.bufferSize);
buffer.copy(mergeBuffer, 0, bytesRemaining);
offset = buffer.length - bytesRemaining;
}
}
if (offset > 0) {
mergeBuffers.push(mergeBuffer.slice(0, offset));
}
return mergeBuffers;
}
function benchmark(buffers) {
var protocol = new Protocol();
protocol._handshakeInitializationPacket = true;
protocol.query({typeCast: false, sql: 'SELECT ...'});
var start = +new Date;
for (var i = 0; i < buffers.length; i++) {
protocol.write(buffers[i]);
}
var duration = Date.now() - start;
var hz = Math.round(options.rows / (duration / 1000));
console.log(hz);
}
var buffers = createBuffers();
while (true) {
benchmark(buffers);
}
+42
View File
@@ -0,0 +1,42 @@
var common = require('../test/common');
var client = common.createConnection({typeCast: false});
var rowsPerRun = 100000;
client.connect(function(err) {
if (err) throw err;
client.query('USE node_mysql_test', function(err, results) {
if (err) throw err;
selectRows();
});
});
var firstSelect;
var rowCount = 0;
console.error('Benchmarking rows per second in hz:');
function selectRows() {
firstSelect = firstSelect || Date.now();
client.query('SELECT * FROM posts', function(err, rows) {
if (err) throw err;
rowCount += rows.length;
if (rowCount < rowsPerRun) {
selectRows();
return;
}
var duration = (Date.now() - firstSelect) / 1000;
var hz = Math.round(rowCount / duration);
console.log(hz);
rowCount = 0;
firstSelect = null;
selectRows();
});
};
+20
View File
@@ -0,0 +1,20 @@
var Connection = require('./lib/Connection');
var ConnectionConfig = require('./lib/ConnectionConfig');
var Types = require('./lib/protocol/constants/types');
var SqlString = require('./lib/protocol/SqlString');
var Pool = require('./lib/Pool');
var PoolConfig = require('./lib/PoolConfig');
exports.createConnection = function(config) {
return new Connection({config: new ConnectionConfig(config)});
};
exports.createPool = function(config) {
return new Pool({config: new PoolConfig(config)});
};
exports.createQuery = Connection.createQuery;
exports.Types = Types;
exports.escape = SqlString.escape;
exports.escapeId = SqlString.escapeId;
+164
View File
@@ -0,0 +1,164 @@
var Net = require('net');
var ConnectionConfig = require('./ConnectionConfig');
var Pool = require('./Pool');
var Protocol = require('./protocol/Protocol');
var SqlString = require('./protocol/SqlString');
var Query = require('./protocol/sequences/Query');
var EventEmitter = require('events').EventEmitter;
var Util = require('util');
module.exports = Connection;
Util.inherits(Connection, EventEmitter);
function Connection(options) {
EventEmitter.call(this);
this.config = options.config;
this._socket = options.socket;
this._protocol = new Protocol({config: this.config, connection: this});
this._connectCalled = false;
}
Connection.createQuery = function(sql, values, cb) {
if (sql instanceof Query) {
return sql;
}
var options = {};
if (typeof sql === 'object') {
// query(options, cb)
options = sql;
cb = values;
} else if (typeof values === 'function') {
// query(sql, cb)
cb = values;
options.sql = sql;
options.values = undefined;
} else {
// query(sql, values, cb)
options.sql = sql;
options.values = values;
}
return new Query(options, cb);
};
Connection.prototype.connect = function(cb) {
if (!this._connectCalled) {
this._connectCalled = true;
this._socket = (this.config.socketPath)
? Net.createConnection(this.config.socketPath)
: Net.createConnection(this.config.port, this.config.host);
this._socket.pipe(this._protocol);
this._protocol.pipe(this._socket);
this._socket.on('error', this._handleNetworkError.bind(this));
this._protocol.on('unhandledError', this._handleProtocolError.bind(this));
this._protocol.on('drain', this._handleProtocolDrain.bind(this));
this._protocol.on('end', this._handleProtocolEnd.bind(this));
}
this._protocol.handshake(cb);
};
Connection.prototype.changeUser = function(options, cb){
this._implyConnect();
if (typeof options === 'function') {
cb = options;
options = {};
}
var charsetNumber = (options.charset)
? Config.getCharsetNumber(options.charset)
: this.config.charsetNumber;
return this._protocol.changeUser({
user : options.user || this.config.user,
password : options.password || this.config.password,
database : options.database || this.config.database,
charsetNumber : charsetNumber,
currentConfig : this.config
}, cb);
};
Connection.prototype.query = function(sql, values, cb) {
this._implyConnect();
var query = Connection.createQuery(sql, values, cb);
if (!(typeof sql == 'object' && 'typeCast' in sql)) {
query.typeCast = this.config.typeCast;
}
query.sql = this.format(query.sql, query.values || []);
delete query.values;
return this._protocol._enqueue(query);
};
Connection.prototype.ping = function(cb) {
this._implyConnect();
this._protocol.ping(cb);
};
Connection.prototype.statistics = function(cb) {
this._implyConnect();
this._protocol.stats(cb);
};
Connection.prototype.end = function(cb) {
this._implyConnect();
this._protocol.quit(cb);
};
Connection.prototype.destroy = function() {
this._implyConnect();
this._socket.destroy();
this._protocol.destroy();
};
Connection.prototype.pause = function() {
this._socket.pause();
this._protocol.pause();
};
Connection.prototype.resume = function() {
this._socket.resume();
this._protocol.resume();
};
Connection.prototype.escape = function(value) {
return SqlString.escape(value, false, this.config.timezone);
};
Connection.prototype.format = function(sql, values) {
if (typeof this.config.queryFormat == "function") {
return this.config.queryFormat.call(this, sql, values, this.config.timezone);
}
return SqlString.format(sql, values, this.config.timezone);
};
Connection.prototype._handleNetworkError = function(err) {
this._protocol.handleNetworkError(err);
};
Connection.prototype._handleProtocolError = function(err) {
this.emit('error', err);
};
Connection.prototype._handleProtocolDrain = function() {
this.emit('drain');
};
Connection.prototype._handleProtocolEnd = function(err) {
this.emit('end', err);
};
Connection.prototype._implyConnect = function() {
if (!this._connectCalled) {
this.connect();
}
};
+113
View File
@@ -0,0 +1,113 @@
var urlParse = require('url').parse;
var ClientConstants = require('./protocol/constants/client');
var Charsets = require('./protocol/constants/charsets');
module.exports = ConnectionConfig;
function ConnectionConfig(options) {
if (typeof options === 'string') {
options = ConnectionConfig.parseUrl(options);
}
this.host = options.host || 'localhost';
this.port = options.port || 3306;
this.socketPath = options.socketPath;
this.user = options.user || undefined;
this.password = options.password || undefined;
this.database = options.database;
this.insecureAuth = options.insecureAuth || false;
this.supportBigNumbers = options.supportBigNumbers || false;
this.debug = options.debug;
this.timezone = options.timezone || 'local';
this.flags = options.flags || '';
this.queryFormat = options.queryFormat;
this.pool = options.pool || undefined;
this.typeCast = (options.typeCast === undefined)
? true
: options.typeCast;
if (this.timezone[0] == " ") {
// "+" is a url encoded char for space so it
// gets translated to space when giving a
// connection string..
this.timezone = "+" + this.timezone.substr(1);
}
this.maxPacketSize = 0;
this.charsetNumber = (options.charset)
? ConnectionConfig.getCharsetNumber(options.charset)
: Charsets.UTF8_GENERAL_CI;
this.clientFlags = ConnectionConfig.mergeFlags(ConnectionConfig.getDefaultFlags(options),
options.flags || '');
}
ConnectionConfig.mergeFlags = function(default_flags, user_flags) {
var flags = 0x0, i;
user_flags = (user_flags || '').toUpperCase().split(/\s*,+\s*/);
// add default flags unless "blacklisted"
for (i in default_flags) {
if (user_flags.indexOf("-" + default_flags[i]) >= 0) continue;
flags |= ClientConstants["CLIENT_" + default_flags[i]] || 0x0;
}
// add user flags unless already already added
for (i in user_flags) {
if (user_flags[i][0] == "-") continue;
if (default_flags.indexOf(user_flags[i]) >= 0) continue;
flags |= ClientConstants["CLIENT_" + user_flags[i]] || 0x0;
}
return flags;
};
ConnectionConfig.getDefaultFlags = function(options) {
var defaultFlags = [ "LONG_PASSWORD", "FOUND_ROWS", "LONG_FLAG",
"CONNECT_WITH_DB", "ODBC", "LOCAL_FILES",
"IGNORE_SPACE", "PROTOCOL_41", "IGNORE_SIGPIPE",
"TRANSACTIONS", "RESERVED", "SECURE_CONNECTION",
"MULTI_RESULTS" ];
if (options && options.multipleStatements) {
defaultFlags.push("MULTI_STATEMENTS");
}
return defaultFlags;
};
ConnectionConfig.getCharsetNumber = function(charset) {
return Charsets[charset];
};
ConnectionConfig.parseUrl = function(url) {
url = urlParse(url, true);
var options = {
host : url.hostname,
port : url.port,
database : url.pathname.substr(1),
};
if (url.auth) {
var auth = url.auth.split(':');
options.user = auth[0];
options.password = auth[1];
}
if (url.query) {
for (var key in url.query) {
var value = url.query[key];
try {
// Try to parse this as a JSON expression first
options[key] = JSON.parse(value);
} catch (err) {
// Otherwise assume it is a plain string
options[key] = value;
}
}
}
return options;
};
+148
View File
@@ -0,0 +1,148 @@
var Mysql = require('../');
var Connection = require('./Connection');
module.exports = Pool;
function Pool(options) {
this.config = options.config;
this.config.connectionConfig.pool = this;
this._allConnections = [];
this._freeConnections = [];
this._connectionQueue = [];
this._closed = false;
}
Pool.prototype.getConnection = function(cb) {
if (this._closed) {
cb(new Error('Pool is closed.'));
return;
}
if (this._freeConnections.length > 0) {
var connection = this._freeConnections[0];
this._freeConnections.shift();
cb(null, connection);
} else if (this.config.connectionLimit == 0 || this._allConnections.length < this.config.connectionLimit) {
var self = this;
var connection = this._createConnection();
this._allConnections.push(connection);
connection.connect(function(err) {
if (self._closed) {
cb(new Error('Pool is closed.'));
}
else if (err) {
cb(err);
} else {
cb(null, connection);
}
});
} else if (this.config.waitForConnections) {
this._connectionQueue.push(cb);
} else {
cb(new Error('No connections available.'));
}
};
Pool.prototype.releaseConnection = function(connection) {
if (connection._poolRemoved) {
// The connection has been removed from the pool and is no longer good.
if (this._connectionQueue.length) {
var cb = this._connectionQueue[0];
this._connectionQueue.shift();
process.nextTick(this.getConnection.bind(this, cb));
}
} else if (this._connectionQueue.length) {
var cb = this._connectionQueue[0];
this._connectionQueue.shift();
process.nextTick(cb.bind(null, null, connection));
} else {
this._freeConnections.push(connection);
}
};
Pool.prototype.end = function(cb) {
this._closed = true;
cb = cb || function(err) { if( err ) throw err; };
var self = this;
var closedConnections = 0;
var calledBack = false;
var endCB = function(err) {
if (calledBack) {
return;
} else if (err) {
calledBack = true;
delete endCB;
cb(err);
} else if (++closedConnections >= self._allConnections.length) {
calledBack = true;
delete endCB;
cb();
}
};
if (this._allConnections.length == 0) {
endCB();
return;
}
for (var i = 0; i < this._allConnections.length; ++i) {
var connection = this._allConnections[i];
connection.destroy = connection._realDestroy;
connection.end = connection._realEnd;
connection.end(endCB);
}
};
Pool.prototype._createConnection = function() {
var self = this;
var connection = (this.config.createConnection)
? this.config.createConnection(this.config.connectionConfig)
: Mysql.createConnection(this.config.connectionConfig);
connection._realEnd = connection.end;
connection.end = function(cb) {
self.releaseConnection(connection);
if (cb) cb();
};
connection._realDestroy = connection.destroy;
connection.destroy = function() {
self._removeConnection(connection);
connection.destroy();
};
// When a fatal error occurs the connection's protocol ends, which will cause
// the connection to end as well, thus we only need to watch for the end event
// and we will be notified of disconnects.
connection.on('end', this._handleConnectionEnd.bind(this, connection));
return connection;
};
Pool.prototype._handleConnectionEnd = function(connection) {
if (this._closed || connection._poolRemoved) {
return;
}
this._removeConnection(connection);
};
Pool.prototype._removeConnection = function(connection) {
connection._poolRemoved = true;
for (var i = 0; i < this._allConnections.length; ++i) {
if (this._allConnections[i] === connection) {
this._allConnections.splice(i, 1);
break;
}
}
for (var i = 0; i < this._freeConnections.length; ++i) {
if (this._freeConnections[i] === connection) {
this._freeConnections.splice(i, 1);
break;
}
}
connection.end = connection._realEnd;
connection.destroy = connection._realDestroy;
this.releaseConnection(connection);
};
+14
View File
@@ -0,0 +1,14 @@
var ConnectionConfig = require('./ConnectionConfig');
module.exports = PoolConfig;
function PoolConfig(options) {
this.connectionConfig = new ConnectionConfig(options);
this.createConnection = options.createConnection || undefined;
this.waitForConnections = (options.waitForConnections === undefined)
? true
: Boolean(options.waitForConnections);
this.connectionLimit = (options.connectionLimit === undefined)
? 10
: Number(options.connectionLimit);
}
+165
View File
@@ -0,0 +1,165 @@
var Buffer = require('buffer').Buffer;
var Crypto = require('crypto');
var Auth = exports;
function sha1(msg) {
var hash = Crypto.createHash('sha1');
hash.update(msg);
// hash.digest() does not output buffers yet
return hash.digest('binary');
};
Auth.sha1 = sha1;
function xor(a, b) {
a = new Buffer(a, 'binary');
b = new Buffer(b, 'binary');
var result = new Buffer(a.length);
for (var i = 0; i < a.length; i++) {
result[i] = (a[i] ^ b[i]);
}
return result;
};
Auth.xor = xor;
Auth.token = function(password, scramble) {
if (!password) {
return new Buffer(0);
}
var stage1 = sha1(password);
var stage2 = sha1(stage1);
var stage3 = sha1(scramble.toString('binary') + stage2);
return xor(stage3, stage1);
};
// This is a port of sql/password.c:hash_password which needs to be used for
// pre-4.1 passwords.
Auth.hashPassword = function(password) {
var nr = [0x5030, 0x5735],
add = 7,
nr2 = [0x1234, 0x5671],
result = new Buffer(8);
if (typeof password == 'string'){
password = new Buffer(password);
}
for (var i = 0; i < password.length; i++) {
var c = password[i];
if (c == 32 || c == 9) {
// skip space in password
continue;
}
// nr^= (((nr & 63)+add)*c)+ (nr << 8);
// nr = xor(nr, add(mul(add(and(nr, 63), add), c), shl(nr, 8)))
nr = this.xor32(nr, this.add32(this.mul32(this.add32(this.and32(nr, [0,63]), [0,add]), [0,c]), this.shl32(nr, 8)));
// nr2+=(nr2 << 8) ^ nr;
// nr2 = add(nr2, xor(shl(nr2, 8), nr))
nr2 = this.add32(nr2, this.xor32(this.shl32(nr2, 8), nr));
// add+=tmp;
add += c;
}
this.int31Write(result, nr, 0);
this.int31Write(result, nr2, 4);
return result;
};
Auth.randomInit = function(seed1, seed2) {
return {
max_value: 0x3FFFFFFF,
max_value_dbl: 0x3FFFFFFF,
seed1: seed1 % 0x3FFFFFFF,
seed2: seed2 % 0x3FFFFFFF
};
};
Auth.myRnd = function(r){
r.seed1 = (r.seed1 * 3 + r.seed2) % r.max_value;
r.seed2 = (r.seed1 + r.seed2 + 33) % r.max_value;
return r.seed1 / r.max_value_dbl;
};
Auth.scramble323 = function(message, password) {
var to = new Buffer(8),
hashPass = this.hashPassword(password),
hashMessage = this.hashPassword(message.slice(0, 8)),
seed1 = this.int32Read(hashPass, 0) ^ this.int32Read(hashMessage, 0),
seed2 = this.int32Read(hashPass, 4) ^ this.int32Read(hashMessage, 4),
r = this.randomInit(seed1, seed2);
for (var i = 0; i < 8; i++){
to[i] = Math.floor(this.myRnd(r) * 31) + 64;
}
var extra = (Math.floor(this.myRnd(r) * 31));
for (var i = 0; i < 8; i++){
to[i] ^= extra;
}
return to;
};
Auth.fmt32 = function(x){
var a = x[0].toString(16),
b = x[1].toString(16);
if (a.length == 1) a = '000'+a;
if (a.length == 2) a = '00'+a;
if (a.length == 3) a = '0'+a;
if (b.length == 1) b = '000'+b;
if (b.length == 2) b = '00'+b;
if (b.length == 3) b = '0'+b;
return '' + a + '/' + b;
};
Auth.xor32 = function(a,b){
return [a[0] ^ b[0], a[1] ^ b[1]];
};
Auth.add32 = function(a,b){
var w1 = a[1] + b[1],
w2 = a[0] + b[0] + ((w1 & 0xFFFF0000) >> 16);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.mul32 = function(a,b){
// based on this example of multiplying 32b ints using 16b
// http://www.dsprelated.com/showmessage/89790/1.php
var w1 = a[1] * b[1],
w2 = (((a[1] * b[1]) >> 16) & 0xFFFF) + ((a[0] * b[1]) & 0xFFFF) + (a[1] * b[0] & 0xFFFF);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.and32 = function(a,b){
return [a[0] & b[0], a[1] & b[1]];
};
Auth.shl32 = function(a,b){
// assume b is 16 or less
var w1 = a[1] << b,
w2 = (a[0] << b) | ((w1 & 0xFFFF0000) >> 16);
return [w2 & 0xFFFF, w1 & 0xFFFF];
};
Auth.int31Write = function(buffer, number, offset) {
buffer[offset] = (number[0] >> 8) & 0x7F;
buffer[offset + 1] = (number[0]) & 0xFF;
buffer[offset + 2] = (number[1] >> 8) & 0xFF;
buffer[offset + 3] = (number[1]) & 0xFF;
};
Auth.int32Read = function(buffer, offset){
return (buffer[offset] << 24)
+ (buffer[offset+1] << 16)
+ (buffer[offset+2] << 8)
+ (buffer[offset+3]);
};
+5
View File
@@ -0,0 +1,5 @@
module.exports = PacketHeader;
function PacketHeader(length, number) {
this.length = length;
this.number = number;
}
+197
View File
@@ -0,0 +1,197 @@
var BIT_16 = Math.pow(2, 16);
var BIT_24 = Math.pow(2, 24);
// The maximum precision JS Numbers can hold precisely
// Don't panic: Good enough to represent byte values up to 8192 TB
var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1;
module.exports = PacketWriter;
function PacketWriter() {
this._buffer = new Buffer(0);
this._offset = 0;
}
PacketWriter.prototype.toBuffer = function(parser) {
var packets = Math.floor(this._buffer.length / MAX_PACKET_LENGTH) + 1;
var buffer = this._buffer;
this._buffer = new Buffer(this._buffer.length + packets * 4);
for (var packet = 0; packet < packets; packet++) {
this._offset = packet * (MAX_PACKET_LENGTH + 4);
var isLast = (packet + 1 === packets);
var packetLength = (isLast)
? buffer.length % MAX_PACKET_LENGTH
: MAX_PACKET_LENGTH;
var packetNumber = parser.incrementPacketNumber();
this.writeUnsignedNumber(3, packetLength);
this.writeUnsignedNumber(1, packetNumber);
var start = packet * MAX_PACKET_LENGTH;
var end = start + packetLength;
this.writeBuffer(buffer.slice(start, end));
}
return this._buffer;
};
PacketWriter.prototype.writeUnsignedNumber = function(bytes, value) {
this._allocate(bytes);
for (var i = 0; i < bytes; i++) {
this._buffer[this._offset++] = (value >> (i * 8)) & 0xff;
}
};
PacketWriter.prototype.writeFiller = function(bytes) {
this._allocate(bytes);
for (var i = 0; i < bytes; i++) {
this._buffer[this._offset++] = 0x00;
}
};
PacketWriter.prototype.writeNullTerminatedString = function(value, encoding) {
// Typecast undefined into '' and numbers into strings
value = value || '';
value = value + '';
var bytes = Buffer.byteLength(value, encoding || 'utf-8') + 1;
this._allocate(bytes);
this._buffer.write(value, this._offset, encoding);
this._buffer[this._offset + bytes - 1] = 0x00;
this._offset += bytes;
};
PacketWriter.prototype.writeString = function(value) {
// Typecast undefined into '' and numbers into strings
value = value || '';
value = value + '';
var bytes = Buffer.byteLength(value, 'utf-8');
this._allocate(bytes);
this._buffer.write(value, this._offset, 'utf-8');
this._offset += bytes;
};
PacketWriter.prototype.writeBuffer = function(value) {
var bytes = value.length;
this._allocate(bytes);
value.copy(this._buffer, this._offset);
this._offset += bytes;
};
PacketWriter.prototype.writeLengthCodedNumber = function(value) {
if (value === null) {
this._allocate(1);
this._buffer[this._offset++] = 251;
return;
}
if (value <= 250) {
this._allocate(1);
this._buffer[this._offset++] = value;
return;
}
if (value > IEEE_754_BINARY_64_PRECISION) {
throw new Error(
'writeLengthCodedNumber: JS precision range exceeded, your ' +
'number is > 53 bit: "' + value + '"'
);
}
if (value <= BIT_16) {
this._allocate(3)
this._buffer[this._offset++] = 252;
} else if (value <= BIT_24) {
this._allocate(4)
this._buffer[this._offset++] = 253;
} else {
this._allocate(9);
this._buffer[this._offset++] = 254;
}
// 16 Bit
this._buffer[this._offset++] = value & 0xff;
this._buffer[this._offset++] = (value >> 8) & 0xff;
if (value <= BIT_16) return;
// 24 Bit
this._buffer[this._offset++] = (value >> 16) & 0xff;
if (value <= BIT_24) return;
this._buffer[this._offset++] = (value >> 24) & 0xff;
// Hack: Get the most significant 32 bit (JS bitwise operators are 32 bit)
value = value.toString(2);
value = value.substr(0, value.length - 32);
value = parseInt(value, 2);
this._buffer[this._offset++] = value & 0xff;
this._buffer[this._offset++] = (value >> 8) & 0xff;
this._buffer[this._offset++] = (value >> 16) & 0xff;
// Set last byte to 0, as we can only support 53 bits in JS (see above)
this._buffer[this._offset++] = 0;
};
PacketWriter.prototype.writeLengthCodedBuffer = function(value) {
var bytes = value.length;
this.writeLengthCodedNumber(bytes);
this.writeBuffer(value);
};
PacketWriter.prototype.writeNullTerminatedBuffer = function(value) {
this.writeBuffer(value);
this.writeFiller(1); // 0x00 terminator
};
PacketWriter.prototype.writeLengthCodedString = function(value) {
if (value === null) {
this.writeLengthCodedNumber(null);
return;
}
value = (value === undefined)
? ''
: String(value);
var bytes = Buffer.byteLength(value, 'utf-8');
this.writeLengthCodedNumber(bytes);
if (!bytes) {
return;
}
this._allocate(bytes);
this._buffer.write(value, this._offset, 'utf-8');
this._offset += bytes;
};
PacketWriter.prototype._allocate = function(bytes) {
if (!this._buffer) {
this._buffer = new Buffer(bytes);
return;
}
var bytesRemaining = this._buffer.length - this._offset;
if (bytesRemaining >= bytes) {
return;
}
var oldBuffer = this._buffer;
this._buffer = new Buffer(oldBuffer.length + bytes);
oldBuffer.copy(this._buffer);
};
+386
View File
@@ -0,0 +1,386 @@
var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
var MAX_PACKET_LENGTH = Math.pow(2, 24) - 1;
var PacketHeader = require('./PacketHeader');
var BigNumber = require("bignumber.js");
module.exports = Parser;
function Parser(options) {
options = options || {};
this._supportBigNumbers = options.config && options.config.supportBigNumbers;
this._buffer = new Buffer(0);
this._longPacketBuffers = [];
this._offset = 0;
this._packetEnd = null;
this._packetHeader = null;
this._onPacket = options.onPacket || function() {};
this._nextPacketNumber = 0;
this._encoding = 'utf-8';
this._paused = false;
}
Parser.prototype.write = function(buffer) {
this.append(buffer);
while (true) {
if (this._paused) {
return;
}
if (!this._packetHeader) {
if (this._bytesRemaining() < 4) {
break;
}
this._packetHeader = new PacketHeader(
this.parseUnsignedNumber(3),
this.parseUnsignedNumber(1)
);
this._trackAndVerifyPacketNumber(this._packetHeader.number);
}
if (this._bytesRemaining() < this._packetHeader.length) {
break;
}
this._packetEnd = this._offset + this._packetHeader.length;
if (this._packetHeader.length === MAX_PACKET_LENGTH) {
this._longPacketBuffers.push(this._buffer.slice(this._offset, this._packetEnd));
this._advanceToNextPacket();
continue;
}
this._combineLongPacketBuffers();
// Try...finally to ensure exception safety. Unfortunately this is costing
// us up to ~10% performance in some benchmarks.
var hadException = true;
try {
this._onPacket(this._packetHeader);
hadException = false;
} finally {
this._advanceToNextPacket();
// If we had an exception, the parser while loop will be broken out
// of after the finally block. So we need to make sure to re-enter it
// to continue parsing any bytes that may already have been received.
if (hadException) {
process.nextTick(this.write.bind(this));
}
}
}
};
Parser.prototype.append = function(newBuffer) {
// If resume() is called, we don't pass a buffer to write()
if (!newBuffer) {
return;
}
var oldBuffer = this._buffer;
var bytesRemaining = this._bytesRemaining();
var newLength = bytesRemaining + newBuffer.length;
var combinedBuffer = (this._offset > newLength)
? oldBuffer.slice(0, newLength)
: new Buffer(newLength);
oldBuffer.copy(combinedBuffer, 0, this._offset);
newBuffer.copy(combinedBuffer, bytesRemaining);
this._buffer = combinedBuffer;
this._offset = 0;
};
Parser.prototype.pause = function() {
this._paused = true;
};
Parser.prototype.resume = function() {
this._paused = false;
// nextTick() to avoid entering write() multiple times within the same stack
// which would cause problems as write manipulates the state of the object.
process.nextTick(this.write.bind(this));
};
Parser.prototype.peak = function() {
return this._buffer[this._offset];
};
Parser.prototype.parseUnsignedNumber = function(bytes) {
var bytesRead = 0;
var value = 0;
while (bytesRead < bytes) {
var byte = this._buffer[this._offset++];
value += byte * Math.pow(256, bytesRead);
bytesRead++;
}
return value;
};
Parser.prototype.parseLengthCodedString = function() {
var length = this.parseLengthCodedNumber();
if (length === null) {
return null;
}
return this.parseString(length);
};
Parser.prototype.parseLengthCodedBuffer = function() {
var length = this.parseLengthCodedNumber();
if (length === null) {
return null;
}
return this.parseBuffer(length);
};
Parser.prototype.parseLengthCodedNumber = function() {
var bits = this._buffer[this._offset++];
if (bits <= 251) {
return (bits === 251)
? null
: bits;
}
var length;
var bigNumber = false;
var value = 0;
if (bits === 252) {
length = 2;
} else if (bits === 253) {
length = 3;
} else if (bits === 254) {
length = 8;
if (this._supportBigNumbers) {
if (this._buffer[this._offset + 6] > 31 || this._buffer[this._offset + 7]) {
value = new BigNumber(0);
bigNumber = true;
}
}
} else {
throw new Error('parseLengthCodedNumber: Unexpected first byte: ' + bits);
}
for (var bytesRead = 0; bytesRead < length; bytesRead++) {
bits = this._buffer[this._offset++];
if (bigNumber) {
value = value.plus((new BigNumber(256)).pow(bytesRead).times(bits));
} else {
value += Math.pow(256, bytesRead) * bits;
}
}
if (bigNumber) {
return value.toString();
}
if (value >= IEEE_754_BINARY_64_PRECISION) {
throw new Error(
'parseLengthCodedNumber: JS precision range exceeded, ' +
'number is >= 53 bit: "' + value + '"'
);
}
return value;
};
Parser.prototype.parseFiller = function(length) {
return this.parseBuffer(length);
};
Parser.prototype.parseNullTerminatedBuffer = function() {
var end = this._nullByteOffset();
var value = this._buffer.slice(this._offset, end);
this._offset = end + 1;
return value;
};
Parser.prototype.parseNullTerminatedString = function() {
var end = this._nullByteOffset();
var value = this._buffer.toString(this._encoding, this._offset, end);
this._offset = end + 1;
return value;
};
Parser.prototype._nullByteOffset = function() {
var offset = this._offset;
while (this._buffer[offset] !== 0x00) {
offset++;
if (offset >= this._buffer.length) {
throw new Error('Offset of null terminated string not found.');
}
}
return offset;
};
Parser.prototype.parsePacketTerminatedString = function() {
var length = this._packetEnd - this._offset;
return this.parseString(length);
};
Parser.prototype.parseBuffer = function(length) {
var response = new Buffer(length);
this._buffer.copy(response, 0, this._offset, this._offset + length);
this._offset += length;
return response;
};
Parser.prototype.parseString = function(length) {
var offset = this._offset;
var end = offset + length;
var value = this._buffer.toString(this._encoding, offset, end);
this._offset = end;
return value;
};
Parser.prototype.parseGeometryValue = function() {
var buffer = this.parseLengthCodedBuffer();
var offset = 4;
if (buffer === null) {
return null;
}
function parseGeometry() {
var result = null;
var byteOrder = buffer.readUInt8(offset); offset += 1;
var wkbType = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
switch(wkbType) {
case 1: // WKBPoint
var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
result = {x: x, y: y};
break;
case 2: // WKBLineString
var numPoints = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
result = [];
for(var i=numPoints;i>0;i--) {
var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
result.push({x: x, y: y});
}
break;
case 3: // WKBPolygon
var numRings = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
result = [];
for(var i=numRings;i>0;i--) {
var numPoints = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
var line = [];
for(var j=numPoints;j>0;j--) {
var x = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
var y = byteOrder? buffer.readDoubleLE(offset) : buffer.readDoubleBE(offset); offset += 8;
line.push({x: x, y: y});
}
result.push(line);
}
break;
case 4: // WKBMultiPoint
case 5: // WKBMultiLineString
case 6: // WKBMultiPolygon
case 7: // WKBGeometryCollection
var num = byteOrder? buffer.readUInt32LE(offset) : buffer.readUInt32BE(offset); offset += 4;
var result = [];
for(var i=num;i>0;i--) {
result.push(parseGeometry());
}
break;
}
return result;
}
return parseGeometry();
}
Parser.prototype.reachedPacketEnd = function() {
return this._offset === this._packetEnd;
};
Parser.prototype._bytesRemaining = function() {
return this._buffer.length - this._offset;
};
Parser.prototype._trackAndVerifyPacketNumber = function(number) {
if (number !== this._nextPacketNumber) {
var err = new Error(
'Packets out of order. Got: ' + number + ' ' +
'Expected: ' + this._nextPacketNumber
);
err.code = 'PROTOCOL_PACKETS_OUT_OF_ORDER';
throw err;
}
this.incrementPacketNumber();
};
Parser.prototype.incrementPacketNumber = function() {
var currentPacketNumber = this._nextPacketNumber;
this._nextPacketNumber = (this._nextPacketNumber + 1) % 256;
return currentPacketNumber;
};
Parser.prototype.resetPacketNumber = function() {
this._nextPacketNumber = 0;
};
Parser.prototype.packetLength = function() {
return this._longPacketBuffers.reduce(function(length, buffer) {
return length + buffer.length;
}, this._packetHeader.length);
};
Parser.prototype._combineLongPacketBuffers = function() {
if (!this._longPacketBuffers.length) {
return;
}
var trailingPacketBytes = this._buffer.length - this._packetEnd;
var length = this._longPacketBuffers.reduce(function(length, buffer) {
return length + buffer.length;
}, this._bytesRemaining());
var combinedBuffer = new Buffer(length);
var offset = this._longPacketBuffers.reduce(function(offset, buffer) {
buffer.copy(combinedBuffer, offset);
return offset + buffer.length;
}, 0);
this._buffer.copy(combinedBuffer, offset, this._offset);
this._buffer = combinedBuffer;
this._longPacketBuffers = [];
this._offset = 0;
this._packetEnd = this._buffer.length - trailingPacketBytes;
};
Parser.prototype._advanceToNextPacket = function() {
this._offset = this._packetEnd;
this._packetHeader = null;
this._packetEnd = null;
};
+296
View File
@@ -0,0 +1,296 @@
var Parser = require('./Parser');
var Sequences = require('./sequences');
var Packets = require('./packets');
var Auth = require('./Auth');
var Stream = require('stream').Stream;
var Util = require('util');
var PacketWriter = require('./PacketWriter');
module.exports = Protocol;
Util.inherits(Protocol, Stream);
function Protocol(options) {
Stream.call(this);
options = options || {};
this.readable = true;
this.writable = true;
this._config = options.config || {};
this._connection = options.connection;
this._callback = null;
this._fatalError = null;
this._quitSequence = null;
this._handshakeSequence = null;
this._destroyed = false;
this._queue = [];
this._handshakeInitializationPacket = null;
this._parser = new Parser({
onPacket : this._parsePacket.bind(this),
config : this._config
});
}
Protocol.prototype.write = function(buffer) {
this._parser.write(buffer);
return true;
};
Protocol.prototype.handshake = function(cb) {
return this._handshakeSequence = this._enqueue(new Sequences.Handshake(this._config, cb));
};
Protocol.prototype.query = function(options, cb) {
return this._enqueue(new Sequences.Query(options, cb));
};
Protocol.prototype.changeUser = function(options, cb) {
return this._enqueue(new Sequences.ChangeUser(options, cb));
};
Protocol.prototype.ping = function(cb) {
return this._enqueue(new Sequences.Ping(cb));
};
Protocol.prototype.stats = function(cb) {
return this._enqueue(new Sequences.Statistics(cb));
};
Protocol.prototype.quit = function(cb) {
return this._quitSequence = this._enqueue(new Sequences.Quit(cb));
};
Protocol.prototype.end = function() {
var expected = (this._quitSequence && this._queue[0] === this._quitSequence);
if (expected) {
this._quitSequence.end();
this.emit('end');
return;
}
var err = new Error('Connection lost: The server closed the connection.');
err.fatal = true;
err.code = 'PROTOCOL_CONNECTION_LOST';
this._delegateError(err);
};
Protocol.prototype.pause = function() {
this._parser.pause();
};
Protocol.prototype.resume = function() {
this._parser.resume();
};
Protocol.prototype._enqueue = function(sequence) {
if (!this._validateEnqueue(sequence)) {
return sequence;
}
this._queue.push(sequence);
var self = this;
sequence
.on('error', function(err) {
self._delegateError(err, sequence);
})
.on('packet', function(packet) {
self._emitPacket(packet);
})
.on('end', function() {
self._dequeue();
});
if (this._queue.length === 1) {
this._parser.resetPacketNumber();
sequence.start();
}
return sequence;
};
Protocol.prototype._validateEnqueue = function(sequence) {
var err;
var prefix = 'Cannot enqueue ' + sequence.constructor.name + ' after ';
if (this._quitSequence) {
err = new Error(prefix + 'invoking quit.');
err.code = 'PROTOCOL_ENQUEUE_AFTER_QUIT';
} else if (this._destroyed) {
err = new Error(prefix + 'being destroyed.');
err.code = 'PROTOCOL_ENQUEUE_AFTER_DESTROY';
} else if (this._handshakeSequence && sequence.constructor === Sequences.Handshake) {
err = new Error(prefix + 'already enqueuing a Handshake.');
err.code = 'PROTOCOL_ENQUEUE_HANDSHAKE_TWICE';
} else {
return true;
}
var self = this;
err.fatal = false;
sequence
.on('error', function(err) {
self._delegateError(err, sequence);
})
.end(err);
return false;
};
Protocol.prototype._parsePacket = function() {
var sequence = this._queue[0];
var Packet = this._determinePacket(sequence);
var packet = new Packet();
// Special case: Faster dispatch, and parsing done inside sequence
if (Packet === Packets.RowDataPacket) {
sequence.RowDataPacket(packet, this._parser, this._connection);
if (this._config.debug) {
this._debugPacket(true, packet);
}
return;
}
packet.parse(this._parser);
if (this._config.debug) {
this._debugPacket(true, packet);
}
if (Packet === Packets.HandshakeInitializationPacket) {
this._handshakeInitializationPacket = packet;
}
sequence[Packet.name](packet);
};
Protocol.prototype._emitPacket = function(packet) {
var packetWriter = new PacketWriter();
packet.write(packetWriter);
this.emit('data', packetWriter.toBuffer(this._parser));
if (this._config.debug) {
this._debugPacket(false, packet)
}
};
Protocol.prototype._determinePacket = function(sequence) {
var firstByte = this._parser.peak();
if (sequence.determinePacket) {
var Packet = sequence.determinePacket(firstByte, this._parser);
if (Packet) {
return Packet;
}
}
switch (firstByte) {
case 0x00: return Packets.OkPacket;
case 0xfe: return Packets.EofPacket;
case 0xff: return Packets.ErrorPacket;
}
throw new Error('Could not determine packet, firstByte = ' + firstByte);
};
Protocol.prototype._dequeue = function() {
// No point in advancing the queue, we are dead
if (this._fatalError) {
return;
}
this._queue.shift();
var sequence = this._queue[0];
if (!sequence) {
this.emit('drain');
return;
}
this._parser.resetPacketNumber();
if (sequence.constructor == Sequences.ChangeUser) {
sequence.start(this._handshakeInitializationPacket);
return;
}
sequence.start();
};
Protocol.prototype.handleNetworkError = function(err) {
err.fatal = true;
var sequence = this._queue[0];
if (sequence) {
sequence.end(err)
} else {
this._delegateError(err);
}
};
Protocol.prototype._delegateError = function(err, sequence) {
// Stop delegating errors after the first fatal error
if (this._fatalError) {
return;
}
if (err.fatal) {
this._fatalError = err;
}
if (this._shouldErrorBubbleUp(err, sequence)) {
// Can't use regular 'error' event here as that always destroys the pipe
// between socket and protocol which is not what we want (unless the
// exception was fatal).
this.emit('unhandledError', err);
} else if (err.fatal) {
this._queue.forEach(function(sequence) {
sequence.end(err);
});
}
// Make sure the stream we are piping to is getting closed
if (err.fatal) {
this.emit('end', err);
}
};
Protocol.prototype._shouldErrorBubbleUp = function(err, sequence) {
if (sequence) {
if (sequence.hasErrorHandler()) {
return false;
} else if (!err.fatal) {
return true;
}
}
return (err.fatal && !this._hasPendingErrorHandlers());
};
Protocol.prototype._hasPendingErrorHandlers = function() {
return this._queue.some(function(sequence) {
return sequence.hasErrorHandler();
});
};
Protocol.prototype.destroy = function() {
this._destroyed = true;
this._parser.pause();
};
Protocol.prototype._debugPacket = function(incoming, packet) {
var headline = (incoming)
? '<-- '
: '--> ';
headline = headline + packet.constructor.name;
console.log(headline);
console.log(packet);
console.log('');
};
+7
View File
@@ -0,0 +1,7 @@
module.exports = ResultSet;
function ResultSet(resultSetHeaderPacket) {
this.resultSetHeaderPacket = resultSetHeaderPacket;
this.fieldPackets = [];
this.eofPackets = [];
this.rows = [];
}
+136
View File
@@ -0,0 +1,136 @@
var SqlString = exports;
SqlString.escapeId = function (val, forbidQualified) {
if (forbidQualified) {
return '`' + val.replace(/`/g, '``') + '`';
}
return '`' + val.replace(/`/g, '``').replace(/\./g, '`.`') + '`';
};
SqlString.escape = function(val, stringifyObjects, timeZone) {
if (val === undefined || val === null) {
return 'NULL';
}
switch (typeof val) {
case 'boolean': return (val) ? 'true' : 'false';
case 'number': return val+'';
}
if (val instanceof Date) {
val = SqlString.dateToString(val, timeZone || "Z");
}
if (Buffer.isBuffer(val)) {
return SqlString.bufferToString(val);
}
if (Array.isArray(val)) {
return SqlString.arrayToList(val, timeZone);
}
if (typeof val === 'object') {
if (stringifyObjects) {
val = val.toString();
} else {
return SqlString.objectToValues(val, timeZone);
}
}
val = val.replace(/[\0\n\r\b\t\\\'\"\x1a]/g, function(s) {
switch(s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\"+s;
}
});
return "'"+val+"'";
};
SqlString.arrayToList = function(array, timeZone) {
return array.map(function(v) {
if (Array.isArray(v)) return '(' + SqlString.arrayToList(v) + ')';
return SqlString.escape(v, true, timeZone);
}).join(', ');
};
SqlString.format = function(sql, values, timeZone) {
values = [].concat(values);
return sql.replace(/\?/g, function(match) {
if (!values.length) {
return match;
}
return SqlString.escape(values.shift(), false, timeZone);
});
};
SqlString.dateToString = function(date, timeZone) {
var dt = new Date(date);
if (timeZone != 'local') {
var tz = convertTimezone(timeZone);
dt.setTime(dt.getTime() + (dt.getTimezoneOffset() * 60000));
if (tz !== false) {
dt.setTime(dt.getTime() + (tz * 60000));
}
}
var year = dt.getFullYear();
var month = zeroPad(dt.getMonth() + 1);
var day = zeroPad(dt.getDate());
var hour = zeroPad(dt.getHours());
var minute = zeroPad(dt.getMinutes());
var second = zeroPad(dt.getSeconds());
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
};
SqlString.bufferToString = function(buffer) {
var hex = '';
try {
hex = buffer.toString('hex');
} catch (err) {
// node v0.4.x does not support hex / throws unknown encoding error
for (var i = 0; i < buffer.length; i++) {
var byte = buffer[i];
hex += zeroPad(byte.toString(16));
}
}
return "X'" + hex+ "'";
};
SqlString.objectToValues = function(object, timeZone) {
var values = [];
for (var key in object) {
var value = object[key];
if(typeof value === 'function') {
continue;
}
values.push(this.escapeId(key) + ' = ' + SqlString.escape(value, true, timeZone));
}
return values.join(', ');
};
function zeroPad(number) {
return (number < 10) ? '0' + number : number;
}
function convertTimezone(tz) {
if (tz == "Z") return 0;
var m = tz.match(/([\+\-\s])(\d\d):?(\d\d)?/);
if (m) {
return (m[1] == '-' ? -1 : 1) * (parseInt(m[2], 10) + ((m[3] ? parseInt(m[3], 10) : 0) / 60)) * 60;
}
return false;
}
+128
View File
@@ -0,0 +1,128 @@
// not sure where I got this from, will need to add a generation script for it
exports.BIG5_CHINESE_CI = 1;
exports.LATIN2_CZECH_CS = 2;
exports.DEC8_SWEDISH_CI = 3;
exports.CP850_GENERAL_CI = 4;
exports.LATIN1_GERMAN1_CI = 5;
exports.HP8_ENGLISH_CI = 6;
exports.KOI8R_GENERAL_CI = 7;
exports.LATIN1_SWEDISH_CI = 8;
exports.LATIN2_GENERAL_CI = 9;
exports.SWE7_SWEDISH_CI = 10;
exports.ASCII_GENERAL_CI = 11;
exports.UJIS_JAPANESE_CI = 12;
exports.SJIS_JAPANESE_CI = 13;
exports.CP1251_BULGARIAN_CI = 14;
exports.LATIN1_DANISH_CI = 15;
exports.HEBREW_GENERAL_CI = 16;
exports.TIS620_THAI_CI = 18;
exports.EUCKR_KOREAN_CI = 19;
exports.LATIN7_ESTONIAN_CS = 20;
exports.LATIN2_HUNGARIAN_CI = 21;
exports.KOI8U_GENERAL_CI = 22;
exports.CP1251_UKRAINIAN_CI = 23;
exports.GB2312_CHINESE_CI = 24;
exports.GREEK_GENERAL_CI = 25;
exports.CP1250_GENERAL_CI = 26;
exports.LATIN2_CROATIAN_CI = 27;
exports.GBK_CHINESE_CI = 28;
exports.CP1257_LITHUANIAN_CI = 29;
exports.LATIN5_TURKISH_CI = 30;
exports.LATIN1_GERMAN2_CI = 31;
exports.ARMSCII8_GENERAL_CI = 32;
exports.UTF8_GENERAL_CI = 33;
exports.CP1250_CZECH_CS = 34;
exports.UCS2_GENERAL_CI = 35;
exports.CP866_GENERAL_CI = 36;
exports.KEYBCS2_GENERAL_CI = 37;
exports.MACCE_GENERAL_CI = 38;
exports.MACROMAN_GENERAL_CI = 39;
exports.CP852_GENERAL_CI = 40;
exports.LATIN7_GENERAL_CI = 41;
exports.LATIN7_GENERAL_CS = 42;
exports.MACCE_BIN = 43;
exports.CP1250_CROATIAN_CI = 44;
exports.LATIN1_BIN = 47;
exports.LATIN1_GENERAL_CI = 48;
exports.LATIN1_GENERAL_CS = 49;
exports.CP1251_BIN = 50;
exports.CP1251_GENERAL_CI = 51;
exports.CP1251_GENERAL_CS = 52;
exports.MACROMAN_BIN = 53;
exports.CP1256_GENERAL_CI = 57;
exports.CP1257_BIN = 58;
exports.CP1257_GENERAL_CI = 59;
exports.BINARY = 63;
exports.ARMSCII8_BIN = 64;
exports.ASCII_BIN = 65;
exports.CP1250_BIN = 66;
exports.CP1256_BIN = 67;
exports.CP866_BIN = 68;
exports.DEC8_BIN = 69;
exports.GREEK_BIN = 70;
exports.HEBREW_BIN = 71;
exports.HP8_BIN = 72;
exports.KEYBCS2_BIN = 73;
exports.KOI8R_BIN = 74;
exports.KOI8U_BIN = 75;
exports.LATIN2_BIN = 77;
exports.LATIN5_BIN = 78;
exports.LATIN7_BIN = 79;
exports.CP850_BIN = 80;
exports.CP852_BIN = 81;
exports.SWE7_BIN = 82;
exports.UTF8_BIN = 83;
exports.BIG5_BIN = 84;
exports.EUCKR_BIN = 85;
exports.GB2312_BIN = 86;
exports.GBK_BIN = 87;
exports.SJIS_BIN = 88;
exports.TIS620_BIN = 89;
exports.UCS2_BIN = 90;
exports.UJIS_BIN = 91;
exports.GEOSTD8_GENERAL_CI = 92;
exports.GEOSTD8_BIN = 93;
exports.LATIN1_SPANISH_CI = 94;
exports.CP932_JAPANESE_CI = 95;
exports.CP932_BIN = 96;
exports.EUCJPMS_JAPANESE_CI = 97;
exports.EUCJPMS_BIN = 98;
exports.CP1250_POLISH_CI = 99;
exports.UCS2_UNICODE_CI = 128;
exports.UCS2_ICELANDIC_CI = 129;
exports.UCS2_LATVIAN_CI = 130;
exports.UCS2_ROMANIAN_CI = 131;
exports.UCS2_SLOVENIAN_CI = 132;
exports.UCS2_POLISH_CI = 133;
exports.UCS2_ESTONIAN_CI = 134;
exports.UCS2_SPANISH_CI = 135;
exports.UCS2_SWEDISH_CI = 136;
exports.UCS2_TURKISH_CI = 137;
exports.UCS2_CZECH_CI = 138;
exports.UCS2_DANISH_CI = 139;
exports.UCS2_LITHUANIAN_CI = 140;
exports.UCS2_SLOVAK_CI = 141;
exports.UCS2_SPANISH2_CI = 142;
exports.UCS2_ROMAN_CI = 143;
exports.UCS2_PERSIAN_CI = 144;
exports.UCS2_ESPERANTO_CI = 145;
exports.UCS2_HUNGARIAN_CI = 146;
exports.UTF8_UNICODE_CI = 192;
exports.UTF8_ICELANDIC_CI = 193;
exports.UTF8_LATVIAN_CI = 194;
exports.UTF8_ROMANIAN_CI = 195;
exports.UTF8_SLOVENIAN_CI = 196;
exports.UTF8_POLISH_CI = 197;
exports.UTF8_ESTONIAN_CI = 198;
exports.UTF8_SPANISH_CI = 199;
exports.UTF8_SWEDISH_CI = 200;
exports.UTF8_TURKISH_CI = 201;
exports.UTF8_CZECH_CI = 202;
exports.UTF8_DANISH_CI = 203;
exports.UTF8_LITHUANIAN_CI = 204;
exports.UTF8_SLOVAK_CI = 205;
exports.UTF8_SPANISH2_CI = 206;
exports.UTF8_ROMAN_CI = 207;
exports.UTF8_PERSIAN_CI = 208;
exports.UTF8_ESPERANTO_CI = 209;
exports.UTF8_HUNGARIAN_CI = 210;
+26
View File
@@ -0,0 +1,26 @@
// Manually extracted from mysql-5.5.23/include/mysql_com.h
exports.CLIENT_LONG_PASSWORD = 1; /* new more secure passwords */
exports.CLIENT_FOUND_ROWS = 2; /* Found instead of affected rows */
exports.CLIENT_LONG_FLAG = 4; /* Get all column flags */
exports.CLIENT_CONNECT_WITH_DB = 8; /* One can specify db on connect */
exports.CLIENT_NO_SCHEMA = 16; /* Don't allow database.table.column */
exports.CLIENT_COMPRESS = 32; /* Can use compression protocol */
exports.CLIENT_ODBC = 64; /* Odbc client */
exports.CLIENT_LOCAL_FILES = 128; /* Can use LOAD DATA LOCAL */
exports.CLIENT_IGNORE_SPACE = 256; /* Ignore spaces before '(' */
exports.CLIENT_PROTOCOL_41 = 512; /* New 4.1 protocol */
exports.CLIENT_INTERACTIVE = 1024; /* This is an interactive client */
exports.CLIENT_SSL = 2048; /* Switch to SSL after handshake */
exports.CLIENT_IGNORE_SIGPIPE = 4096; /* IGNORE sigpipes */
exports.CLIENT_TRANSACTIONS = 8192; /* Client knows about transactions */
exports.CLIENT_RESERVED = 16384; /* Old flag for 4.1 protocol */
exports.CLIENT_SECURE_CONNECTION = 32768; /* New 4.1 authentication */
exports.CLIENT_MULTI_STATEMENTS = 65536; /* Enable/disable multi-stmt support */
exports.CLIENT_MULTI_RESULTS = 131072; /* Enable/disable multi-results */
exports.CLIENT_PS_MULTI_RESULTS = 262144; /* Multi-results in PS-protocol */
exports.CLIENT_PLUGIN_AUTH = 524288; /* Client supports plugin authentication */
exports.CLIENT_SSL_VERIFY_SERVER_CERT = 1073741824;
exports.CLIENT_REMEMBER_OPTIONS = 2147483648;
+725
View File
@@ -0,0 +1,725 @@
// Generated by generate-error-constants.js, do not modify by hand
exports[1000] = 'ER_HASHCHK';
exports[1001] = 'ER_NISAMCHK';
exports[1002] = 'ER_NO';
exports[1003] = 'ER_YES';
exports[1004] = 'ER_CANT_CREATE_FILE';
exports[1005] = 'ER_CANT_CREATE_TABLE';
exports[1006] = 'ER_CANT_CREATE_DB';
exports[1007] = 'ER_DB_CREATE_EXISTS';
exports[1008] = 'ER_DB_DROP_EXISTS';
exports[1009] = 'ER_DB_DROP_DELETE';
exports[1010] = 'ER_DB_DROP_RMDIR';
exports[1011] = 'ER_CANT_DELETE_FILE';
exports[1012] = 'ER_CANT_FIND_SYSTEM_REC';
exports[1013] = 'ER_CANT_GET_STAT';
exports[1014] = 'ER_CANT_GET_WD';
exports[1015] = 'ER_CANT_LOCK';
exports[1016] = 'ER_CANT_OPEN_FILE';
exports[1017] = 'ER_FILE_NOT_FOUND';
exports[1018] = 'ER_CANT_READ_DIR';
exports[1019] = 'ER_CANT_SET_WD';
exports[1020] = 'ER_CHECKREAD';
exports[1021] = 'ER_DISK_FULL';
exports[1022] = 'ER_DUP_KEY';
exports[1023] = 'ER_ERROR_ON_CLOSE';
exports[1024] = 'ER_ERROR_ON_READ';
exports[1025] = 'ER_ERROR_ON_RENAME';
exports[1026] = 'ER_ERROR_ON_WRITE';
exports[1027] = 'ER_FILE_USED';
exports[1028] = 'ER_FILSORT_ABORT';
exports[1029] = 'ER_FORM_NOT_FOUND';
exports[1030] = 'ER_GET_ERRNO';
exports[1031] = 'ER_ILLEGAL_HA';
exports[1032] = 'ER_KEY_NOT_FOUND';
exports[1033] = 'ER_NOT_FORM_FILE';
exports[1034] = 'ER_NOT_KEYFILE';
exports[1035] = 'ER_OLD_KEYFILE';
exports[1036] = 'ER_OPEN_AS_READONLY';
exports[1037] = 'ER_OUTOFMEMORY';
exports[1038] = 'ER_OUT_OF_SORTMEMORY';
exports[1039] = 'ER_UNEXPECTED_EOF';
exports[1040] = 'ER_CON_COUNT_ERROR';
exports[1041] = 'ER_OUT_OF_RESOURCES';
exports[1042] = 'ER_BAD_HOST_ERROR';
exports[1043] = 'ER_HANDSHAKE_ERROR';
exports[1044] = 'ER_DBACCESS_DENIED_ERROR';
exports[1045] = 'ER_ACCESS_DENIED_ERROR';
exports[1046] = 'ER_NO_DB_ERROR';
exports[1047] = 'ER_UNKNOWN_COM_ERROR';
exports[1048] = 'ER_BAD_NULL_ERROR';
exports[1049] = 'ER_BAD_DB_ERROR';
exports[1050] = 'ER_TABLE_EXISTS_ERROR';
exports[1051] = 'ER_BAD_TABLE_ERROR';
exports[1052] = 'ER_NON_UNIQ_ERROR';
exports[1053] = 'ER_SERVER_SHUTDOWN';
exports[1054] = 'ER_BAD_FIELD_ERROR';
exports[1055] = 'ER_WRONG_FIELD_WITH_GROUP';
exports[1056] = 'ER_WRONG_GROUP_FIELD';
exports[1057] = 'ER_WRONG_SUM_SELECT';
exports[1058] = 'ER_WRONG_VALUE_COUNT';
exports[1059] = 'ER_TOO_LONG_IDENT';
exports[1060] = 'ER_DUP_FIELDNAME';
exports[1061] = 'ER_DUP_KEYNAME';
exports[1062] = 'ER_DUP_ENTRY';
exports[1063] = 'ER_WRONG_FIELD_SPEC';
exports[1064] = 'ER_PARSE_ERROR';
exports[1065] = 'ER_EMPTY_QUERY';
exports[1066] = 'ER_NONUNIQ_TABLE';
exports[1067] = 'ER_INVALID_DEFAULT';
exports[1068] = 'ER_MULTIPLE_PRI_KEY';
exports[1069] = 'ER_TOO_MANY_KEYS';
exports[1070] = 'ER_TOO_MANY_KEY_PARTS';
exports[1071] = 'ER_TOO_LONG_KEY';
exports[1072] = 'ER_KEY_COLUMN_DOES_NOT_EXITS';
exports[1073] = 'ER_BLOB_USED_AS_KEY';
exports[1074] = 'ER_TOO_BIG_FIELDLENGTH';
exports[1075] = 'ER_WRONG_AUTO_KEY';
exports[1076] = 'ER_READY';
exports[1077] = 'ER_NORMAL_SHUTDOWN';
exports[1078] = 'ER_GOT_SIGNAL';
exports[1079] = 'ER_SHUTDOWN_COMPLETE';
exports[1080] = 'ER_FORCING_CLOSE';
exports[1081] = 'ER_IPSOCK_ERROR';
exports[1082] = 'ER_NO_SUCH_INDEX';
exports[1083] = 'ER_WRONG_FIELD_TERMINATORS';
exports[1084] = 'ER_BLOBS_AND_NO_TERMINATED';
exports[1085] = 'ER_TEXTFILE_NOT_READABLE';
exports[1086] = 'ER_FILE_EXISTS_ERROR';
exports[1087] = 'ER_LOAD_INFO';
exports[1088] = 'ER_ALTER_INFO';
exports[1089] = 'ER_WRONG_SUB_KEY';
exports[1090] = 'ER_CANT_REMOVE_ALL_FIELDS';
exports[1091] = 'ER_CANT_DROP_FIELD_OR_KEY';
exports[1092] = 'ER_INSERT_INFO';
exports[1093] = 'ER_UPDATE_TABLE_USED';
exports[1094] = 'ER_NO_SUCH_THREAD';
exports[1095] = 'ER_KILL_DENIED_ERROR';
exports[1096] = 'ER_NO_TABLES_USED';
exports[1097] = 'ER_TOO_BIG_SET';
exports[1098] = 'ER_NO_UNIQUE_LOGFILE';
exports[1099] = 'ER_TABLE_NOT_LOCKED_FOR_WRITE';
exports[1100] = 'ER_TABLE_NOT_LOCKED';
exports[1101] = 'ER_BLOB_CANT_HAVE_DEFAULT';
exports[1102] = 'ER_WRONG_DB_NAME';
exports[1103] = 'ER_WRONG_TABLE_NAME';
exports[1104] = 'ER_TOO_BIG_SELECT';
exports[1105] = 'ER_UNKNOWN_ERROR';
exports[1106] = 'ER_UNKNOWN_PROCEDURE';
exports[1107] = 'ER_WRONG_PARAMCOUNT_TO_PROCEDURE';
exports[1108] = 'ER_WRONG_PARAMETERS_TO_PROCEDURE';
exports[1109] = 'ER_UNKNOWN_TABLE';
exports[1110] = 'ER_FIELD_SPECIFIED_TWICE';
exports[1111] = 'ER_INVALID_GROUP_FUNC_USE';
exports[1112] = 'ER_UNSUPPORTED_EXTENSION';
exports[1113] = 'ER_TABLE_MUST_HAVE_COLUMNS';
exports[1114] = 'ER_RECORD_FILE_FULL';
exports[1115] = 'ER_UNKNOWN_CHARACTER_SET';
exports[1116] = 'ER_TOO_MANY_TABLES';
exports[1117] = 'ER_TOO_MANY_FIELDS';
exports[1118] = 'ER_TOO_BIG_ROWSIZE';
exports[1119] = 'ER_STACK_OVERRUN';
exports[1120] = 'ER_WRONG_OUTER_JOIN';
exports[1121] = 'ER_NULL_COLUMN_IN_INDEX';
exports[1122] = 'ER_CANT_FIND_UDF';
exports[1123] = 'ER_CANT_INITIALIZE_UDF';
exports[1124] = 'ER_UDF_NO_PATHS';
exports[1125] = 'ER_UDF_EXISTS';
exports[1126] = 'ER_CANT_OPEN_LIBRARY';
exports[1127] = 'ER_CANT_FIND_DL_ENTRY';
exports[1128] = 'ER_FUNCTION_NOT_DEFINED';
exports[1129] = 'ER_HOST_IS_BLOCKED';
exports[1130] = 'ER_HOST_NOT_PRIVILEGED';
exports[1131] = 'ER_PASSWORD_ANONYMOUS_USER';
exports[1132] = 'ER_PASSWORD_NOT_ALLOWED';
exports[1133] = 'ER_PASSWORD_NO_MATCH';
exports[1134] = 'ER_UPDATE_INFO';
exports[1135] = 'ER_CANT_CREATE_THREAD';
exports[1136] = 'ER_WRONG_VALUE_COUNT_ON_ROW';
exports[1137] = 'ER_CANT_REOPEN_TABLE';
exports[1138] = 'ER_INVALID_USE_OF_NULL';
exports[1139] = 'ER_REGEXP_ERROR';
exports[1140] = 'ER_MIX_OF_GROUP_FUNC_AND_FIELDS';
exports[1141] = 'ER_NONEXISTING_GRANT';
exports[1142] = 'ER_TABLEACCESS_DENIED_ERROR';
exports[1143] = 'ER_COLUMNACCESS_DENIED_ERROR';
exports[1144] = 'ER_ILLEGAL_GRANT_FOR_TABLE';
exports[1145] = 'ER_GRANT_WRONG_HOST_OR_USER';
exports[1146] = 'ER_NO_SUCH_TABLE';
exports[1147] = 'ER_NONEXISTING_TABLE_GRANT';
exports[1148] = 'ER_NOT_ALLOWED_COMMAND';
exports[1149] = 'ER_SYNTAX_ERROR';
exports[1150] = 'ER_DELAYED_CANT_CHANGE_LOCK';
exports[1151] = 'ER_TOO_MANY_DELAYED_THREADS';
exports[1152] = 'ER_ABORTING_CONNECTION';
exports[1153] = 'ER_NET_PACKET_TOO_LARGE';
exports[1154] = 'ER_NET_READ_ERROR_FROM_PIPE';
exports[1155] = 'ER_NET_FCNTL_ERROR';
exports[1156] = 'ER_NET_PACKETS_OUT_OF_ORDER';
exports[1157] = 'ER_NET_UNCOMPRESS_ERROR';
exports[1158] = 'ER_NET_READ_ERROR';
exports[1159] = 'ER_NET_READ_INTERRUPTED';
exports[1160] = 'ER_NET_ERROR_ON_WRITE';
exports[1161] = 'ER_NET_WRITE_INTERRUPTED';
exports[1162] = 'ER_TOO_LONG_STRING';
exports[1163] = 'ER_TABLE_CANT_HANDLE_BLOB';
exports[1164] = 'ER_TABLE_CANT_HANDLE_AUTO_INCREMENT';
exports[1165] = 'ER_DELAYED_INSERT_TABLE_LOCKED';
exports[1166] = 'ER_WRONG_COLUMN_NAME';
exports[1167] = 'ER_WRONG_KEY_COLUMN';
exports[1168] = 'ER_WRONG_MRG_TABLE';
exports[1169] = 'ER_DUP_UNIQUE';
exports[1170] = 'ER_BLOB_KEY_WITHOUT_LENGTH';
exports[1171] = 'ER_PRIMARY_CANT_HAVE_NULL';
exports[1172] = 'ER_TOO_MANY_ROWS';
exports[1173] = 'ER_REQUIRES_PRIMARY_KEY';
exports[1174] = 'ER_NO_RAID_COMPILED';
exports[1175] = 'ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE';
exports[1176] = 'ER_KEY_DOES_NOT_EXITS';
exports[1177] = 'ER_CHECK_NO_SUCH_TABLE';
exports[1178] = 'ER_CHECK_NOT_IMPLEMENTED';
exports[1179] = 'ER_CANT_DO_THIS_DURING_AN_TRANSACTION';
exports[1180] = 'ER_ERROR_DURING_COMMIT';
exports[1181] = 'ER_ERROR_DURING_ROLLBACK';
exports[1182] = 'ER_ERROR_DURING_FLUSH_LOGS';
exports[1183] = 'ER_ERROR_DURING_CHECKPOINT';
exports[1184] = 'ER_NEW_ABORTING_CONNECTION';
exports[1185] = 'ER_DUMP_NOT_IMPLEMENTED';
exports[1186] = 'ER_FLUSH_MASTER_BINLOG_CLOSED';
exports[1187] = 'ER_INDEX_REBUILD';
exports[1188] = 'ER_MASTER';
exports[1189] = 'ER_MASTER_NET_READ';
exports[1190] = 'ER_MASTER_NET_WRITE';
exports[1191] = 'ER_FT_MATCHING_KEY_NOT_FOUND';
exports[1192] = 'ER_LOCK_OR_ACTIVE_TRANSACTION';
exports[1193] = 'ER_UNKNOWN_SYSTEM_VARIABLE';
exports[1194] = 'ER_CRASHED_ON_USAGE';
exports[1195] = 'ER_CRASHED_ON_REPAIR';
exports[1196] = 'ER_WARNING_NOT_COMPLETE_ROLLBACK';
exports[1197] = 'ER_TRANS_CACHE_FULL';
exports[1198] = 'ER_SLAVE_MUST_STOP';
exports[1199] = 'ER_SLAVE_NOT_RUNNING';
exports[1200] = 'ER_BAD_SLAVE';
exports[1201] = 'ER_MASTER_INFO';
exports[1202] = 'ER_SLAVE_THREAD';
exports[1203] = 'ER_TOO_MANY_USER_CONNECTIONS';
exports[1204] = 'ER_SET_CONSTANTS_ONLY';
exports[1205] = 'ER_LOCK_WAIT_TIMEOUT';
exports[1206] = 'ER_LOCK_TABLE_FULL';
exports[1207] = 'ER_READ_ONLY_TRANSACTION';
exports[1208] = 'ER_DROP_DB_WITH_READ_LOCK';
exports[1209] = 'ER_CREATE_DB_WITH_READ_LOCK';
exports[1210] = 'ER_WRONG_ARGUMENTS';
exports[1211] = 'ER_NO_PERMISSION_TO_CREATE_USER';
exports[1212] = 'ER_UNION_TABLES_IN_DIFFERENT_DIR';
exports[1213] = 'ER_LOCK_DEADLOCK';
exports[1214] = 'ER_TABLE_CANT_HANDLE_FT';
exports[1215] = 'ER_CANNOT_ADD_FOREIGN';
exports[1216] = 'ER_NO_REFERENCED_ROW';
exports[1217] = 'ER_ROW_IS_REFERENCED';
exports[1218] = 'ER_CONNECT_TO_MASTER';
exports[1219] = 'ER_QUERY_ON_MASTER';
exports[1220] = 'ER_ERROR_WHEN_EXECUTING_COMMAND';
exports[1221] = 'ER_WRONG_USAGE';
exports[1222] = 'ER_WRONG_NUMBER_OF_COLUMNS_IN_SELECT';
exports[1223] = 'ER_CANT_UPDATE_WITH_READLOCK';
exports[1224] = 'ER_MIXING_NOT_ALLOWED';
exports[1225] = 'ER_DUP_ARGUMENT';
exports[1226] = 'ER_USER_LIMIT_REACHED';
exports[1227] = 'ER_SPECIFIC_ACCESS_DENIED_ERROR';
exports[1228] = 'ER_LOCAL_VARIABLE';
exports[1229] = 'ER_GLOBAL_VARIABLE';
exports[1230] = 'ER_NO_DEFAULT';
exports[1231] = 'ER_WRONG_VALUE_FOR_VAR';
exports[1232] = 'ER_WRONG_TYPE_FOR_VAR';
exports[1233] = 'ER_VAR_CANT_BE_READ';
exports[1234] = 'ER_CANT_USE_OPTION_HERE';
exports[1235] = 'ER_NOT_SUPPORTED_YET';
exports[1236] = 'ER_MASTER_FATAL_ERROR_READING_BINLOG';
exports[1237] = 'ER_SLAVE_IGNORED_TABLE';
exports[1238] = 'ER_INCORRECT_GLOBAL_LOCAL_VAR';
exports[1239] = 'ER_WRONG_FK_DEF';
exports[1240] = 'ER_KEY_REF_DO_NOT_MATCH_TABLE_REF';
exports[1241] = 'ER_OPERAND_COLUMNS';
exports[1242] = 'ER_SUBQUERY_NO_';
exports[1243] = 'ER_UNKNOWN_STMT_HANDLER';
exports[1244] = 'ER_CORRUPT_HELP_DB';
exports[1245] = 'ER_CYCLIC_REFERENCE';
exports[1246] = 'ER_AUTO_CONVERT';
exports[1247] = 'ER_ILLEGAL_REFERENCE';
exports[1248] = 'ER_DERIVED_MUST_HAVE_ALIAS';
exports[1249] = 'ER_SELECT_REDUCED';
exports[1250] = 'ER_TABLENAME_NOT_ALLOWED_HERE';
exports[1251] = 'ER_NOT_SUPPORTED_AUTH_MODE';
exports[1252] = 'ER_SPATIAL_CANT_HAVE_NULL';
exports[1253] = 'ER_COLLATION_CHARSET_MISMATCH';
exports[1254] = 'ER_SLAVE_WAS_RUNNING';
exports[1255] = 'ER_SLAVE_WAS_NOT_RUNNING';
exports[1256] = 'ER_TOO_BIG_FOR_UNCOMPRESS';
exports[1257] = 'ER_ZLIB_Z_MEM_ERROR';
exports[1258] = 'ER_ZLIB_Z_BUF_ERROR';
exports[1259] = 'ER_ZLIB_Z_DATA_ERROR';
exports[1260] = 'ER_CUT_VALUE_GROUP_CONCAT';
exports[1261] = 'ER_WARN_TOO_FEW_RECORDS';
exports[1262] = 'ER_WARN_TOO_MANY_RECORDS';
exports[1263] = 'ER_WARN_NULL_TO_NOTNULL';
exports[1264] = 'ER_WARN_DATA_OUT_OF_RANGE';
exports[1265] = 'WARN_DATA_TRUNCATED';
exports[1266] = 'ER_WARN_USING_OTHER_HANDLER';
exports[1267] = 'ER_CANT_AGGREGATE_';
exports[1268] = 'ER_DROP_USER';
exports[1269] = 'ER_REVOKE_GRANTS';
exports[1270] = 'ER_CANT_AGGREGATE_';
exports[1271] = 'ER_CANT_AGGREGATE_NCOLLATIONS';
exports[1272] = 'ER_VARIABLE_IS_NOT_STRUCT';
exports[1273] = 'ER_UNKNOWN_COLLATION';
exports[1274] = 'ER_SLAVE_IGNORED_SSL_PARAMS';
exports[1275] = 'ER_SERVER_IS_IN_SECURE_AUTH_MODE';
exports[1276] = 'ER_WARN_FIELD_RESOLVED';
exports[1277] = 'ER_BAD_SLAVE_UNTIL_COND';
exports[1278] = 'ER_MISSING_SKIP_SLAVE';
exports[1279] = 'ER_UNTIL_COND_IGNORED';
exports[1280] = 'ER_WRONG_NAME_FOR_INDEX';
exports[1281] = 'ER_WRONG_NAME_FOR_CATALOG';
exports[1282] = 'ER_WARN_QC_RESIZE';
exports[1283] = 'ER_BAD_FT_COLUMN';
exports[1284] = 'ER_UNKNOWN_KEY_CACHE';
exports[1285] = 'ER_WARN_HOSTNAME_WONT_WORK';
exports[1286] = 'ER_UNKNOWN_STORAGE_ENGINE';
exports[1287] = 'ER_WARN_DEPRECATED_SYNTAX';
exports[1288] = 'ER_NON_UPDATABLE_TABLE';
exports[1289] = 'ER_FEATURE_DISABLED';
exports[1290] = 'ER_OPTION_PREVENTS_STATEMENT';
exports[1291] = 'ER_DUPLICATED_VALUE_IN_TYPE';
exports[1292] = 'ER_TRUNCATED_WRONG_VALUE';
exports[1293] = 'ER_TOO_MUCH_AUTO_TIMESTAMP_COLS';
exports[1294] = 'ER_INVALID_ON_UPDATE';
exports[1295] = 'ER_UNSUPPORTED_PS';
exports[1296] = 'ER_GET_ERRMSG';
exports[1297] = 'ER_GET_TEMPORARY_ERRMSG';
exports[1298] = 'ER_UNKNOWN_TIME_ZONE';
exports[1299] = 'ER_WARN_INVALID_TIMESTAMP';
exports[1300] = 'ER_INVALID_CHARACTER_STRING';
exports[1301] = 'ER_WARN_ALLOWED_PACKET_OVERFLOWED';
exports[1302] = 'ER_CONFLICTING_DECLARATIONS';
exports[1303] = 'ER_SP_NO_RECURSIVE_CREATE';
exports[1304] = 'ER_SP_ALREADY_EXISTS';
exports[1305] = 'ER_SP_DOES_NOT_EXIST';
exports[1306] = 'ER_SP_DROP_FAILED';
exports[1307] = 'ER_SP_STORE_FAILED';
exports[1308] = 'ER_SP_LILABEL_MISMATCH';
exports[1309] = 'ER_SP_LABEL_REDEFINE';
exports[1310] = 'ER_SP_LABEL_MISMATCH';
exports[1311] = 'ER_SP_UNINIT_VAR';
exports[1312] = 'ER_SP_BADSELECT';
exports[1313] = 'ER_SP_BADRETURN';
exports[1314] = 'ER_SP_BADSTATEMENT';
exports[1315] = 'ER_UPDATE_LOG_DEPRECATED_IGNORED';
exports[1316] = 'ER_UPDATE_LOG_DEPRECATED_TRANSLATED';
exports[1317] = 'ER_QUERY_INTERRUPTED';
exports[1318] = 'ER_SP_WRONG_NO_OF_ARGS';
exports[1319] = 'ER_SP_COND_MISMATCH';
exports[1320] = 'ER_SP_NORETURN';
exports[1321] = 'ER_SP_NORETURNEND';
exports[1322] = 'ER_SP_BAD_CURSOR_QUERY';
exports[1323] = 'ER_SP_BAD_CURSOR_SELECT';
exports[1324] = 'ER_SP_CURSOR_MISMATCH';
exports[1325] = 'ER_SP_CURSOR_ALREADY_OPEN';
exports[1326] = 'ER_SP_CURSOR_NOT_OPEN';
exports[1327] = 'ER_SP_UNDECLARED_VAR';
exports[1328] = 'ER_SP_WRONG_NO_OF_FETCH_ARGS';
exports[1329] = 'ER_SP_FETCH_NO_DATA';
exports[1330] = 'ER_SP_DUP_PARAM';
exports[1331] = 'ER_SP_DUP_VAR';
exports[1332] = 'ER_SP_DUP_COND';
exports[1333] = 'ER_SP_DUP_CURS';
exports[1334] = 'ER_SP_CANT_ALTER';
exports[1335] = 'ER_SP_SUBSELECT_NYI';
exports[1336] = 'ER_STMT_NOT_ALLOWED_IN_SF_OR_TRG';
exports[1337] = 'ER_SP_VARCOND_AFTER_CURSHNDLR';
exports[1338] = 'ER_SP_CURSOR_AFTER_HANDLER';
exports[1339] = 'ER_SP_CASE_NOT_FOUND';
exports[1340] = 'ER_FPARSER_TOO_BIG_FILE';
exports[1341] = 'ER_FPARSER_BAD_HEADER';
exports[1342] = 'ER_FPARSER_EOF_IN_COMMENT';
exports[1343] = 'ER_FPARSER_ERROR_IN_PARAMETER';
exports[1344] = 'ER_FPARSER_EOF_IN_UNKNOWN_PARAMETER';
exports[1345] = 'ER_VIEW_NO_EXPLAIN';
exports[1346] = 'ER_FRM_UNKNOWN_TYPE';
exports[1347] = 'ER_WRONG_OBJECT';
exports[1348] = 'ER_NONUPDATEABLE_COLUMN';
exports[1349] = 'ER_VIEW_SELECT_DERIVED';
exports[1350] = 'ER_VIEW_SELECT_CLAUSE';
exports[1351] = 'ER_VIEW_SELECT_VARIABLE';
exports[1352] = 'ER_VIEW_SELECT_TMPTABLE';
exports[1353] = 'ER_VIEW_WRONG_LIST';
exports[1354] = 'ER_WARN_VIEW_MERGE';
exports[1355] = 'ER_WARN_VIEW_WITHOUT_KEY';
exports[1356] = 'ER_VIEW_INVALID';
exports[1357] = 'ER_SP_NO_DROP_SP';
exports[1358] = 'ER_SP_GOTO_IN_HNDLR';
exports[1359] = 'ER_TRG_ALREADY_EXISTS';
exports[1360] = 'ER_TRG_DOES_NOT_EXIST';
exports[1361] = 'ER_TRG_ON_VIEW_OR_TEMP_TABLE';
exports[1362] = 'ER_TRG_CANT_CHANGE_ROW';
exports[1363] = 'ER_TRG_NO_SUCH_ROW_IN_TRG';
exports[1364] = 'ER_NO_DEFAULT_FOR_FIELD';
exports[1365] = 'ER_DIVISION_BY_ZERO';
exports[1366] = 'ER_TRUNCATED_WRONG_VALUE_FOR_FIELD';
exports[1367] = 'ER_ILLEGAL_VALUE_FOR_TYPE';
exports[1368] = 'ER_VIEW_NONUPD_CHECK';
exports[1369] = 'ER_VIEW_CHECK_FAILED';
exports[1370] = 'ER_PROCACCESS_DENIED_ERROR';
exports[1371] = 'ER_RELAY_LOG_FAIL';
exports[1372] = 'ER_PASSWD_LENGTH';
exports[1373] = 'ER_UNKNOWN_TARGET_BINLOG';
exports[1374] = 'ER_IO_ERR_LOG_INDEX_READ';
exports[1375] = 'ER_BINLOG_PURGE_PROHIBITED';
exports[1376] = 'ER_FSEEK_FAIL';
exports[1377] = 'ER_BINLOG_PURGE_FATAL_ERR';
exports[1378] = 'ER_LOG_IN_USE';
exports[1379] = 'ER_LOG_PURGE_UNKNOWN_ERR';
exports[1380] = 'ER_RELAY_LOG_INIT';
exports[1381] = 'ER_NO_BINARY_LOGGING';
exports[1382] = 'ER_RESERVED_SYNTAX';
exports[1383] = 'ER_WSAS_FAILED';
exports[1384] = 'ER_DIFF_GROUPS_PROC';
exports[1385] = 'ER_NO_GROUP_FOR_PROC';
exports[1386] = 'ER_ORDER_WITH_PROC';
exports[1387] = 'ER_LOGGING_PROHIBIT_CHANGING_OF';
exports[1388] = 'ER_NO_FILE_MAPPING';
exports[1389] = 'ER_WRONG_MAGIC';
exports[1390] = 'ER_PS_MANY_PARAM';
exports[1391] = 'ER_KEY_PART_';
exports[1392] = 'ER_VIEW_CHECKSUM';
exports[1393] = 'ER_VIEW_MULTIUPDATE';
exports[1394] = 'ER_VIEW_NO_INSERT_FIELD_LIST';
exports[1395] = 'ER_VIEW_DELETE_MERGE_VIEW';
exports[1396] = 'ER_CANNOT_USER';
exports[1397] = 'ER_XAER_NOTA';
exports[1398] = 'ER_XAER_INVAL';
exports[1399] = 'ER_XAER_RMFAIL';
exports[1400] = 'ER_XAER_OUTSIDE';
exports[1401] = 'ER_XAER_RMERR';
exports[1402] = 'ER_XA_RBROLLBACK';
exports[1403] = 'ER_NONEXISTING_PROC_GRANT';
exports[1404] = 'ER_PROC_AUTO_GRANT_FAIL';
exports[1405] = 'ER_PROC_AUTO_REVOKE_FAIL';
exports[1406] = 'ER_DATA_TOO_LONG';
exports[1407] = 'ER_SP_BAD_SQLSTATE';
exports[1408] = 'ER_STARTUP';
exports[1409] = 'ER_LOAD_FROM_FIXED_SIZE_ROWS_TO_VAR';
exports[1410] = 'ER_CANT_CREATE_USER_WITH_GRANT';
exports[1411] = 'ER_WRONG_VALUE_FOR_TYPE';
exports[1412] = 'ER_TABLE_DEF_CHANGED';
exports[1413] = 'ER_SP_DUP_HANDLER';
exports[1414] = 'ER_SP_NOT_VAR_ARG';
exports[1415] = 'ER_SP_NO_RETSET';
exports[1416] = 'ER_CANT_CREATE_GEOMETRY_OBJECT';
exports[1417] = 'ER_FAILED_ROUTINE_BREAK_BINLOG';
exports[1418] = 'ER_BINLOG_UNSAFE_ROUTINE';
exports[1419] = 'ER_BINLOG_CREATE_ROUTINE_NEED_SUPER';
exports[1420] = 'ER_EXEC_STMT_WITH_OPEN_CURSOR';
exports[1421] = 'ER_STMT_HAS_NO_OPEN_CURSOR';
exports[1422] = 'ER_COMMIT_NOT_ALLOWED_IN_SF_OR_TRG';
exports[1423] = 'ER_NO_DEFAULT_FOR_VIEW_FIELD';
exports[1424] = 'ER_SP_NO_RECURSION';
exports[1425] = 'ER_TOO_BIG_SCALE';
exports[1426] = 'ER_TOO_BIG_PRECISION';
exports[1427] = 'ER_M_BIGGER_THAN_D';
exports[1428] = 'ER_WRONG_LOCK_OF_SYSTEM_TABLE';
exports[1429] = 'ER_CONNECT_TO_FOREIGN_DATA_SOURCE';
exports[1430] = 'ER_QUERY_ON_FOREIGN_DATA_SOURCE';
exports[1431] = 'ER_FOREIGN_DATA_SOURCE_DOESNT_EXIST';
exports[1432] = 'ER_FOREIGN_DATA_STRING_INVALID_CANT_CREATE';
exports[1433] = 'ER_FOREIGN_DATA_STRING_INVALID';
exports[1434] = 'ER_CANT_CREATE_FEDERATED_TABLE';
exports[1435] = 'ER_TRG_IN_WRONG_SCHEMA';
exports[1436] = 'ER_STACK_OVERRUN_NEED_MORE';
exports[1437] = 'ER_TOO_LONG_BODY';
exports[1438] = 'ER_WARN_CANT_DROP_DEFAULT_KEYCACHE';
exports[1439] = 'ER_TOO_BIG_DISPLAYWIDTH';
exports[1440] = 'ER_XAER_DUPID';
exports[1441] = 'ER_DATETIME_FUNCTION_OVERFLOW';
exports[1442] = 'ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG';
exports[1443] = 'ER_VIEW_PREVENT_UPDATE';
exports[1444] = 'ER_PS_NO_RECURSION';
exports[1445] = 'ER_SP_CANT_SET_AUTOCOMMIT';
exports[1446] = 'ER_MALFORMED_DEFINER';
exports[1447] = 'ER_VIEW_FRM_NO_USER';
exports[1448] = 'ER_VIEW_OTHER_USER';
exports[1449] = 'ER_NO_SUCH_USER';
exports[1450] = 'ER_FORBID_SCHEMA_CHANGE';
exports[1451] = 'ER_ROW_IS_REFERENCED_';
exports[1452] = 'ER_NO_REFERENCED_ROW_';
exports[1453] = 'ER_SP_BAD_VAR_SHADOW';
exports[1454] = 'ER_TRG_NO_DEFINER';
exports[1455] = 'ER_OLD_FILE_FORMAT';
exports[1456] = 'ER_SP_RECURSION_LIMIT';
exports[1457] = 'ER_SP_PROC_TABLE_CORRUPT';
exports[1458] = 'ER_SP_WRONG_NAME';
exports[1459] = 'ER_TABLE_NEEDS_UPGRADE';
exports[1460] = 'ER_SP_NO_AGGREGATE';
exports[1461] = 'ER_MAX_PREPARED_STMT_COUNT_REACHED';
exports[1462] = 'ER_VIEW_RECURSIVE';
exports[1463] = 'ER_NON_GROUPING_FIELD_USED';
exports[1464] = 'ER_TABLE_CANT_HANDLE_SPKEYS';
exports[1465] = 'ER_NO_TRIGGERS_ON_SYSTEM_SCHEMA';
exports[1466] = 'ER_REMOVED_SPACES';
exports[1467] = 'ER_AUTOINC_READ_FAILED';
exports[1468] = 'ER_USERNAME';
exports[1469] = 'ER_HOSTNAME';
exports[1470] = 'ER_WRONG_STRING_LENGTH';
exports[1471] = 'ER_NON_INSERTABLE_TABLE';
exports[1472] = 'ER_ADMIN_WRONG_MRG_TABLE';
exports[1473] = 'ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT';
exports[1474] = 'ER_NAME_BECOMES_EMPTY';
exports[1475] = 'ER_AMBIGUOUS_FIELD_TERM';
exports[1476] = 'ER_FOREIGN_SERVER_EXISTS';
exports[1477] = 'ER_FOREIGN_SERVER_DOESNT_EXIST';
exports[1478] = 'ER_ILLEGAL_HA_CREATE_OPTION';
exports[1479] = 'ER_PARTITION_REQUIRES_VALUES_ERROR';
exports[1480] = 'ER_PARTITION_WRONG_VALUES_ERROR';
exports[1481] = 'ER_PARTITION_MAXVALUE_ERROR';
exports[1482] = 'ER_PARTITION_SUBPARTITION_ERROR';
exports[1483] = 'ER_PARTITION_SUBPART_MIX_ERROR';
exports[1484] = 'ER_PARTITION_WRONG_NO_PART_ERROR';
exports[1485] = 'ER_PARTITION_WRONG_NO_SUBPART_ERROR';
exports[1486] = 'ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR';
exports[1487] = 'ER_NO_CONST_EXPR_IN_RANGE_OR_LIST_ERROR';
exports[1488] = 'ER_FIELD_NOT_FOUND_PART_ERROR';
exports[1489] = 'ER_LIST_OF_FIELDS_ONLY_IN_HASH_ERROR';
exports[1490] = 'ER_INCONSISTENT_PARTITION_INFO_ERROR';
exports[1491] = 'ER_PARTITION_FUNC_NOT_ALLOWED_ERROR';
exports[1492] = 'ER_PARTITIONS_MUST_BE_DEFINED_ERROR';
exports[1493] = 'ER_RANGE_NOT_INCREASING_ERROR';
exports[1494] = 'ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR';
exports[1495] = 'ER_MULTIPLE_DEF_CONST_IN_LIST_PART_ERROR';
exports[1496] = 'ER_PARTITION_ENTRY_ERROR';
exports[1497] = 'ER_MIX_HANDLER_ERROR';
exports[1498] = 'ER_PARTITION_NOT_DEFINED_ERROR';
exports[1499] = 'ER_TOO_MANY_PARTITIONS_ERROR';
exports[1500] = 'ER_SUBPARTITION_ERROR';
exports[1501] = 'ER_CANT_CREATE_HANDLER_FILE';
exports[1502] = 'ER_BLOB_FIELD_IN_PART_FUNC_ERROR';
exports[1503] = 'ER_UNIQUE_KEY_NEED_ALL_FIELDS_IN_PF';
exports[1504] = 'ER_NO_PARTS_ERROR';
exports[1505] = 'ER_PARTITION_MGMT_ON_NONPARTITIONED';
exports[1506] = 'ER_FOREIGN_KEY_ON_PARTITIONED';
exports[1507] = 'ER_DROP_PARTITION_NON_EXISTENT';
exports[1508] = 'ER_DROP_LAST_PARTITION';
exports[1509] = 'ER_COALESCE_ONLY_ON_HASH_PARTITION';
exports[1510] = 'ER_REORG_HASH_ONLY_ON_SAME_NO';
exports[1511] = 'ER_REORG_NO_PARAM_ERROR';
exports[1512] = 'ER_ONLY_ON_RANGE_LIST_PARTITION';
exports[1513] = 'ER_ADD_PARTITION_SUBPART_ERROR';
exports[1514] = 'ER_ADD_PARTITION_NO_NEW_PARTITION';
exports[1515] = 'ER_COALESCE_PARTITION_NO_PARTITION';
exports[1516] = 'ER_REORG_PARTITION_NOT_EXIST';
exports[1517] = 'ER_SAME_NAME_PARTITION';
exports[1518] = 'ER_NO_BINLOG_ERROR';
exports[1519] = 'ER_CONSECUTIVE_REORG_PARTITIONS';
exports[1520] = 'ER_REORG_OUTSIDE_RANGE';
exports[1521] = 'ER_PARTITION_FUNCTION_FAILURE';
exports[1522] = 'ER_PART_STATE_ERROR';
exports[1523] = 'ER_LIMITED_PART_RANGE';
exports[1524] = 'ER_PLUGIN_IS_NOT_LOADED';
exports[1525] = 'ER_WRONG_VALUE';
exports[1526] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE';
exports[1527] = 'ER_FILEGROUP_OPTION_ONLY_ONCE';
exports[1528] = 'ER_CREATE_FILEGROUP_FAILED';
exports[1529] = 'ER_DROP_FILEGROUP_FAILED';
exports[1530] = 'ER_TABLESPACE_AUTO_EXTEND_ERROR';
exports[1531] = 'ER_WRONG_SIZE_NUMBER';
exports[1532] = 'ER_SIZE_OVERFLOW_ERROR';
exports[1533] = 'ER_ALTER_FILEGROUP_FAILED';
exports[1534] = 'ER_BINLOG_ROW_LOGGING_FAILED';
exports[1535] = 'ER_BINLOG_ROW_WRONG_TABLE_DEF';
exports[1536] = 'ER_BINLOG_ROW_RBR_TO_SBR';
exports[1537] = 'ER_EVENT_ALREADY_EXISTS';
exports[1538] = 'ER_EVENT_STORE_FAILED';
exports[1539] = 'ER_EVENT_DOES_NOT_EXIST';
exports[1540] = 'ER_EVENT_CANT_ALTER';
exports[1541] = 'ER_EVENT_DROP_FAILED';
exports[1542] = 'ER_EVENT_INTERVAL_NOT_POSITIVE_OR_TOO_BIG';
exports[1543] = 'ER_EVENT_ENDS_BEFORE_STARTS';
exports[1544] = 'ER_EVENT_EXEC_TIME_IN_THE_PAST';
exports[1545] = 'ER_EVENT_OPEN_TABLE_FAILED';
exports[1546] = 'ER_EVENT_NEITHER_M_EXPR_NOR_M_AT';
exports[1547] = 'ER_COL_COUNT_DOESNT_MATCH_CORRUPTED';
exports[1548] = 'ER_CANNOT_LOAD_FROM_TABLE';
exports[1549] = 'ER_EVENT_CANNOT_DELETE';
exports[1550] = 'ER_EVENT_COMPILE_ERROR';
exports[1551] = 'ER_EVENT_SAME_NAME';
exports[1552] = 'ER_EVENT_DATA_TOO_LONG';
exports[1553] = 'ER_DROP_INDEX_FK';
exports[1554] = 'ER_WARN_DEPRECATED_SYNTAX_WITH_VER';
exports[1555] = 'ER_CANT_WRITE_LOCK_LOG_TABLE';
exports[1556] = 'ER_CANT_LOCK_LOG_TABLE';
exports[1557] = 'ER_FOREIGN_DUPLICATE_KEY';
exports[1558] = 'ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE';
exports[1559] = 'ER_TEMP_TABLE_PREVENTS_SWITCH_OUT_OF_RBR';
exports[1560] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_FORMAT';
exports[1561] = 'ER_NDB_CANT_SWITCH_BINLOG_FORMAT';
exports[1562] = 'ER_PARTITION_NO_TEMPORARY';
exports[1563] = 'ER_PARTITION_CONST_DOMAIN_ERROR';
exports[1564] = 'ER_PARTITION_FUNCTION_IS_NOT_ALLOWED';
exports[1565] = 'ER_DDL_LOG_ERROR';
exports[1566] = 'ER_NULL_IN_VALUES_LESS_THAN';
exports[1567] = 'ER_WRONG_PARTITION_NAME';
exports[1568] = 'ER_CANT_CHANGE_TX_ISOLATION';
exports[1569] = 'ER_DUP_ENTRY_AUTOINCREMENT_CASE';
exports[1570] = 'ER_EVENT_MODIFY_QUEUE_ERROR';
exports[1571] = 'ER_EVENT_SET_VAR_ERROR';
exports[1572] = 'ER_PARTITION_MERGE_ERROR';
exports[1573] = 'ER_CANT_ACTIVATE_LOG';
exports[1574] = 'ER_RBR_NOT_AVAILABLE';
exports[1575] = 'ER_BASE';
exports[1576] = 'ER_EVENT_RECURSION_FORBIDDEN';
exports[1577] = 'ER_EVENTS_DB_ERROR';
exports[1578] = 'ER_ONLY_INTEGERS_ALLOWED';
exports[1579] = 'ER_UNSUPORTED_LOG_ENGINE';
exports[1580] = 'ER_BAD_LOG_STATEMENT';
exports[1581] = 'ER_CANT_RENAME_LOG_TABLE';
exports[1582] = 'ER_WRONG_PARAMCOUNT_TO_NATIVE_FCT';
exports[1583] = 'ER_WRONG_PARAMETERS_TO_NATIVE_FCT';
exports[1584] = 'ER_WRONG_PARAMETERS_TO_STORED_FCT';
exports[1585] = 'ER_NATIVE_FCT_NAME_COLLISION';
exports[1586] = 'ER_DUP_ENTRY_WITH_KEY_NAME';
exports[1587] = 'ER_BINLOG_PURGE_EMFILE';
exports[1588] = 'ER_EVENT_CANNOT_CREATE_IN_THE_PAST';
exports[1589] = 'ER_EVENT_CANNOT_ALTER_IN_THE_PAST';
exports[1590] = 'ER_SLAVE_INCIDENT';
exports[1591] = 'ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT';
exports[1592] = 'ER_BINLOG_UNSAFE_STATEMENT';
exports[1593] = 'ER_SLAVE_FATAL_ERROR';
exports[1594] = 'ER_SLAVE_RELAY_LOG_READ_FAILURE';
exports[1595] = 'ER_SLAVE_RELAY_LOG_WRITE_FAILURE';
exports[1596] = 'ER_SLAVE_CREATE_EVENT_FAILURE';
exports[1597] = 'ER_SLAVE_MASTER_COM_FAILURE';
exports[1598] = 'ER_BINLOG_LOGGING_IMPOSSIBLE';
exports[1599] = 'ER_VIEW_NO_CREATION_CTX';
exports[1600] = 'ER_VIEW_INVALID_CREATION_CTX';
exports[1601] = 'ER_SR_INVALID_CREATION_CTX';
exports[1602] = 'ER_TRG_CORRUPTED_FILE';
exports[1603] = 'ER_TRG_NO_CREATION_CTX';
exports[1604] = 'ER_TRG_INVALID_CREATION_CTX';
exports[1605] = 'ER_EVENT_INVALID_CREATION_CTX';
exports[1606] = 'ER_TRG_CANT_OPEN_TABLE';
exports[1607] = 'ER_CANT_CREATE_SROUTINE';
exports[1608] = 'ER_NEVER_USED';
exports[1609] = 'ER_NO_FORMAT_DESCRIPTION_EVENT_BEFORE_BINLOG_STATEMENT';
exports[1610] = 'ER_SLAVE_CORRUPT_EVENT';
exports[1611] = 'ER_LOAD_DATA_INVALID_COLUMN';
exports[1612] = 'ER_LOG_PURGE_NO_FILE';
exports[1613] = 'ER_XA_RBTIMEOUT';
exports[1614] = 'ER_XA_RBDEADLOCK';
exports[1615] = 'ER_NEED_REPREPARE';
exports[1616] = 'ER_DELAYED_NOT_SUPPORTED';
exports[1617] = 'WARN_NO_MASTER_INFO';
exports[1618] = 'WARN_OPTION_IGNORED';
exports[1619] = 'WARN_PLUGIN_DELETE_BUILTIN';
exports[1620] = 'WARN_PLUGIN_BUSY';
exports[1621] = 'ER_VARIABLE_IS_READONLY';
exports[1622] = 'ER_WARN_ENGINE_TRANSACTION_ROLLBACK';
exports[1623] = 'ER_SLAVE_HEARTBEAT_FAILURE';
exports[1624] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE';
exports[1625] = 'ER_NDB_REPLICATION_SCHEMA_ERROR';
exports[1626] = 'ER_CONFLICT_FN_PARSE_ERROR';
exports[1627] = 'ER_EXCEPTIONS_WRITE_ERROR';
exports[1628] = 'ER_TOO_LONG_TABLE_COMMENT';
exports[1629] = 'ER_TOO_LONG_FIELD_COMMENT';
exports[1630] = 'ER_FUNC_INEXISTENT_NAME_COLLISION';
exports[1631] = 'ER_DATABASE_NAME';
exports[1632] = 'ER_TABLE_NAME';
exports[1633] = 'ER_PARTITION_NAME';
exports[1634] = 'ER_SUBPARTITION_NAME';
exports[1635] = 'ER_TEMPORARY_NAME';
exports[1636] = 'ER_RENAMED_NAME';
exports[1637] = 'ER_TOO_MANY_CONCURRENT_TRXS';
exports[1638] = 'WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED';
exports[1639] = 'ER_DEBUG_SYNC_TIMEOUT';
exports[1640] = 'ER_DEBUG_SYNC_HIT_LIMIT';
exports[1641] = 'ER_DUP_SIGNAL_SET';
exports[1642] = 'ER_SIGNAL_WARN';
exports[1643] = 'ER_SIGNAL_NOT_FOUND';
exports[1644] = 'ER_SIGNAL_EXCEPTION';
exports[1645] = 'ER_RESIGNAL_WITHOUT_ACTIVE_HANDLER';
exports[1646] = 'ER_SIGNAL_BAD_CONDITION_TYPE';
exports[1647] = 'WARN_COND_ITEM_TRUNCATED';
exports[1648] = 'ER_COND_ITEM_TOO_LONG';
exports[1649] = 'ER_UNKNOWN_LOCALE';
exports[1650] = 'ER_SLAVE_IGNORE_SERVER_IDS';
exports[1651] = 'ER_QUERY_CACHE_DISABLED';
exports[1652] = 'ER_SAME_NAME_PARTITION_FIELD';
exports[1653] = 'ER_PARTITION_COLUMN_LIST_ERROR';
exports[1654] = 'ER_WRONG_TYPE_COLUMN_VALUE_ERROR';
exports[1655] = 'ER_TOO_MANY_PARTITION_FUNC_FIELDS_ERROR';
exports[1656] = 'ER_MAXVALUE_IN_VALUES_IN';
exports[1657] = 'ER_TOO_MANY_VALUES_ERROR';
exports[1658] = 'ER_ROW_SINGLE_PARTITION_FIELD_ERROR';
exports[1659] = 'ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD';
exports[1660] = 'ER_PARTITION_FIELDS_TOO_LONG';
exports[1661] = 'ER_BINLOG_ROW_ENGINE_AND_STMT_ENGINE';
exports[1662] = 'ER_BINLOG_ROW_MODE_AND_STMT_ENGINE';
exports[1663] = 'ER_BINLOG_UNSAFE_AND_STMT_ENGINE';
exports[1664] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_ENGINE';
exports[1665] = 'ER_BINLOG_STMT_MODE_AND_ROW_ENGINE';
exports[1666] = 'ER_BINLOG_ROW_INJECTION_AND_STMT_MODE';
exports[1667] = 'ER_BINLOG_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE';
exports[1668] = 'ER_BINLOG_UNSAFE_LIMIT';
exports[1669] = 'ER_BINLOG_UNSAFE_INSERT_DELAYED';
exports[1670] = 'ER_BINLOG_UNSAFE_SYSTEM_TABLE';
exports[1671] = 'ER_BINLOG_UNSAFE_AUTOINC_COLUMNS';
exports[1672] = 'ER_BINLOG_UNSAFE_UDF';
exports[1673] = 'ER_BINLOG_UNSAFE_SYSTEM_VARIABLE';
exports[1674] = 'ER_BINLOG_UNSAFE_SYSTEM_FUNCTION';
exports[1675] = 'ER_BINLOG_UNSAFE_NONTRANS_AFTER_TRANS';
exports[1676] = 'ER_MESSAGE_AND_STATEMENT';
exports[1677] = 'ER_SLAVE_CONVERSION_FAILED';
exports[1678] = 'ER_SLAVE_CANT_CREATE_CONVERSION';
exports[1679] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_FORMAT';
exports[1680] = 'ER_PATH_LENGTH';
exports[1681] = 'ER_WARN_DEPRECATED_SYNTAX_NO_REPLACEMENT';
exports[1682] = 'ER_WRONG_NATIVE_TABLE_STRUCTURE';
exports[1683] = 'ER_WRONG_PERFSCHEMA_USAGE';
exports[1684] = 'ER_WARN_I_S_SKIPPED_TABLE';
exports[1685] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_BINLOG_DIRECT';
exports[1686] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_BINLOG_DIRECT';
exports[1687] = 'ER_SPATIAL_MUST_HAVE_GEOM_COL';
exports[1688] = 'ER_TOO_LONG_INDEX_COMMENT';
exports[1689] = 'ER_LOCK_ABORTED';
exports[1690] = 'ER_DATA_OUT_OF_RANGE';
exports[1691] = 'ER_WRONG_SPVAR_TYPE_IN_LIMIT';
exports[1692] = 'ER_BINLOG_UNSAFE_MULTIPLE_ENGINES_AND_SELF_LOGGING_ENGINE';
exports[1693] = 'ER_BINLOG_UNSAFE_MIXED_STATEMENT';
exports[1694] = 'ER_INSIDE_TRANSACTION_PREVENTS_SWITCH_SQL_LOG_BIN';
exports[1695] = 'ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN';
exports[1696] = 'ER_FAILED_READ_FROM_PAR_FILE';
exports[1697] = 'ER_VALUES_IS_NOT_INT_TYPE_ERROR';
exports[1698] = 'ER_ACCESS_DENIED_NO_PASSWORD_ERROR';
exports[1699] = 'ER_SET_PASSWORD_AUTH_PLUGIN';
exports[1700] = 'ER_GRANT_PLUGIN_USER_EXISTS';
exports[1701] = 'ER_TRUNCATE_ILLEGAL_FK';
exports[1702] = 'ER_PLUGIN_IS_PERMANENT';
exports[1703] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN';
exports[1704] = 'ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX';
exports[1705] = 'ER_STMT_CACHE_FULL';
exports[1706] = 'ER_MULTI_UPDATE_KEY_CONFLICT';
exports[1707] = 'ER_TABLE_NEEDS_REBUILD';
exports[1708] = 'WARN_OPTION_BELOW_LIMIT';
exports[1709] = 'ER_INDEX_COLUMN_TOO_LONG';
exports[1710] = 'ER_ERROR_IN_TRIGGER_BODY';
exports[1711] = 'ER_ERROR_IN_UNKNOWN_TRIGGER_BODY';
exports[1712] = 'ER_INDEX_CORRUPT';
exports[1713] = 'ER_UNDO_RECORD_TOO_BIG';
exports[1714] = 'ER_BINLOG_UNSAFE_INSERT_IGNORE_SELECT';
exports[1715] = 'ER_BINLOG_UNSAFE_INSERT_SELECT_UPDATE';
exports[1716] = 'ER_BINLOG_UNSAFE_REPLACE_SELECT';
exports[1717] = 'ER_BINLOG_UNSAFE_CREATE_IGNORE_SELECT';
exports[1718] = 'ER_BINLOG_UNSAFE_CREATE_REPLACE_SELECT';
exports[1719] = 'ER_BINLOG_UNSAFE_UPDATE_IGNORE';
exports[1720] = 'ER_PLUGIN_NO_UNINSTALL';
exports[1721] = 'ER_PLUGIN_NO_INSTALL';
exports[1722] = 'ER_BINLOG_UNSAFE_WRITE_AUTOINC_SELECT';
exports[1723] = 'ER_BINLOG_UNSAFE_CREATE_SELECT_AUTOINC';
+18
View File
@@ -0,0 +1,18 @@
// Manually extracted from mysql-5.5.23/include/mysql_com.h
exports.NOT_NULL_FLAG = 1; /* Field can't be NULL */
exports.PRI_KEY_FLAG = 2; /* Field is part of a primary key */
exports.UNIQUE_KEY_FLAG = 4; /* Field is part of a unique key */
exports.MULTIPLE_KEY_FLAG = 8; /* Field is part of a key */
exports.BLOB_FLAG = 16; /* Field is a blob */
exports.UNSIGNED_FLAG = 32; /* Field is unsigned */
exports.ZEROFILL_FLAG = 64; /* Field is zerofill */
exports.BINARY_FLAG = 128; /* Field is binary */
/* The following are only sent to new clients */
exports.ENUM_FLAG = 256; /* field is an enum */
exports.AUTO_INCREMENT_FLAG = 512; /* field is a autoincrement field */
exports.TIMESTAMP_FLAG = 1024; /* Field is a timestamp */
exports.SET_FLAG = 2048; /* field is a set */
exports.NO_DEFAULT_VALUE_FLAG = 4096; /* Field doesn't have default value */
exports.ON_UPDATE_NOW_FLAG = 8192; /* Field is set to NOW on UPDATE */
exports.NUM_FLAG = 32768; /* Field is num (for clients) */
+39
View File
@@ -0,0 +1,39 @@
// Manually extracted from mysql-5.5.23/include/mysql_com.h
/**
Is raised when a multi-statement transaction
has been started, either explicitly, by means
of BEGIN or COMMIT AND CHAIN, or
implicitly, by the first transactional
statement, when autocommit=off.
*/
exports.SERVER_STATUS_IN_TRANS = 1;
exports.SERVER_STATUS_AUTOCOMMIT = 2; /* Server in auto_commit mode */
exports.SERVER_MORE_RESULTS_EXISTS = 8; /* Multi query - next query exists */
exports.SERVER_QUERY_NO_GOOD_INDEX_USED = 16;
exports.SERVER_QUERY_NO_INDEX_USED = 32;
/**
The server was able to fulfill the clients request and opened a
read-only non-scrollable cursor for a query. This flag comes
in reply to COM_STMT_EXECUTE and COM_STMT_FETCH commands.
*/
exports.SERVER_STATUS_CURSOR_EXISTS = 64;
/**
This flag is sent when a read-only cursor is exhausted, in reply to
COM_STMT_FETCH command.
*/
exports.SERVER_STATUS_LAST_ROW_SENT = 128;
exports.SERVER_STATUS_DB_DROPPED = 256; /* A database was dropped */
exports.SERVER_STATUS_NO_BACKSLASH_ESCAPES = 512;
/**
Sent to the client if after a prepared statement reprepare
we discovered that the new statement returns a different
number of result set columns.
*/
exports.SERVER_STATUS_METADATA_CHANGED = 1024;
exports.SERVER_QUERY_WAS_SLOW = 2048;
/**
To mark ResultSet containing output parameter values.
*/
exports.SERVER_PS_OUT_PARAMS = 4096;
+29
View File
@@ -0,0 +1,29 @@
// Manually extracted from mysql-5.5.23/include/mysql_com.h
// some more info here: http://dev.mysql.com/doc/refman/5.5/en/c-api-prepared-statement-type-codes.html
exports.DECIMAL = 0x00; // aka DECIMAL (http://dev.mysql.com/doc/refman/5.0/en/precision-math-decimal-changes.html)
exports.TINY = 0x01; // aka TINYINT, 1 byte
exports.SHORT = 0x02; // aka SMALLINT, 2 bytes
exports.LONG = 0x03; // aka INT, 4 bytes
exports.FLOAT = 0x04; // aka FLOAT, 4-8 bytes
exports.DOUBLE = 0x05; // aka DOUBLE, 8 bytes
exports.NULL = 0x06; // NULL (used for prepared statements, I think)
exports.TIMESTAMP = 0x07; // aka TIMESTAMP
exports.LONGLONG = 0x08; // aka BIGINT, 8 bytes
exports.INT24 = 0x09; // aka MEDIUMINT, 3 bytes
exports.DATE = 0x0a; // aka DATE
exports.TIME = 0x0b; // aka TIME
exports.DATETIME = 0x0c; // aka DATETIME
exports.YEAR = 0x0d; // aka YEAR, 1 byte (don't ask)
exports.NEWDATE = 0x0e; // aka ?
exports.VARCHAR = 0x0f; // aka VARCHAR (?)
exports.BIT = 0x10; // aka BIT, 1-8 byte
exports.NEWDECIMAL = 0xf6; // aka DECIMAL
exports.ENUM = 0xf7; // aka ENUM
exports.SET = 0xf8; // aka SET
exports.TINY_BLOB = 0xf9; // aka TINYBLOB, TINYTEXT
exports.MEDIUM_BLOB = 0xfa; // aka MEDIUMBLOB, MEDIUMTEXT
exports.LONG_BLOB = 0xfb; // aka LONGBLOG, LONGTEXT
exports.BLOB = 0xfc; // aka BLOB, TEXT
exports.VAR_STRING = 0xfd; // aka VARCHAR, VARBINARY
exports.STRING = 0xfe; // aka CHAR, BINARY
exports.GEOMETRY = 0xff; // aka GEOMETRY
+32
View File
@@ -0,0 +1,32 @@
module.exports = ClientAuthenticationPacket;
function ClientAuthenticationPacket(options) {
options = options || {};
this.clientFlags = options.clientFlags;
this.maxPacketSize = options.maxPacketSize;
this.charsetNumber = options.charsetNumber;
this.filler = undefined;
this.user = options.user;
this.scrambleBuff = options.scrambleBuff;
this.database = options.database;
}
ClientAuthenticationPacket.prototype.parse = function(parser) {
this.clientFlags = parser.parseUnsignedNumber(4);
this.maxPacketSize = parser.parseUnsignedNumber(4);
this.charsetNumber = parser.parseUnsignedNumber(1);
this.filler = parser.parseFiller(23);
this.user = parser.parseNullTerminatedString();
this.scrambleBuff = parser.parseLengthCodedBuffer();
this.database = parser.parseNullTerminatedString();
};
ClientAuthenticationPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(4, this.clientFlags);
writer.writeUnsignedNumber(4, this.maxPacketSize);
writer.writeUnsignedNumber(1, this.charsetNumber);
writer.writeFiller(23);
writer.writeNullTerminatedString(this.user);
writer.writeLengthCodedBuffer(this.scrambleBuff);
writer.writeNullTerminatedString(this.database);
};
+25
View File
@@ -0,0 +1,25 @@
module.exports = ComChangeUserPacket;
function ComChangeUserPacket(options) {
options = options || {};
this.command = 0x11;
this.user = options.user;
this.scrambleBuff = options.scrambleBuff;
this.database = options.database;
this.charsetNumber = options.charsetNumber;
}
ComChangeUserPacket.prototype.parse = function(parser) {
this.user = parser.parseNullTerminatedString();
this.scrambleBuff = parser.parseLengthCodedBuffer();
this.database = parser.parseNullTerminatedString();
this.charsetNumber = parser.parseUnsignedNumber(1);
};
ComChangeUserPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
writer.writeNullTerminatedString(this.user);
writer.writeLengthCodedBuffer(this.scrambleBuff);
writer.writeNullTerminatedString(this.database);
writer.writeUnsignedNumber(1, this.charsetNumber);
};
+12
View File
@@ -0,0 +1,12 @@
module.exports = ComPingPacket;
function ComPingPacket(sql) {
this.command = 0x0e;
}
ComPingPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
};
ComPingPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
};
+15
View File
@@ -0,0 +1,15 @@
module.exports = ComQueryPacket;
function ComQueryPacket(sql) {
this.command = 0x03;
this.sql = sql;
}
ComQueryPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
writer.writeString(this.sql);
};
ComQueryPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
this.sql = parser.parsePacketTerminatedString();
};
+7
View File
@@ -0,0 +1,7 @@
module.exports = ComQuitPacket;
function ComQuitPacket(sql) {
}
ComQuitPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0x01);
};
+12
View File
@@ -0,0 +1,12 @@
module.exports = ComStatisticsPacket;
function ComStatisticsPacket(sql) {
this.command = 0x09;
}
ComStatisticsPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.command);
};
ComStatisticsPacket.prototype.parse = function(parser) {
this.command = parser.parseUnsignedNumber(1);
};
+6
View File
@@ -0,0 +1,6 @@
module.exports = EmptyPacket;
function EmptyPacket() {
}
EmptyPacket.prototype.write = function(writer) {
};
+20
View File
@@ -0,0 +1,20 @@
module.exports = EofPacket;
function EofPacket(options) {
options = options || {};
this.fieldCount = undefined;
this.warningCount = options.warningCount;
this.serverStatus = options.serverStatus;
}
EofPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
this.warningCount = parser.parseUnsignedNumber(2);
this.serverStatus = parser.parseUnsignedNumber(2);
};
EofPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0xfe);
writer.writeUnsignedNumber(2, this.warningCount);
writer.writeUnsignedNumber(2, this.serverStatus);
};
+35
View File
@@ -0,0 +1,35 @@
module.exports = ErrorPacket;
function ErrorPacket(options) {
options = options || {};
this.fieldCount = options.fieldCount;
this.errno = options.errno;
this.sqlStateMarker = options.sqlStateMarker;
this.sqlState = options.sqlState;
this.message = options.message;
}
ErrorPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
this.errno = parser.parseUnsignedNumber(2);
// sqlStateMarker ('#' = 0x23) indicates error packet format
if (parser.peak() === 0x23) {
this.sqlStateMarker = parser.parseString(1);
this.sqlState = parser.parseString(5);
}
this.message = parser.parsePacketTerminatedString();
};
ErrorPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0xff);
writer.writeUnsignedNumber(2, this.errno);
if (this.sqlStateMarker) {
writer.writeString(this.sqlStateMarker);
writer.writeString(this.sqlState);
}
writer.writeString(this.message);
};
+31
View File
@@ -0,0 +1,31 @@
var Types = require('../constants/types');
module.exports = Field;
function Field(options) {
options = options || {};
this.parser = options.parser;
this.db = options.packet.db;
this.table = options.packet.table;
this.name = options.packet.name;
this.type = typeToString(options.packet.type);
this.length = options.packet.length;
}
Field.prototype.string = function () {
return this.parser.parseLengthCodedString();
};
Field.prototype.buffer = function () {
return this.parser.parseLengthCodedBuffer();
};
Field.prototype.geometry = function () {
return this.parser.parseGeometryValue();
};
function typeToString(t) {
for (var k in Types) {
if (Types[k] == t) return k;
}
}
+65
View File
@@ -0,0 +1,65 @@
module.exports = FieldPacket;
function FieldPacket(options) {
options = options || {};
this.catalog = options.catalog;
this.db = options.db;
this.table = options.table;
this.orgTable = options.orgTable;
this.name = options.name;
this.orgName = options.orgName;
this.filler1 = undefined;
this.charsetNr = options.charsetNr;
this.length = options.length;
this.type = options.type;
this.flags = options.flags;
this.decimals = options.decimals;
this.filler2 = undefined;
this.default = options.default;
this.zeroFill = options.zeroFill;
}
FieldPacket.prototype.parse = function(parser) {
this.catalog = parser.parseLengthCodedString();
this.db = parser.parseLengthCodedString();
this.table = parser.parseLengthCodedString();
this.orgTable = parser.parseLengthCodedString();
this.name = parser.parseLengthCodedString();
this.orgName = parser.parseLengthCodedString();
this.filler1 = parser.parseFiller(1);
this.charsetNr = parser.parseUnsignedNumber(2);
this.fieldLength = parser.parseUnsignedNumber(4);
this.type = parser.parseUnsignedNumber(1);
this.flags = parser.parseUnsignedNumber(2);
this.decimals = parser.parseUnsignedNumber(1);
this.filler2 = parser.parseFiller(2);
// parsed flags
this.zeroFill = (this.flags & 0x0040 ? true : false);
if (parser.reachedPacketEnd()) {
return;
}
this.default = parser.parseLengthCodedNumber();
};
FieldPacket.prototype.write = function(writer) {
writer.writeLengthCodedString(this.catalog);
writer.writeLengthCodedString(this.db);
writer.writeLengthCodedString(this.table);
writer.writeLengthCodedString(this.orgTable);
writer.writeLengthCodedString(this.name);
writer.writeLengthCodedString(this.orgName);
writer.writeFiller(1);
writer.writeUnsignedNumber(2, this.charsetNr || 0);
writer.writeUnsignedNumber(4, this.fieldLength || 0);
writer.writeUnsignedNumber(1, this.type) || 0;
writer.writeUnsignedNumber(2, this.flags || 0);
writer.writeUnsignedNumber(1, this.decimals || 0);
writer.writeFiller(2);
if (this.default !== undefined) {
writer.writeLengthCodedString(this.default);
}
};
@@ -0,0 +1,81 @@
module.exports = HandshakeInitializationPacket;
function HandshakeInitializationPacket(options) {
options = options || {};
this.protocolVersion = options.protocolVersion;
this.serverVersion = options.serverVersion;
this.threadId = options.threadId;
this.scrambleBuff1 = options.scrambleBuff1;
this.filler1 = options.filler1;
this.serverCapabilities1 = options.serverCapabilities1;
this.serverLanguage = options.serverLanguage;
this.serverStatus = options.serverStatus;
this.serverCapabilities2 = options.serverCapabilities2;
this.scrambleLength = options.scrambleLength;
this.filler2 = options.filler2;
this.scrambleBuff2 = options.scrambleBuff2;
this.filler3 = options.filler3;
this.pluginData = options.pluginData;
}
HandshakeInitializationPacket.prototype.parse = function(parser) {
this.protocolVersion = parser.parseUnsignedNumber(1);
this.serverVersion = parser.parseNullTerminatedString();
this.threadId = parser.parseUnsignedNumber(4);
this.scrambleBuff1 = parser.parseBuffer(8);
this.filler1 = parser.parseFiller(1);
this.serverCapabilities1 = parser.parseUnsignedNumber(2);
this.serverLanguage = parser.parseUnsignedNumber(1);
this.serverStatus = parser.parseUnsignedNumber(2);
this.serverCapabilities2 = parser.parseUnsignedNumber(2);
this.scrambleLength = parser.parseUnsignedNumber(1);
this.filler2 = parser.parseFiller(10);
// scrambleBuff2 should be 0x00 terminated, but sphinx does not do this
// so we assume scrambleBuff2 to be 12 byte and treat the next byte as a
// filler byte.
this.scrambleBuff2 = parser.parseBuffer(12);
this.filler3 = parser.parseFiller(1);
if (parser.reachedPacketEnd()) {
return;
}
// According to the docs this should be 0x00 terminated, but MariaDB does
// not do this, so we assume this string to be packet terminated.
this.pluginData = parser.parsePacketTerminatedString();
// However, if there is a trailing '\0', strip it
var lastChar = this.pluginData.length - 1;
if (this.pluginData[lastChar] === '\0') {
this.pluginData = this.pluginData.substr(0, lastChar);
}
};
HandshakeInitializationPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.protocolVersion);
writer.writeNullTerminatedString(this.serverVersion);
writer.writeUnsignedNumber(4, this.threadId);
writer.writeBuffer(this.scrambleBuff1);
writer.writeFiller(1);
writer.writeUnsignedNumber(2, this.serverCapabilities1);
writer.writeUnsignedNumber(1, this.serverLanguage);
writer.writeUnsignedNumber(2, this.serverStatus);
writer.writeUnsignedNumber(2, this.serverCapabilities2);
writer.writeUnsignedNumber(1, this.scrambleLength);
writer.writeFiller(10);
writer.writeNullTerminatedBuffer(this.scrambleBuff2);
if (this.pluginData !== undefined) {
writer.writeNullTerminatedString(this.pluginData);
}
};
HandshakeInitializationPacket.prototype.scrambleBuff = function() {
var buffer = new Buffer(this.scrambleBuff1.length + this.scrambleBuff2.length);
this.scrambleBuff1.copy(buffer);
this.scrambleBuff2.copy(buffer, this.scrambleBuff1.length);
return buffer;
};
+8
View File
@@ -0,0 +1,8 @@
module.exports = LocalDataFilePacket;
function LocalDataFilePacket(data) {
this.data = data;
}
LocalDataFilePacket.prototype.write = function(writer) {
writer.writeString(this.data);
};
+34
View File
@@ -0,0 +1,34 @@
module.exports = OkPacket;
function OkPacket() {
this.fieldCount = undefined;
this.affectedRows = undefined;
this.insertId = undefined;
this.serverStatus = undefined;
this.warningCount = undefined;
this.message = undefined;
}
OkPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseUnsignedNumber(1);
this.affectedRows = parser.parseLengthCodedNumber();
this.insertId = parser.parseLengthCodedNumber();
this.serverStatus = parser.parseUnsignedNumber(2);
this.warningCount = parser.parseUnsignedNumber(2);
this.message = parser.parsePacketTerminatedString();
this.changedRows = 0;
var m = this.message.match(/\schanged:\s*(\d+)/i);
if (m !== null) {
this.changedRows = parseInt(m[1], 10);
}
};
OkPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, 0x00);
writer.writeLengthCodedNumber(this.affectedRows || 0);
writer.writeLengthCodedNumber(this.insertId || 0);
writer.writeUnsignedNumber(2, this.serverStatus || 0);
writer.writeUnsignedNumber(2, this.warningCount || 0);
writer.writeString(this.message);
};
+15
View File
@@ -0,0 +1,15 @@
module.exports = OldPasswordPacket;
function OldPasswordPacket(options) {
options = options || {};
this.scrambleBuff = options.scrambleBuff;
}
OldPasswordPacket.prototype.parse = function(parser) {
this.scrambleBuff = parser.parseNullTerminatedBuffer();
};
OldPasswordPacket.prototype.write = function(writer) {
writer.writeBuffer(this.scrambleBuff);
writer.writeFiller(1);
};
+25
View File
@@ -0,0 +1,25 @@
module.exports = ResultSetHeaderPacket;
function ResultSetHeaderPacket(options) {
options = options || {};
this.fieldCount = options.fieldCount;
this.extra = options.extra;
}
ResultSetHeaderPacket.prototype.parse = function(parser) {
this.fieldCount = parser.parseLengthCodedNumber();
if (parser.reachedPacketEnd()) return;
this.extra = (this.fieldCount === null)
? parser.parsePacketTerminatedString()
: parser.parseLengthCodedNumber();
};
ResultSetHeaderPacket.prototype.write = function(writer) {
writer.writeLengthCodedNumber(this.fieldCount);
if (this.extra !== undefined) {
writer.writeLengthCodedNumber(this.extra);
}
};
+92
View File
@@ -0,0 +1,92 @@
var Types = require('../constants/types');
var Charsets = require('../constants/charsets');
var Field = require('./Field');
var IEEE_754_BINARY_64_PRECISION = Math.pow(2, 53);
module.exports = RowDataPacket;
function RowDataPacket() {
}
RowDataPacket.prototype.parse = function(parser, fieldPackets, typeCast, nestTables, connection) {
var self = this;
var next = function () {
return self._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers);
};
for (var i = 0; i < fieldPackets.length; i++) {
var fieldPacket = fieldPackets[i];
var value;
if (typeof typeCast == "function") {
value = typeCast.apply(connection, [ new Field({ packet: fieldPacket, parser: parser }), next ]);
} else {
value = (typeCast)
? this._typeCast(fieldPacket, parser, connection.config.timezone, connection.config.supportBigNumbers)
: ( (fieldPacket.charsetNr === Charsets.BINARY)
? parser.parseLengthCodedBuffer()
: parser.parseLengthCodedString() );
}
if (typeof nestTables == "string" && nestTables.length) {
this[fieldPacket.table + nestTables + fieldPacket.name] = value;
} else if (nestTables) {
this[fieldPacket.table] = this[fieldPacket.table] || {};
this[fieldPacket.table][fieldPacket.name] = value;
} else {
this[fieldPacket.name] = value;
}
}
};
RowDataPacket.prototype._typeCast = function(field, parser, timeZone, supportBigNumbers) {
switch (field.type) {
case Types.TIMESTAMP:
case Types.DATE:
case Types.DATETIME:
case Types.NEWDATE:
var dateString = parser.parseLengthCodedString();
if (dateString === null) {
return null;
}
if (timeZone != 'local') {
if (field.type === Types.DATE) {
dateString += ' 00:00:00 ' + timeZone;
} else {
dateString += timeZone;
}
}
return new Date(dateString);
case Types.TINY:
case Types.SHORT:
case Types.LONG:
case Types.INT24:
case Types.YEAR:
case Types.FLOAT:
case Types.DOUBLE:
case Types.LONGLONG:
case Types.NEWDECIMAL:
var numberString = parser.parseLengthCodedString();
return (numberString === null || (field.zeroFill && numberString[0] == "0"))
? numberString
: ((supportBigNumbers && Number(numberString) > IEEE_754_BINARY_64_PRECISION)
? numberString
: Number(numberString));
case Types.BIT:
return parser.parseLengthCodedBuffer();
case Types.STRING:
case Types.VAR_STRING:
case Types.TINY_BLOB:
case Types.MEDIUM_BLOB:
case Types.LONG_BLOB:
case Types.BLOB:
return (field.charsetNr === Charsets.BINARY)
? parser.parseLengthCodedBuffer()
: parser.parseLengthCodedString();
case Types.GEOMETRY:
return parser.parseGeometryValue();
default:
return parser.parseLengthCodedString();
}
};
+20
View File
@@ -0,0 +1,20 @@
module.exports = StatisticsPacket;
function StatisticsPacket() {
this.message = undefined;
}
StatisticsPacket.prototype.parse = function(parser) {
this.message = parser.parsePacketTerminatedString();
var items = this.message.split(/\s\s/);
for (var i = 0; i < items.length; i++) {
var m = items[i].match(/^(.+)\:\s+(.+)$/);
if (m !== null) {
this[m[1].toLowerCase().replace(/\s/g, '_')] = Number(m[2]);
}
}
};
StatisticsPacket.prototype.write = function(writer) {
writer.writeString(this.message);
};
+14
View File
@@ -0,0 +1,14 @@
module.exports = UseOldPasswordPacket;
function UseOldPasswordPacket(options) {
options = options || {};
this.firstByte = options.firstByte || 0xfe;
}
UseOldPasswordPacket.prototype.parse = function(parser) {
this.firstByte = parser.parseUnsignedNumber(1);
};
UseOldPasswordPacket.prototype.write = function(writer) {
writer.writeUnsignedNumber(1, this.firstByte);
};
+4
View File
@@ -0,0 +1,4 @@
var Elements = module.exports = require('require-all')({
dirname : __dirname,
filter : /([A-Z].+)\.js$/,
});
+41
View File
@@ -0,0 +1,41 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var Auth = require('../Auth');
module.exports = ChangeUser;
Util.inherits(ChangeUser, Sequence);
function ChangeUser(options, callback) {
Sequence.call(this, callback);
this._user = options.user;
this._password = options.password;
this._database = options.database;
this._charsetNumber = options.charsetNumber;
this._currentConfig = options.currentConfig;
}
ChangeUser.prototype.start = function(handshakeInitializationPacket) {
var scrambleBuff = handshakeInitializationPacket.scrambleBuff();
scrambleBuff = Auth.token(this._password, scrambleBuff);
var packet = new Packets.ComChangeUserPacket({
user : this._user,
scrambleBuff : scrambleBuff,
database : this._database,
charsetNumber : this._charsetNumber,
});
this._currentConfig.user = this._user;
this._currentConfig.password = this._password;
this._currentConfig.database = this._database;
this._currentConfig.charsetNumber = this._charsetNumber;
this.emit('packet', packet);
};
ChangeUser.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet);
err.fatal = true;
this.end(err);
};
+65
View File
@@ -0,0 +1,65 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var Auth = require('../Auth');
module.exports = Handshake;
Util.inherits(Handshake, Sequence);
function Handshake(config, callback) {
Sequence.call(this, callback);
this._config = config;
this._handshakeInitializationPacket = null;
}
Handshake.prototype.determinePacket = function(firstByte) {
if (firstByte === 0xff) {
return Packets.ErrorPacket;
}
if (!this._handshakeInitializationPacket) {
return Packets.HandshakeInitializationPacket;
}
if (firstByte === 0xfe) {
return Packets.UseOldPasswordPacket;
}
};
Handshake.prototype['HandshakeInitializationPacket'] = function(packet) {
this._handshakeInitializationPacket = packet;
this.emit('packet', new Packets.ClientAuthenticationPacket({
clientFlags : this._config.clientFlags,
maxPacketSize : this._config.maxPacketSize,
charsetNumber : this._config.charsetNumber,
user : this._config.user,
scrambleBuff : Auth.token(this._config.password, packet.scrambleBuff()),
database : this._config.database,
}));
};
Handshake.prototype['UseOldPasswordPacket'] = function(packet) {
if (!this._config.insecureAuth) {
var err = new Error(
'MySQL server is requesting the old and insecure pre-4.1 auth mechanism.' +
'Upgrade the user password or use the {insecureAuth: true} option.'
);
err.code = 'HANDSHAKE_INSECURE_AUTH';
err.fatal = true;
this.end(err);
return;
}
this.emit('packet', new Packets.OldPasswordPacket({
scrambleBuff : Auth.scramble323(this._handshakeInitializationPacket.scrambleBuff(), this._config.password),
}));
};
Handshake.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet, true);
err.fatal = true;
this.end(err);
};
+14
View File
@@ -0,0 +1,14 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
module.exports = Ping;
Util.inherits(Ping, Sequence);
function Ping(callback) {
Sequence.call(this, callback);
}
Ping.prototype.start = function() {
this.emit('packet', new Packets.ComPingPacket);
};
+163
View File
@@ -0,0 +1,163 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
var ResultSet = require('../ResultSet');
var ServerStatus = require('../constants/server_status');
var fs = require('fs');
module.exports = Query;
Util.inherits(Query, Sequence);
function Query(options, callback) {
Sequence.call(this, callback);
this.sql = options.sql;
this.values = options.values;
this.typeCast = (options.typeCast === undefined)
? true
: options.typeCast;
this.nestTables = options.nestTables || false;
this._resultSet = null;
this._results = [];
this._fields = [];
this._index = 0;
this._loadError = null;
}
Query.prototype.start = function() {
this.emit('packet', new Packets.ComQueryPacket(this.sql));
};
Query.prototype.determinePacket = function(firstByte, parser) {
if (firstByte === 0) {
// If we have a resultSet and got one eofPacket
if (this._resultSet && this._resultSet.eofPackets.length === 1) {
// Then this is a RowDataPacket with an empty string in the first column.
// See: https://github.com/felixge/node-mysql/issues/222
} else {
return;
}
}
if (firstByte === 255) {
return;
}
// EofPacket's are 5 bytes in mysql >= 4.1
// This is the only / best way to differentiate their firstByte from a 9
// byte length coded binary.
if (firstByte === 0xfe && parser.packetLength() < 9) {
return Packets.EofPacket;
}
if (!this._resultSet) {
return Packets.ResultSetHeaderPacket;
}
return (this._resultSet.eofPackets.length === 0)
? Packets.FieldPacket
: Packets.RowDataPacket;
};
Query.prototype['OkPacket'] = function(packet) {
// try...finally for exception safety
try {
if (!this._callback) {
this.emit('result', packet, this._index);
} else {
this._results.push(packet);
this._fields.push(undefined);
}
} finally {
this._index++;
this._handleFinalResultPacket(packet);
}
};
Query.prototype['ErrorPacket'] = function(packet) {
var err = this._packetToError(packet);
var results = (this._results.length > 0)
? this._results
: undefined;
var fields = (this._fields.length > 0)
? this._fields
: undefined;
err.index = this._index;
this.end(err, results, fields);
};
Query.prototype['ResultSetHeaderPacket'] = function(packet) {
this._resultSet = new ResultSet(packet);
// used by LOAD DATA LOCAL INFILE queries
if (packet.fieldCount === null) {
this._sendLocalDataFile(packet.extra);
}
};
Query.prototype['FieldPacket'] = function(packet) {
this._resultSet.fieldPackets.push(packet);
};
Query.prototype['EofPacket'] = function(packet) {
this._resultSet.eofPackets.push(packet);
if (this._resultSet.eofPackets.length === 1 && !this._callback) {
this.emit('fields', this._resultSet.fieldPackets, this._index);
}
if (this._resultSet.eofPackets.length !== 2) {
return;
}
if (this._callback) {
this._results.push(this._resultSet.rows);
this._fields.push(this._resultSet.fieldPackets);
}
this._index++;
this._resultSet = null;
this._handleFinalResultPacket(packet);
};
Query.prototype._handleFinalResultPacket = function(packet) {
if (packet.serverStatus & ServerStatus.SERVER_MORE_RESULTS_EXISTS) {
return;
}
var results = (this._results.length > 1)
? this._results
: this._results[0];
var fields = (this._fields.length > 1)
? this._fields
: this._fields[0];
this.end(this._loadError, results, fields);
};
Query.prototype['RowDataPacket'] = function(packet, parser, connection) {
packet.parse(parser, this._resultSet.fieldPackets, this.typeCast, this.nestTables, connection);
if (this._callback) {
this._resultSet.rows.push(packet);
} else {
this.emit('result', packet, this._index);
}
};
Query.prototype._sendLocalDataFile = function(path) {
var self = this;
fs.readFile(path, 'utf-8', function(err, data) {
if (err) {
self._loadError = err;
} else {
self.emit('packet', new Packets.LocalDataFilePacket(data));
}
self.emit('packet', new Packets.EmptyPacket());
});
};
+13
View File
@@ -0,0 +1,13 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
module.exports = Quit;
Util.inherits(Quit, Sequence);
function Quit(callback) {
Sequence.call(this, callback);
}
Quit.prototype.start = function() {
this.emit('packet', new Packets.ComQuitPacket);
};
+83
View File
@@ -0,0 +1,83 @@
var Util = require('util');
var EventEmitter = require('events').EventEmitter;
var Packets = require('../packets');
var ErrorConstants = require('../constants/errors');
module.exports = Sequence;
Util.inherits(Sequence, EventEmitter);
function Sequence(callback) {
EventEmitter.call(this);
this._callback = callback;
this._ended = false;
// Experimental: Long stack trace support
this._callSite = (new Error).stack.replace(/.+\n/, '');
}
Sequence.determinePacket = function(byte) {
switch (byte) {
case 0x00: return Packets.OkPacket;
case 0xfe: return Packets.EofPacket;
case 0xff: return Packets.ErrorPacket;
}
};
Sequence.prototype.hasErrorHandler = function() {
return this._callback || this.listeners('error').length > 1;
};
Sequence.prototype._packetToError = function(packet) {
var code = ErrorConstants[packet.errno] || 'UNKNOWN_CODE_PLEASE_REPORT';
var err = new Error(code + ': ' + packet.message);
err.code = code;
return err;
};
Sequence.prototype._addLongStackTrace = function(err) {
var delimiter = '\n --------------------\n' ;
if (err.stack.indexOf(delimiter) > -1) {
return;
}
err.stack += delimiter + this._callSite;
};
Sequence.prototype.end = function(err) {
if (this._ended) {
return;
}
this._ended = true;
if (err) {
this._addLongStackTrace(err);
}
// try...finally for exception safety
try {
if (err) {
this.emit('error', err);
}
} finally {
try {
if (this._callback) {
this._callback.apply(this, arguments);
}
} finally {
this.emit('end');
}
}
};
Sequence.prototype['OkPacket'] = function(packet) {
this.end(null, packet);
};
Sequence.prototype['ErrorPacket'] = function(packet) {
this.end(this._packetToError(packet));
};
// Implemented by child classes
Sequence.prototype.start = function() {};
+23
View File
@@ -0,0 +1,23 @@
var Sequence = require('./Sequence');
var Util = require('util');
var Packets = require('../packets');
module.exports = Statistics;
Util.inherits(Statistics, Sequence);
function Statistics(callback) {
Sequence.call(this, callback);
}
Statistics.prototype.start = function() {
this.emit('packet', new Packets.ComStatisticsPacket);
};
Statistics.prototype['StatisticsPacket'] = function (packet) {
this.end(null, packet);
};
Statistics.prototype.determinePacket = function(firstByte, parser) {
if (firstByte === 0x55) {
return Packets.StatisticsPacket;
}
};
+4
View File
@@ -0,0 +1,4 @@
var Elements = module.exports = require('require-all')({
dirname : __dirname,
filter : /([A-Z].+)\.js$/,
});
+23
View File
@@ -0,0 +1,23 @@
The MIT Expat Licence.
Copyright (c) 2012 Michael Mclaughlin
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.
+222
View File
@@ -0,0 +1,222 @@
# bignumber.js #
A Javascript library for arbitrary-precision decimal and non-decimal arithmetic.
## Features
- Faster, smaller, and perhaps easier to use than Javascript versions of Java's BigDecimal
- 5 KB minified and gzipped
- Simple API but full-featured
- Works with numbers with or without fraction digits in bases from 2 to 36 inclusive
- Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of Javascript's Number type
- Includes a `toFraction` and a `squareRoot` method
- Stores values in an accessible decimal floating point format
- No dependencies
- Comprehensive documentation and test set
If an even smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/).
It's half the size but only works with decimal numbers and only has half the methods.
It also does not allow `NaN` or `Infinity`, or have the configuration options of this library.
## Load
The library is the single Javascript file *bignumber.js*
(or *bignumber.min.js*, which is *bignumber.js* minified using uglify-js).
It can be loaded via a script tag in an HTML document for the browser
<script src='./relative/path/to/bignumber.js'></script>
or as a CommonJS, [Node.js](http://nodejs.org) or AMD module using `require`.
For Node, put the *bignumber.js* file into the same directory as the file that is requiring it and use
var BigNumber = require('./bignumber');
or put it in a *node_modules* directory within the directory and use `require('bignumber')`.
The library is also available from the [npm](https://npmjs.org/) registry, so
$ npm install bignumber.js
will install this entire directory in a *node_modules* directory within the current directory.
It can then be loaded with `require('bignumber.js')`.
To load with AMD loader libraries such as [requireJS](http://requirejs.org/):
require(['bignumber'], function(BigNumber) {
// Use BigNumber here in local scope. No global BigNumber.
});
## Use
*In all examples below, `var`, semicolons and `toString` calls are not shown.
If a commented-out value is in quotes it means `toString` has been called on the preceding expression.*
The library exports a single function: BigNumber, the constructor of BigNumber instances.
It accepts a value of type Number, String or BigNumber Object,
x = new BigNumber(123.4567)
y = BigNumber('123456.7e-3') // 'new' is optional
z = new BigNumber(x)
x.equals(y) && y.equals(z) && x.equals(z) // true
and a base from 2 to 36 inclusive can be specified.
x = new BigNumber(1011, 2) // "11"
y = new BigNumber('zz.9', 36) // "1295.25"
z = x.plus(y) // "1306.25"
A BigNumber is immutable in the sense that it is not changed by its methods.
0.3 - 0.1 // 0.19999999999999998
x = new BigNumber(0.3)
x.minus(0.1) // "0.2"
x // "0.3"
The methods that return a BigNumber can be chained.
x.dividedBy(y).plus(z).times(9).floor()
x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').ceil()
Method names over 5 letters in length have a shorter alias.
x.squareRoot().dividedBy(y).toPower(3).equals(x.sqrt().div(y).pow(3)) // true
x.cmp(y.mod(z).neg()) == 1 && x.comparedTo(y.modulo(z).negated()) == 1 // true
Like Javascript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods
x = new BigNumber(255.5)
x.toExponential(5) // "2.55500e+2"
x.toFixed(5) // "255.50000"
x.toPrecision(5) // "255.50"
and a base can be specified for `toString`.
x.toString(16) // "ff.8"
The maximum number of decimal places and the rounding mode for division, square root, base conversion, and negative power operations is set by a configuration object passed to the `config` method of the `BigNumber` constructor.
The other arithmetic operations always give the exact result.
BigNumber.config({ DECIMAL_PLACES : 10, ROUNDING_MODE : 4 })
// Alternatively, BigNumber.config( 10, 4 );
x = new BigNumber(2);
y = new BigNumber(3);
z = x.div(y) // "0.6666666667"
z.sqrt() // "0.8164965809"
z.pow(-3) // "3.3749999995"
z.toString(2) // "0.1010101011"
z.times(z) // "0.44444444448888888889"
z.times(z).round(10) // "0.4444444445"
There is a `toFraction` method with an optional *maximum denominator* argument
y = new BigNumber(355)
pi = y.dividedBy(113) // "3.1415929204"
pi.toFraction() // [ "7853982301", "2500000000" ]
pi.toFraction(1000) // [ "355", "113" ]
and `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `BigNumber` values.
x = new BigNumber(NaN) // "NaN"
y = new BigNumber(Infinity) // "Infinity"
x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true
The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign.
x = new BigNumber(-123.456);
x.c // "1,2,3,4,5,6" coefficient (i.e. significand)
x.e // 2 exponent
x.s // -1 sign
For futher information see the API reference in the *doc* folder.
## Test
The *test* directory contains the test scripts for each method.
The tests can be run with Node or a browser.
For a quick test of all the methods, from a command-line shell at the *test/* directory
$ node quick-test
To test a single method in more depth, e.g.
$ node toFraction
To test all the methods in more depth
$ node every-test
For the browser, see *quick-test.html*, *single-test.html* and *every-test.html* in the *test/browser* directory.
*bignumber-vs-number.html* enables some of the methods of bignumber.js to be compared with those of Javascript's Number type.
## Performance
The *perf* directory contains two applications and a *lib* directory containing the BigDecimal libraries used by both.
*bignumber-vs-bigdecimal.html* tests the performance of bignumber.js against the Javascript translations of two versions of BigDecimal, its use should be more or less self-explanatory.
(The GWT version doesn't work in IE 6.)
* GWT: java.math.BigDecimal
<https://github.com/iriscouch/bigdecimal.js>
* ICU4J: com.ibm.icu.math.BigDecimal
<https://github.com/dtrebbien/BigDecimal.js>
The BigDecimal in Node's npm registry is the GWT version. Despite its seeming popularity I have found it to have some serious bugs, see the Node script *perf/lib/bigdecimal_GWT/bugs.js* for examples of flaws in its *remainder*, *divide* and *compareTo* methods.
*bigtime.js* is a Node command-line application which tests the performance of bignumber.js against the GWT version of BigDecimal from the npm registry.
For example, to compare the time taken by the bignumber.js `plus` method and the BigDecimal `add` method:
$ node bigtime plus 10000 40
This will time 10000 calls to each, using operands of up to 40 random digits and will check that the results match.
For help:
$ node bigtime -h
See the README in the directory for more information.
## Build
I.e. minify.
For Node, if uglify-js is installed globally ( `npm install uglify-js -g` ) then
uglifyjs -o ./bignumber.min.js ./bignumber.js
will create *bignumber.min.js*.
## Feedback
Bugs: surely not! Open an issue, please.
Other feedback to:
Michael Mclaughlin
<a href="mailto:M8ch88l@gmail.com">M8ch88l@gmail.com</a>
Bitcoin donation to:
**1KdnpLRSkWJs4FXPzj7pQ39H4Ur6Urydti**
Thank you
## Licence
See LICENCE.
## Change Log
####1.0.1
* Bugfix: error messages with incorrect method name
* Corrected a couple of spelling mistakes in comments
* Very minor regex tweaks
####1.0.0
* 8/11/2012 Initial release
[![githalytics.com alpha](https://cruel-carlota.pagodabox.com/50b85fd919b406ef9312551092a95fb7 "githalytics.com")](http://githalytics.com/MikeMcl/bignumber.js)
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+45
View File
@@ -0,0 +1,45 @@
bigtime.js
==========
* Creates random numbers and BigNumber and BigDecimal objects in batches.
* UNLIKELY TO RUN OUT OF MEMORY.
* Doesn't show separate times for object creation and method calls.
* Tests methods with one or two operands (i.e. includes abs and negate).
* Doesn't indicate random number creation completion.
* Doesn't calculate average number of digits of operands.
* Creates random numbers in exponential notation.
bigtime-OOM.js
==============
* Creates random numbers and BigNumber and BigDecimal objects all in one go.
* MAY RUN OUT OF MEMORY, e.g. if iterations > 500000 and random digits > 40.
* SHOWS SEPARATE TIMES FOR OBJECT CREATION AND METHOD CALLS.
* Only tests methods with two operands (i.e. no abs or negate).
* Indicates random number creation completion.
* Calculates average number of digits of operands.
* Creates random numbers in normal notation.
In general, bigtime.js is recommended over bigtime-OOM.js, which is included as
separate timings for object creation and method calls may be preferred.
Usage
=====
For help:
$ node bigtime -h
Examples:
Compare the time taken by the BigNumber plus method and the BigDecimal add method.
Time 10000 calls to each.
Use operands of up to 40 random digits (each unique for each iteration).
Check that the BigNumber results match the BigDecimal results.
$ node bigtime plus 10000 40
@@ -0,0 +1,699 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<meta name="Author" content="M Mclaughlin">
<title>Testing BigNumber</title>
<style>
body {margin: 0; padding: 0; font-family: Calibri, Arial, Sans-Serif;}
div {margin: 1em 0;}
h1, #counter {text-align: center; background-color: rgb(225, 225, 225);
margin-top: 1em; padding: 0.2em; font-size: 1.2em;}
a {color: rgb(0, 153, 255); margin: 0 0.6em;}
.links {position: fixed; bottom: 1em; right: 2em; font-size: 0.8em;}
.form, #time {width: 36em; margin: 0 auto;}
.form {text-align: left; margin-top: 1.4em;}
.random input {margin-left: 1em;}
.small {font-size: 0.9em;}
.methods {margin: 1em auto; width: 18em;}
.iterations input, .left {margin-left: 1.6em;}
.info span {margin-left: 1.6em; font-size: 0.9em;}
.info {margin-top: 1.6em;}
.random input, .iterations input {margin-right: 0.3em;}
.random label, .iterations label, .bigd label {font-size: 0.9em;
margin-left: 0.1em;}
.methods label {width: 5em; margin-left: 0.2em; display: inline-block;}
.methods label.right {width: 2em;}
.red {color: red; font-size: 1.1em; font-weight: bold;}
button {width: 10em; height: 2em;}
#dp, #r, #digits, #reps {margin-left: 0.8em;}
#bigint {font-style: italic; display: none;}
#gwt, #icu4j, #bd, #bigint {margin-left: 1.5em;}
#division {display: none;}
#counter {font-size: 2em; background-color: rgb(235, 235, 235);}
#time {text-align: center;}
#results {margin: 0 1.4em;}
</style>
<script src='../bignumber.js'></script>
<script src='./lib/bigdecimal_GWT/bigdecimal.js'></script>
</head>
<body>
<h1>Testing BigNumber against BigDecimal</h1>
<div class='form'>
<div class='methods'>
<input type='radio' id=0 name=1/><label for=0>plus</label>
<input type='radio' id=3 name=1/><label for=3>div</label>
<input type='radio' id=6 name=1/><label for=6 class='right'>abs</label>
<br>
<input type='radio' id=1 name=1/><label for=1>minus</label>
<input type='radio' id=4 name=1/><label for=4>mod</label>
<input type='radio' id=7 name=1/><label for=7 class='right'>neg</label>
<br>
<input type='radio' id=2 name=1/><label for=2>times</label>
<input type='radio' id=5 name=1/><label for=5>cmp</label>
<input type='radio' id=8 name=1/><label for=8 class='right'>pow</label>
</div>
<div class='bigd'>
<span>BigDecimal:</span>
<input type='radio' name=2 id='gwt' /><label for='gwt'>GWT</label>
<input type='radio' name=2 id='icu4j' /><label for='icu4j'>ICU4J</label>
<span id='bigint'>BigInteger</span>
<span id='bd'>add</span>
</div>
<div class='random'>
Random number digits:<input type='text' id='digits' size=12 />
<input type='radio' name=3 id='fix' /><label for='fix'>Fixed</label>
<input type='radio' name=3 id='max' /><label for='max'>Max</label>
<input type='checkbox' id='int' /><label for='int'>Integers only</label>
</div>
<div id='division'>
<span>Decimal places:<input type='text' id='dp' size=9 /></span>
<span class='left'>Rounding:<select id='r'>
<option>UP</option>
<option>DOWN</option>
<option>CEIL</option>
<option>FLOOR</option>
<option>HALF_UP</option>
<option>HALF_DOWN</option>
<option>HALF_EVEN</option>
</select></span>
</div>
<div class='iterations'>
Iterations:<input type='text' id='reps' size=11 />
<input type='checkbox' id='show'/><label for='show'>Show all (no timing)</label>
</div>
<div class='info'>
<button id='start'>Start</button>
<span>Click a method to stop</span>
<span>Press space bar to pause/unpause</span>
</div>
</div>
<div id='counter'>0</div>
<div id='time'></div>
<div id='results'></div>
<div class='links'>
<a href='https://github.com/MikeMcl/bignumber.js' target='_blank'>BigNumber</a>
<a href='https://github.com/iriscouch/bigdecimal.js' target='_blank'>GWT</a>
<a href='https://github.com/dtrebbien/BigDecimal.js/tree/' target='_blank'>ICU4J</a>
</div>
<script>
var i, completedReps, targetReps, cycleReps, cycleTime, prevCycleReps, cycleLimit,
maxDigits, isFixed, isIntOnly, decimalPlaces, rounding, calcTimeout,
counterTimeout, script, isGWT, BigDecimal_GWT, BigDecimal_ICU4J,
bdM, bdTotal, bnM, bnTotal,
bdMs = ['add', 'subtract', 'multiply', 'divide', 'remainder', 'compareTo',
'abs', 'negate', 'pow'],
bnMs = ['plus', 'minus', 'times', 'div', 'mod', 'cmp', 'abs', 'neg', 'pow'],
lastRounding = 4,
pause = false,
up = true,
timingVisible = false,
showAll = false,
// EDIT DEFAULTS HERE
DEFAULT_REPS = 10000,
DEFAULT_DIGITS = 20,
DEFAULT_DECIMAL_PLACES = 20,
DEFAULT_ROUNDING = 4,
MAX_POWER = 20,
CHANCE_NEGATIVE = 0.5, // 0 (never) to 1 (always)
CHANCE_INTEGER = 0.2, // 0 (never) to 1 (always)
MAX_RANDOM_EXPONENT = 100,
SPACE_BAR = 32,
ICU4J_URL = './lib/bigdecimal_ICU4J/BigDecimal-all-last.js',
//
$ = function (id) {return document.getElementById(id)},
$INPUTS = document.getElementsByTagName('input'),
$BD = $('bd'),
$BIGINT = $('bigint'),
$DIGITS = $('digits'),
$GWT = $('gwt'),
$ICU4J = $('icu4j'),
$FIX = $('fix'),
$MAX = $('max'),
$INT = $('int'),
$DIV = $('division'),
$DP = $('dp'),
$R = $('r'),
$REPS = $('reps'),
$SHOW = $('show'),
$START = $('start'),
$COUNTER = $('counter'),
$TIME = $('time'),
$RESULTS = $('results'),
// Get random number in normal notation.
getRandom = function () {
var z,
i = 0,
// n is the number of digits - 1
n = isFixed ? maxDigits - 1 : Math.random() * (maxDigits || 1) | 0,
r = ( Math.random() * 10 | 0 ) + '';
if (n) {
if (r == '0')
r = isIntOnly ? ( ( Math.random() * 9 | 0 ) + 1 ) + '' : (z = r + '.');
for ( ; i++ < n; r += Math.random() * 10 | 0 ){}
if (!z && !isIntOnly && Math.random() > CHANCE_INTEGER) {
r = r.slice( 0, i = (Math.random() * n | 0) + 1 ) +
'.' + r.slice(i);
}
}
// Avoid division by zero error with division and modulo
if ((bdM == 'divide' || bdM == 'remainder') && parseFloat(r) === 0)
r = ( ( Math.random() * 9 | 0 ) + 1 ) + '';
return Math.random() > CHANCE_NEGATIVE ? r : '-' + r;
},
// Get random number in exponential notation (if isIntOnly is false).
// GWT BigDecimal BigInteger does not accept exponential notation.
//getRandom = function () {
// var i = 0,
// // n is the number of significant digits - 1
// n = isFixed ? maxDigits - 1 : Math.random() * (maxDigits || 1) | 0,
// r = ( ( Math.random() * 9 | 0 ) + 1 ) + '';
//
// for (; i++ < n; r += Math.random() * 10 | 0 ){}
//
// if ( !isIntOnly ) {
//
// // Add exponent.
// r += 'e' + ( Math.random() > 0.5 ? '+' : '-' ) +
// ( Math.random() * MAX_RANDOM_EXPONENT | 0 );
// }
//
// return Math.random() > CHANCE_NEGATIVE ? r : '-' + r
//},
showTimings = function () {
var i, bdS, bnS,
sp = '',
r = bnTotal < bdTotal
? (bnTotal ? bdTotal / bnTotal : bdTotal)
: (bdTotal ? bnTotal / bdTotal : bnTotal);
bdS = 'BigDecimal: ' + (bdTotal || '<1');
bnS = 'BigNumber: ' + (bnTotal || '<1');
for ( i = bdS.length - bnS.length; i-- > 0; sp += '&nbsp;'){}
bnS = 'BigNumber: ' + sp + (bnTotal || '<1');
$TIME.innerHTML =
'No mismatches<div>' + bdS + ' ms<br>' + bnS + ' ms</div>' +
((r = parseFloat(r.toFixed(1))) > 1
? 'Big' + (bnTotal < bdTotal ? 'Number' : 'Decimal')
+ ' was ' + r + ' times faster'
: 'Times approximately equal');
},
clear = function () {
clearTimeout(calcTimeout);
clearTimeout(counterTimeout);
$COUNTER.style.textDecoration = 'none';
$COUNTER.innerHTML = '0';
$TIME.innerHTML = $RESULTS.innerHTML = '';
$START.innerHTML = 'Start';
},
begin = function () {
var i;
clear();
targetReps = +$REPS.value;
if (!(targetReps > 0)) return;
$START.innerHTML = 'Restart';
i = +$DIGITS.value;
$DIGITS.value = maxDigits = i && isFinite(i) ? i : DEFAULT_DIGITS;
for (i = 0; i < 9; i++) {
if ($INPUTS[i].checked) {
bnM = bnMs[$INPUTS[i].id];
bdM = bdMs[$INPUTS[i].id];
break;
}
}
if (bdM == 'divide') {
i = +$DP.value;
$DP.value = decimalPlaces = isFinite(i) ? i : DEFAULT_DECIMAL_PLACES;
rounding = $R.selectedIndex;
BigNumber.config(decimalPlaces, rounding);
}
isFixed = $FIX.checked;
isIntOnly = $INT.checked;
showAll = $SHOW.checked;
BigDecimal = (isGWT = $GWT.checked)
? (isIntOnly ? BigInteger : BigDecimal_GWT)
: BigDecimal_ICU4J;
prevCycleReps = cycleLimit = completedReps = bdTotal = bnTotal = 0;
pause = false;
cycleReps = showAll ? 1 : 0.5;
cycleTime = +new Date();
setTimeout(updateCounter, 0);
},
updateCounter = function () {
if (pause) {
if (!timingVisible && !showAll) {
showTimings();
timingVisible = true;
}
counterTimeout = setTimeout(updateCounter, 50);
return
}
$COUNTER.innerHTML = completedReps;
if (completedReps < targetReps) {
if (timingVisible) {
$TIME.innerHTML = '';
timingVisible = false;
}
if (!showAll) {
// Adjust cycleReps so counter is updated every second-ish
if (prevCycleReps != cycleReps) {
// cycleReps too low
if (+new Date() - cycleTime < 1e3) {
prevCycleReps = cycleReps;
if (cycleLimit) {
cycleReps += ((cycleLimit - cycleReps) / 2);
} else {
cycleReps *= 2;
}
// cycleReps too high
} else {
cycleLimit = cycleReps;
cycleReps -= ((cycleReps - prevCycleReps) / 2);
}
cycleReps = Math.floor(cycleReps) || 1;
cycleTime = +new Date();
}
if (completedReps + cycleReps > targetReps) {
cycleReps = targetReps - completedReps;
}
}
completedReps += cycleReps;
calcTimeout = setTimeout(calc, 0);
// Finished - show timings summary
} else {
$START.innerHTML = 'Start';
$COUNTER.style.textDecoration = 'underline';
if (!showAll) {
showTimings();
}
}
},
calc = function () {
var start, bdT, bnT, bdR, bnR,
xs = [cycleReps],
ys = [cycleReps],
bdRs = [cycleReps],
bnRs = [cycleReps];
// GENERATE RANDOM OPERANDS
for (i = 0; i < cycleReps; i++) {
xs[i] = getRandom();
}
if (bdM == 'pow') {
// GWT pow argument must be Number type and integer
if (isGWT) {
for (i = 0; i < cycleReps; i++) {
ys[i] = Math.floor(Math.random() * (MAX_POWER + 1));
}
// ICU4J pow argument must be BigDecimal
} else {
for (i = 0; i < cycleReps; i++) {
ys[i] = Math.floor(Math.random() * (MAX_POWER + 1)) + '';
}
}
// No second operand needed for abs and negate
} else if (bdM != 'abs' && bdM != 'negate') {
for (i = 0; i < cycleReps; i++) {
ys[i] = getRandom();
}
}
//********************************************************************//
//************************** START TIMING ****************************//
//********************************************************************//
// BIGDECIMAL
if (bdM == 'divide') {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](new BigDecimal(ys[i]),
decimalPlaces, rounding);
}
bdT = +new Date() - start;
// GWT pow argument must be Number type and integer
} else if (bdM == 'pow' && isGWT) {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](ys[i]);
}
bdT = +new Date() - start;
} else if (bdM == 'abs' || bdM == 'negate') {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM]();
}
bdT = +new Date() - start;
} else {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](new BigDecimal(ys[i]));
}
bdT = +new Date() - start;
}
// BIGNUM
if (bdM == 'pow') {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM](ys[i]);
}
bnT = +new Date() - start;
} else if (bdM == 'abs' || bdM == 'negate') {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM]();
}
bnT = +new Date() - start;
} else {
start = +new Date();
for (i = 0; i < cycleReps; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM](new BigNumber(ys[i]));
}
bnT = +new Date() - start;
}
//********************************************************************//
//**************************** END TIMING ****************************//
//********************************************************************//
// CHECK FOR MISMATCHES
for (i = 0; i < cycleReps; i++) {
bnR = bnRs[i].toString();
// Remove any trailing zeros from BigDecimal result
if (isGWT) {
bdR = bdM == 'compareTo' || isIntOnly
? bdRs[i].toString()
: bdRs[i].stripTrailingZeros().toPlainString();
} else {
// No toPlainString() or stripTrailingZeros() in ICU4J
bdR = bdRs[i].toString();
if (bdR.indexOf('.') != -1) {
bdR = bdR.replace(/\.?0+$/, '');
}
}
if (bdR !== bnR) {
$RESULTS.innerHTML =
'<span class="red">Breaking on first mismatch:</span>' +
'<br><br>' +xs[i] + '<br>' + bnM + '<br>' + ys[i] +
'<br><br>BigDecimal<br>' + bdR + '<br>' + bnR + '<br>BigNumber';
if (bdM == 'divide') {
$RESULTS.innerHTML += '<br><br>Decimal places: ' +
decimalPlaces + '<br>Rounding mode: ' + rounding;
}
return;
} else if (showAll) {
$RESULTS.innerHTML = xs[i] + '<br>' + bnM + '<br>' + ys[i] +
'<br><br>BigDecimal<br>' + bdR + '<br>' + bnR + '<br>BigNumber';
}
}
bdTotal += bdT;
bnTotal += bnT;
updateCounter();
};
// EVENT HANDLERS
document.onkeyup = function (evt) {
evt = evt || window.event;
if ((evt.keyCode || evt.which) == SPACE_BAR) {
up = true;
}
};
document.onkeydown = function (evt) {
evt = evt || window.event;
if (up && (evt.keyCode || evt.which) == SPACE_BAR) {
pause = !pause;
up = false;
}
};
// BigNumber methods' radio buttons' event handlers
for (i = 0; i < 9; i++) {
$INPUTS[i].checked = false;
$INPUTS[i].disabled = false;
$INPUTS[i].onclick = function () {
clear();
lastRounding = $R.options.selectedIndex;
$DIV.style.display = 'none';
bnM = bnMs[this.id];
$BD.innerHTML = bdM = bdMs[this.id];
};
}
$INPUTS[1].onclick = function () {
clear();
$R.options.selectedIndex = lastRounding;
$DIV.style.display = 'block';
bnM = bnMs[this.id];
$BD.innerHTML = bdM = bdMs[this.id];
};
// Show/hide BigInteger and disable/un-disable division accordingly as BigInteger
// throws an exception if division gives "no exact representable decimal result"
$INT.onclick = function () {
if (this.checked && $GWT.checked) {
if ($INPUTS[1].checked) {
$INPUTS[1].checked = false;
$INPUTS[0].checked = true;
$BD.innerHTML = bdMs[$INPUTS[0].id];
$DIV.style.display = 'none';
}
$INPUTS[1].disabled = true;
$BIGINT.style.display = 'inline';
} else {
$INPUTS[1].disabled = false;
$BIGINT.style.display = 'none';
}
};
$ICU4J.onclick = function () {
$INPUTS[1].disabled = false;
$BIGINT.style.display = 'none';
};
$GWT.onclick = function () {
if ($INT.checked) {
if ($INPUTS[1].checked) {
$INPUTS[1].checked = false;
$INPUTS[0].checked = true;
$BD.innerHTML = bdMs[$INPUTS[0].id];
$DIV.style.display = 'none';
}
$INPUTS[1].disabled = true;
$BIGINT.style.display = 'inline';
}
};
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : false,
RANGE : 1E9,
EXPONENTIAL_AT : 1E9
});
// Set defaults
$MAX.checked = $INPUTS[0].checked = $GWT.checked = true;
$SHOW.checked = $INT.checked = false;
$REPS.value = DEFAULT_REPS;
$DIGITS.value = DEFAULT_DIGITS;
$DP.value = DEFAULT_DECIMAL_PLACES;
$R.option = DEFAULT_ROUNDING;
BigDecimal_GWT = BigDecimal;
BigDecimal = undefined;
// Load ICU4J BigDecimal
script = document.createElement("script");
script.src = ICU4J_URL;
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
script = null;
BigDecimal_ICU4J = BigDecimal;
$START.onmousedown = begin;
}
};
document.getElementsByTagName("head")[0].appendChild(script);
/*
NOTES:
ICU4J
=====
IBM java package: com.ibm.icu.math
pow's argument must be a BigDecimal.
Among other differences, doesn't have .toPlainString() or .stripTrailingZeros().
Exports BigDecimal only.
Much faster than gwt on Firefox, on Chrome it varies with the method.
GWT
===
Java standard class library: java.math.BigDecimal
Exports:
RoundingMode
MathContext
BigDecimal
BigInteger
BigDecimal properties:
ROUND_CEILING
ROUND_DOWN
ROUND_FLOOR
ROUND_HALF_DOWN
ROUND_HALF_EVEN
ROUND_HALF_UP
ROUND_UNNECESSARY
ROUND_UP
__init__
valueOf
log
logObj
ONE
TEN
ZERO
BigDecimal instance properties/methods:
( for (var i in new BigDecimal('1').__gwt_instance.__gwtex_wrap) {...} )
byteValueExact
compareTo
doubleValue
equals
floatValue
hashCode
intValue
intValueExact
max
min
movePointLeft
movePointRight
precision
round
scale
scaleByPowerOfTen
shortValueExact
signum
stripTrailingZeros
toBigInteger
toBigIntegerExact
toEngineeringString
toPlainString
toString
ulp
unscaledValue
longValue
longValueExact
abs
add
divide
divideToIntegralValue
multiply
negate
plus
pow
remainder
setScale
subtract
divideAndRemainder
*/
</script>
</body>
</html>
+366
View File
@@ -0,0 +1,366 @@
var arg, i, max, method, methodIndex, decimalPlaces,
reps, rounding, start, timesEqual, Xs, Ys,
bdM, bdMT, bdOT, bdRs, bdXs, bdYs,
bnM, bnMT, bnOT, bnRs, bnXs, bnYs,
memoryUsage, showMemory, bnR, bdR,
prevRss, prevHeapUsed, prevHeapTotal,
args = process.argv.splice(2),
BigDecimal = require('./lib/bigdecimal_GWT/bigdecimal').BigDecimal,
BigNumber = require('../bignumber'),
bdMs = ['add', 'subtract', 'multiply', 'divide', 'remainder', 'compareTo', 'pow'],
bnMs1 = ['plus', 'minus', 'times', 'dividedBy', 'modulo', 'comparedTo', 'toPower'],
bnMs2 = ['', '', '', 'div', 'mod', 'cmp', ''],
Ms = [bdMs, bnMs1, bnMs2],
allMs = [].concat.apply([], Ms),
expTotal = 0,
total = 0,
ALWAYS_SHOW_MEMORY = false,
DEFAULT_MAX_DIGITS = 20,
DEFAULT_POW_MAX_DIGITS = 20,
DEFAULT_REPS = 1e4,
DEFAULT_POW_REPS = 1e2,
DEFAULT_PLACES = 20,
MAX_POWER = 50,
getRandom = function (maxDigits) {
var i = 0, z,
// number of digits - 1
n = Math.random() * ( maxDigits || 1 ) | 0,
r = ( Math.random() * 10 | 0 ) + '';
if ( n ) {
if ( z = r === '0' ) {
r += '.';
}
for ( ; i++ < n; r += Math.random() * 10 | 0 ){}
// 20% chance of integer
if ( !z && Math.random() > 0.2 )
r = r.slice( 0, i = ( Math.random() * n | 0 ) + 1 ) + '.' + r.slice(i);
}
// Avoid 'division by zero' error with division and modulo.
if ((bdM == 'divide' || bdM == 'remainder') && parseFloat(r) === 0)
r = ( ( Math.random() * 9 | 0 ) + 1 ) + '';
total += n + 1;
// 50% chance of negative
return Math.random() > 0.5 ? r : '-' + r;
},
pad = function (str) {
str += '... ';
while (str.length < 26) str += ' ';
return str;
},
getFastest = function (bn, bd) {
var r;
if (Math.abs(bn - bd) > 2) {
r = 'Big' + ((bn < bd)
? 'Number ' + (bn ? parseFloat((bd / bn).toFixed(1)) : bd)
: 'Decimal ' + (bd ? parseFloat((bn / bd).toFixed(1)) : bn)) +
' times faster';
} else {
timesEqual = 1;
r = 'Times approximately equal';
}
return r;
},
showMemoryChange = function () {
if (showMemory) {
memoryUsage = process.memoryUsage();
var rss = memoryUsage.rss,
heapUsed = memoryUsage.heapUsed,
heapTotal = memoryUsage.heapTotal;
console.log(' Change in memory usage: ' +
' rss: ' + toKB(rss - prevRss) +
', hU: ' + toKB(heapUsed - prevHeapUsed) +
', hT: ' + toKB(heapTotal - prevHeapTotal));
prevRss = rss; prevHeapUsed = heapUsed; prevHeapTotal = heapTotal;
}
},
toKB = function (m) {
return parseFloat((m / 1024).toFixed(1)) + ' KB';
};
// PARSE COMMAND LINE AND SHOW HELP
if (arg = args[0], typeof arg != 'undefined' && !isFinite(arg) &&
allMs.indexOf(arg) == -1 && !/^-*m$/i.test(arg)) {
console.log(
'\n node bigtime-OOM [METHOD] [METHOD CALLS [MAX DIGITS [DECIMAL PLACES]]]\n' +
'\n METHOD: The method to be timed and compared with the automatically' +
'\n chosen corresponding method from BigDecimal or BigNumber\n' +
'\n BigDecimal: add subtract multiply divide remainder compareTo pow' +
'\n BigNumber: plus minus times dividedBy modulo comparedTo toPower' +
'\n (div mod cmp pow)' +
'\n\n METHOD CALLS: The number of method calls to be timed' +
'\n\n MAX DIGITS: The maximum number of digits of the random ' +
'\n numbers used in the method calls' +
'\n\n DECIMAL PLACES: The number of decimal places used in division' +
'\n (The rounding mode is randomly chosen)' +
'\n\n Default values: METHOD: randomly chosen' +
'\n METHOD CALLS: ' + DEFAULT_REPS +
' (pow: ' + DEFAULT_POW_REPS + ')' +
'\n MAX DIGITS: ' + DEFAULT_MAX_DIGITS +
' (pow: ' + DEFAULT_POW_MAX_DIGITS + ')' +
'\n DECIMAL PLACES: ' + DEFAULT_PLACES + '\n' +
'\n E.g.s node bigtime-OOM\n node bigtime-OOM minus' +
'\n node bigtime-OOM add 100000' +
'\n node bigtime-OOM times 20000 100' +
'\n node bigtime-OOM div 100000 50 20' +
'\n node bigtime-OOM 9000' +
'\n node bigtime-OOM 1000000 20\n' +
'\n To show memory usage include an argument m or -m' +
'\n E.g. node bigtime-OOM m add');
} else {
BigNumber.config({EXPONENTIAL_AT : 1E9, RANGE : 1E9});
Number.prototype.toPlainString = Number.prototype.toString;
for (i = 0; i < args.length; i++) {
arg = args[i];
if (isFinite(arg)) {
arg = Math.abs(parseInt(arg));
if (reps == null) {
reps = arg <= 1e10 ? arg : 0;
} else if (max == null) {
max = arg <= 1e6 ? arg : 0;
} else if (decimalPlaces == null) {
decimalPlaces = arg <= 1e6 ? arg : DEFAULT_PLACES;
}
} else if (/^-*m$/i.test(arg)) {
showMemory = true;
} else if (method == null) {
method = arg;
}
}
for (i = 0;
i < Ms.length && (methodIndex = Ms[i].indexOf(method)) == -1;
i++) {}
bnM = methodIndex == -1
? bnMs1[methodIndex = Math.floor(Math.random() * bdMs.length)]
: (Ms[i][0] == 'add' ? bnMs1 : Ms[i])[methodIndex];
bdM = bdMs[methodIndex];
if (!reps)
reps = bdM == 'pow' ? DEFAULT_POW_REPS : DEFAULT_REPS;
if (!max)
max = bdM == 'pow' ? DEFAULT_POW_MAX_DIGITS : DEFAULT_MAX_DIGITS;
if (decimalPlaces == null)
decimalPlaces = DEFAULT_PLACES;
Xs = [reps], Ys = [reps];
bdXs = [reps], bdYs = [reps], bdRs = [reps];
bnXs = [reps], bnYs = [reps], bnRs = [reps];
showMemory = showMemory || ALWAYS_SHOW_MEMORY;
console.log('\n BigNumber %s vs BigDecimal %s', bnM, bdM);
console.log('\n Method calls: %d', reps);
if (bdM == 'divide') {
rounding = Math.floor(Math.random() * 7);
console.log('\n Decimal places: %d\n Rounding mode: %d', decimalPlaces, rounding);
BigNumber.config(decimalPlaces, rounding);
}
if (showMemory) {
memoryUsage = process.memoryUsage();
console.log(' Memory usage: rss: ' +
toKB(prevRss = memoryUsage.rss) + ', hU: ' +
toKB(prevHeapUsed = memoryUsage.heapUsed) + ', hT: ' +
toKB(prevHeapTotal = memoryUsage.heapTotal));
}
// CREATE RANDOM NUMBERS
// POW: BigDecimal requires JS Number type for exponent argument
if (bdM == 'pow') {
process.stdout.write('\n Creating ' + reps +
' random numbers (max. digits: ' + max + ')... ');
for (i = 0; i < reps; i++) {
Xs[i] = getRandom(max);
}
console.log('done\n Average number of digits: %d',
((total / reps) | 0));
process.stdout.write(' Creating ' + reps +
' random integer exponents (max. value: ' + MAX_POWER + ')... ');
for (i = 0; i < reps; i++) {
bdYs[i] = bnYs[i] = Math.floor(Math.random() * (MAX_POWER + 1));
expTotal += bdYs[i];
}
console.log('done\n Average value: %d', ((expTotal / reps) | 0));
showMemoryChange();
// POW: TIME CREATION OF BIGDECIMALS
process.stdout.write('\n Creating BigDecimals... ');
start = +new Date();
for (i = 0; i < reps; i++) {
bdXs[i] = new BigDecimal(Xs[i]);
}
bdOT = +new Date() - start;
console.log('done. Time taken: %s ms', bdOT || '<1');
showMemoryChange();
// POW: TIME CREATION OF BIGNUMBERS
process.stdout.write(' Creating BigNumbers... ');
start = +new Date();
for (i = 0; i < reps; i++) {
bnXs[i] = new BigNumber(Xs[i]);
}
bnOT = +new Date() - start;
console.log('done. Time taken: %s ms', bnOT || '<1');
// NOT POW
} else {
process.stdout.write('\n Creating ' + (reps * 2) +
' random numbers (max. digits: ' + max + ')... ');
for (i = 0; i < reps; i++) {
Xs[i] = getRandom(max);
Ys[i] = getRandom(max);
}
console.log('done\n Average number of digits: %d',
( total / (reps * 2) ) | 0);
showMemoryChange();
// TIME CREATION OF BIGDECIMALS
process.stdout.write('\n Creating BigDecimals... ');
start = +new Date();
for (i = 0; i < reps; i++) {
bdXs[i] = new BigDecimal(Xs[i]);
bdYs[i] = new BigDecimal(Ys[i]);
}
bdOT = +new Date() - start;
console.log('done. Time taken: %s ms', bdOT || '<1');
showMemoryChange();
// TIME CREATION OF BIGNUMBERS
process.stdout.write(' Creating BigNumbers... ');
start = +new Date();
for (i = 0; i < reps; i++) {
bnXs[i] = new BigNumber(Xs[i]);
bnYs[i] = new BigNumber(Ys[i]);
}
bnOT = +new Date() - start;
console.log('done. Time taken: %s ms', bnOT || '<1');
}
showMemoryChange();
console.log('\n Object creation: %s\n', getFastest(bnOT, bdOT));
// TIME BIGDECIMAL METHOD CALLS
process.stdout.write(pad(' BigDecimal ' + bdM));
if (bdM == 'divide') {
start = +new Date();
while (i--) bdRs[i] = bdXs[i][bdM](bdYs[i], decimalPlaces, rounding);
bdMT = +new Date() - start;
} else {
start = +new Date();
while (i--) bdRs[i] = bdXs[i][bdM](bdYs[i]);
bdMT = +new Date() - start;
}
console.log('done. Time taken: %s ms', bdMT || '<1');
// TIME BIGNUMBER METHOD CALLS
i = reps;
process.stdout.write(pad(' BigNumber ' + bnM));
start = +new Date();
while (i--) bnRs[i] = bnXs[i][bnM](bnYs[i]);
bnMT = +new Date() - start;
console.log('done. Time taken: %s ms', bnMT || '<1');
// TIMINGS SUMMARY
console.log('\n Method calls: %s', getFastest(bnMT, bdMT));
if (!timesEqual) {
console.log('\n Overall: ' +
getFastest((bnOT || 1) + (bnMT || 1), (bdOT || 1) + (bdMT || 1)));
}
// CHECK FOR MISMATCHES
process.stdout.write('\n Checking for mismatches... ');
for (i = 0; i < reps; i++) {
bnR = bnRs[i].toString();
bdR = bdRs[i].toPlainString();
// Strip any trailing zeros from non-integer BigDecimals
if (bdR.indexOf('.') != -1) {
bdR = bdR.replace(/\.?0+$/, '');
}
if (bdR !== bnR) {
console.log('breaking on first mismatch (result number %d):' +
'\n\n BigDecimal: %s\n BigNumber: %s', i, bdR, bnR);
console.log('\n x: %s\n y: %s', Xs[i], Ys[i]);
if (bdM == 'divide') {
console.log('\n dp: %d\n r: %d',decimalPlaces, rounding);
}
break;
}
}
if (i == reps) {
console.log('done. None found.\n');
}
}
+335
View File
@@ -0,0 +1,335 @@
var arg, i, j, max, method, methodIndex, decimalPlaces, rounding, reps, start,
timesEqual, xs, ys, prevRss, prevHeapUsed, prevHeapTotal, showMemory,
bdM, bdT, bdR, bdRs,
bnM, bnT, bnR, bnRs,
args = process.argv.splice(2),
BigDecimal = require('./lib/bigdecimal_GWT/bigdecimal').BigDecimal,
BigNumber = require('../bignumber'),
bdMs = ['add', 'subtract', 'multiply', 'divide', 'remainder',
'compareTo', 'pow', 'negate', 'abs'],
bnMs1 = ['plus', 'minus', 'times', 'dividedBy', 'modulo',
'comparedTo', 'toPower', 'negated', 'abs'],
bnMs2 = ['', '', '', 'div', 'mod', 'cmp', '', 'neg', ''],
Ms = [bdMs, bnMs1, bnMs2],
allMs = [].concat.apply([], Ms),
bdTotal = 0,
bnTotal = 0,
BD = {},
BN = {},
ALWAYS_SHOW_MEMORY = false,
DEFAULT_MAX_DIGITS = 20,
DEFAULT_POW_MAX_DIGITS = 20,
DEFAULT_REPS = 1e4,
DEFAULT_POW_REPS = 1e2,
DEFAULT_PLACES = 20,
MAX_POWER = 50,
MAX_RANDOM_EXPONENT = 100,
getRandom = function (maxDigits) {
var i = 0, z,
// number of digits - 1
n = Math.random() * ( maxDigits || 1 ) | 0,
r = ( Math.random() * 10 | 0 ) + '';
if ( n ) {
if ( z = r === '0' ) {
r += '.';
}
for ( ; i++ < n; r += Math.random() * 10 | 0 ){}
// 20% chance of integer
if ( !z && Math.random() > 0.2 )
r = r.slice( 0, i = ( Math.random() * n | 0 ) + 1 ) + '.' + r.slice(i);
}
// Avoid 'division by zero' error with division and modulo.
if ((bdM == 'divide' || bdM == 'remainder') && parseFloat(r) === 0)
r = ( ( Math.random() * 9 | 0 ) + 1 ) + '';
// 50% chance of negative
return Math.random() > 0.5 ? r : '-' + r;
},
// Returns exponential notation.
//getRandom = function (maxDigits) {
// var i = 0,
// // n is the number of significant digits - 1
// n = Math.random() * (maxDigits || 1) | 0,
// r = ( ( Math.random() * 9 | 0 ) + 1 ) + ( n ? '.' : '' );
//
// for (; i++ < n; r += Math.random() * 10 | 0 ){}
//
// // Add exponent.
// r += 'e' + ( Math.random() > 0.5 ? '+' : '-' ) +
// ( Math.random() * MAX_RANDOM_EXPONENT | 0 );
//
// // 50% chance of being negative.
// return Math.random() > 0.5 ? r : '-' + r
//},
getFastest = function (bn, bd) {
var r;
if (Math.abs(bn - bd) > 2) {
r = 'Big' + ((bn < bd)
? 'Number was ' + (bn ? parseFloat((bd / bn).toFixed(1)) : bd)
: 'Decimal was ' + (bd ? parseFloat((bn / bd).toFixed(1)) : bn)) +
' times faster';
} else {
timesEqual = 1;
r = 'Times approximately equal';
}
return r;
},
getMemory = function (obj) {
if (showMemory) {
var mem = process.memoryUsage(),
rss = mem.rss,
heapUsed = mem.heapUsed,
heapTotal = mem.heapTotal;
if (obj) {
obj.rss += (rss - prevRss);
obj.hU += (heapUsed - prevHeapUsed);
obj.hT += (heapTotal - prevHeapTotal);
}
prevRss = rss;
prevHeapUsed = heapUsed;
prevHeapTotal = heapTotal;
}
},
getMemoryTotals = function (obj) {
function toKB(m) {return parseFloat((m / 1024).toFixed(1))}
return '\trss: ' + toKB(obj.rss) +
'\thU: ' + toKB(obj.hU) +
'\thT: ' + toKB(obj.hT);
};
if (arg = args[0], typeof arg != 'undefined' && !isFinite(arg) &&
allMs.indexOf(arg) == -1 && !/^-*m$/i.test(arg)) {
console.log(
'\n node bigtime [METHOD] [METHOD CALLS [MAX DIGITS [DECIMAL PLACES]]]\n' +
'\n METHOD: The method to be timed and compared with the' +
'\n \t corresponding method from BigDecimal or BigNumber\n' +
'\n BigDecimal: add subtract multiply divide remainder' +
' compareTo pow\n\t\tnegate abs\n\n BigNumber: plus minus times' +
' dividedBy modulo comparedTo toPower\n\t\tnegated abs' +
' (div mod cmp pow neg)' +
'\n\n METHOD CALLS: The number of method calls to be timed' +
'\n\n MAX DIGITS: The maximum number of digits of the random ' +
'\n\t\tnumbers used in the method calls\n\n ' +
'DECIMAL PLACES: The number of decimal places used in division' +
'\n\t\t(The rounding mode is randomly chosen)' +
'\n\n Default values: METHOD: randomly chosen' +
'\n\t\t METHOD CALLS: ' + DEFAULT_REPS +
' (pow: ' + DEFAULT_POW_REPS + ')' +
'\n\t\t MAX DIGITS: ' + DEFAULT_MAX_DIGITS +
' (pow: ' + DEFAULT_POW_MAX_DIGITS + ')' +
'\n\t\t DECIMAL PLACES: ' + DEFAULT_PLACES + '\n' +
'\n E.g. node bigtime\n\tnode bigtime minus\n\tnode bigtime add 100000' +
'\n\tnode bigtime times 20000 100\n\tnode bigtime div 100000 50 20' +
'\n\tnode bigtime 9000\n\tnode bigtime 1000000 20\n' +
'\n To show memory usage, include an argument m or -m' +
'\n E.g. node bigtime m add');
} else {
BigNumber.config({EXPONENTIAL_AT : 1E9, RANGE : 1E9});
Number.prototype.toPlainString = Number.prototype.toString;
for (i = 0; i < args.length; i++) {
arg = args[i];
if (isFinite(arg)) {
arg = Math.abs(parseInt(arg));
if (reps == null)
reps = arg <= 1e10 ? arg : 0;
else if (max == null)
max = arg <= 1e6 ? arg : 0;
else if (decimalPlaces == null)
decimalPlaces = arg <= 1e6 ? arg : DEFAULT_PLACES;
} else if (/^-*m$/i.test(arg))
showMemory = true;
else if (method == null)
method = arg;
}
for (i = 0;
i < Ms.length && (methodIndex = Ms[i].indexOf(method)) == -1;
i++) {}
bnM = methodIndex == -1
? bnMs1[methodIndex = Math.floor(Math.random() * bdMs.length)]
: (Ms[i][0] == 'add' ? bnMs1 : Ms[i])[methodIndex];
bdM = bdMs[methodIndex];
if (!reps)
reps = bdM == 'pow' ? DEFAULT_POW_REPS : DEFAULT_REPS;
if (!max)
max = bdM == 'pow' ? DEFAULT_POW_MAX_DIGITS : DEFAULT_MAX_DIGITS;
if (decimalPlaces == null)
decimalPlaces = DEFAULT_PLACES;
xs = [reps], ys = [reps], bdRs = [reps], bnRs = [reps];
BD.rss = BD.hU = BD.hT = BN.rss = BN.hU = BN.hT = 0;
showMemory = showMemory || ALWAYS_SHOW_MEMORY;
console.log('\n BigNumber %s vs BigDecimal %s\n' +
'\n Method calls: %d\n\n Random operands: %d', bnM, bdM, reps,
bdM == 'abs' || bdM == 'negate' || bdM == 'abs' ? reps : reps * 2);
console.log(' Max. digits of operands: %d', max);
if (bdM == 'divide') {
rounding = Math.floor(Math.random() * 7);
console.log('\n Decimal places: %d\n Rounding mode: %d', decimalPlaces, rounding);
BigNumber.config(decimalPlaces, rounding);
}
process.stdout.write('\n Testing started');
outer:
for (; reps > 0; reps -= 1e4) {
j = Math.min(reps, 1e4);
// GENERATE RANDOM OPERANDS
for (i = 0; i < j; i++) {
xs[i] = getRandom(max);
}
if (bdM == 'pow') {
for (i = 0; i < j; i++) {
ys[i] = Math.floor(Math.random() * (MAX_POWER + 1));
}
} else if (bdM != 'abs' && bdM != 'negate') {
for (i = 0; i < j; i++) {
ys[i] = getRandom(max);
}
}
getMemory();
// BIGDECIMAL
if (bdM == 'divide') {
start = +new Date();
for (i = 0; i < j; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](new BigDecimal(ys[i]),
decimalPlaces, rounding);
}
bdT = +new Date() - start;
} else if (bdM == 'pow') {
start = +new Date();
for (i = 0; i < j; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](ys[i]);
}
bdT = +new Date() - start;
} else if (bdM == 'abs' || bdM == 'negate') {
start = +new Date();
for (i = 0; i < j; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM]();
}
bdT = +new Date() - start;
} else {
start = +new Date();
for (i = 0; i < j; i++) {
bdRs[i] = new BigDecimal(xs[i])[bdM](new BigDecimal(ys[i]));
}
bdT = +new Date() - start;
}
getMemory(BD);
// BIGNUMBER
if (bdM == 'pow') {
start = +new Date();
for (i = 0; i < j; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM](ys[i]);
}
bnT = +new Date() - start;
} else if (bdM == 'abs' || bdM == 'negate') {
start = +new Date();
for (i = 0; i < j; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM]();
}
bnT = +new Date() - start;
} else {
start = +new Date();
for (i = 0; i < j; i++) {
bnRs[i] = new BigNumber(xs[i])[bnM](new BigNumber(ys[i]));
}
bnT = +new Date() - start;
}
getMemory(BN);
// CHECK FOR MISMATCHES
for (i = 0; i < j; i++) {
bnR = bnRs[i].toString();
bdR = bdRs[i].toPlainString();
// Strip any trailing zeros from non-integer BigDecimals
if (bdR.indexOf('.') != -1) {
bdR = bdR.replace(/\.?0+$/, '');
}
if (bdR !== bnR) {
console.log('\n breaking on first mismatch (result number %d):' +
'\n\n BigDecimal: %s\n BigNumber: %s', i, bdR, bnR);
console.log('\n x: %s\n y: %s', xs[i], ys[i]);
if (bdM == 'divide')
console.log('\n dp: %d\n r: %d',decimalPlaces, rounding);
break outer;
}
}
bdTotal += bdT;
bnTotal += bnT;
process.stdout.write(' .');
}
// TIMINGS SUMMARY
if (i == j) {
console.log(' done\n\n No mismatches.');
if (showMemory) {
console.log('\n Change in memory usage (KB):' +
'\n\tBigDecimal' + getMemoryTotals(BD) +
'\n\tBigNumber ' + getMemoryTotals(BN));
}
console.log('\n Time taken:' +
'\n\tBigDecimal ' + (bdTotal || '<1') + ' ms' +
'\n\tBigNumber ' + (bnTotal || '<1') + ' ms\n\n ' +
getFastest(bnTotal, bdTotal) + '\n');
}
}
@@ -0,0 +1,60 @@
// javac BigDecTest.java
// java BigDecTest
import java.math.BigDecimal;
public class BigDecTest
{
public static void main(String[] args) {
int i;
BigDecimal x, y, r;
// remainder
x = new BigDecimal("9.785496E-2");
y = new BigDecimal("-5.9219189762E-2");
r = x.remainder(y);
System.out.println( r.toString() );
// 0.038635770238
x = new BigDecimal("1.23693014661017964112E-5");
y = new BigDecimal("-6.9318042E-7");
r = x.remainder(y);
System.out.println( r.toPlainString() );
// 0.0000005852343261017964112
// divide
x = new BigDecimal("6.9609119610E-78");
y = new BigDecimal("4E-48");
r = x.divide(y, 40, 6); // ROUND_HALF_EVEN
System.out.println( r.toString() );
// 1.7402279902E-30
x = new BigDecimal("5.383458817E-83");
y = new BigDecimal("8E-54");
r = x.divide(y, 40, 6);
System.out.println( r.toString() );
// 6.7293235212E-30
// compareTo
x = new BigDecimal("0.04");
y = new BigDecimal("0.079393068");
i = x.compareTo(y);
System.out.println(i);
// -1
x = new BigDecimal("7.88749578569876987785987658649E-10");
y = new BigDecimal("4.2545098709E-6");
i = x.compareTo(y);
System.out.println(i);
// -1
}
}
@@ -0,0 +1,205 @@
https://github.com/iriscouch/bigdecimal.js
BigDecimal for Javascript is licensed under the Apache License, version 2.0:
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.
File diff suppressed because one or more lines are too long
@@ -0,0 +1,53 @@
// node bugs
// Compare with BigDecTest.java
var i, x, y, r,
BigDecimal = require('./bigdecimal').BigDecimal;
// remainder
x = new BigDecimal("9.785496E-2");
y = new BigDecimal("-5.9219189762E-2");
r = x.remainder(y);
console.log( r.toString() );
// 0.09785496
// Should be 0.038635770238
x = new BigDecimal("1.23693014661017964112E-5");
y = new BigDecimal("-6.9318042E-7");
r = x.remainder(y);
console.log( r.toPlainString() );
// 0.0000123693014661017964112
// Should be 0.0000005852343261017964112
// divide
x = new BigDecimal("6.9609119610E-78");
y = new BigDecimal("4E-48");
r = x.divide(y, 40, 6); // ROUND_HALF_EVEN
console.log( r.toString() );
// 1.7402279903E-30
// Should be 1.7402279902E-30
x = new BigDecimal("5.383458817E-83");
y = new BigDecimal("8E-54");
r = x.divide(y, 40, 6);
console.log( r.toString() );
// 6.7293235213E-30
// Should be 6.7293235212E-30
// compareTo
x = new BigDecimal("0.04");
y = new BigDecimal("0.079393068");
i = x.compareTo(y);
console.log(i);
// 1
// Should be -1
x = new BigDecimal("7.88749578569876987785987658649E-10");
y = new BigDecimal("4.2545098709E-6");
i = x.compareTo(y);
console.log(i);
// 1
// Should be -1
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,61 @@
/*
Copyright (c) 2012 Daniel Trebbien and other contributors
Portions Copyright (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany
Portions Copyright (c) 1995-2001 International Business Machines Corporation and others
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, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
*/
(function(){var m,k=function(){this.form=this.digits=0;this.lostDigits=!1;this.roundingMode=0;var a=this.DEFAULT_FORM,b=this.DEFAULT_LOSTDIGITS,c=this.DEFAULT_ROUNDINGMODE;if(4==k.arguments.length)a=k.arguments[1],b=k.arguments[2],c=k.arguments[3];else if(3==k.arguments.length)a=k.arguments[1],b=k.arguments[2];else if(2==k.arguments.length)a=k.arguments[1];else if(1!=k.arguments.length)throw"MathContext(): "+k.arguments.length+" arguments given; expected 1 to 4";var d=k.arguments[0];if(d!=this.DEFAULT_DIGITS){if(d<
this.MIN_DIGITS)throw"MathContext(): Digits too small: "+d;if(d>this.MAX_DIGITS)throw"MathContext(): Digits too large: "+d;}if(a!=this.SCIENTIFIC&&a!=this.ENGINEERING&&a!=this.PLAIN)throw"MathContext() Bad form value: "+a;if(!this.isValidRound(c))throw"MathContext(): Bad roundingMode value: "+c;this.digits=d;this.form=a;this.lostDigits=b;this.roundingMode=c};k.prototype.getDigits=function(){return this.digits};k.prototype.getForm=function(){return this.form};k.prototype.getLostDigits=function(){return this.lostDigits};
k.prototype.getRoundingMode=function(){return this.roundingMode};k.prototype.toString=function(){var a=null,b=0,c=null,a=this.form==this.SCIENTIFIC?"SCIENTIFIC":this.form==this.ENGINEERING?"ENGINEERING":"PLAIN",d=this.ROUNDS.length,b=0;a:for(;0<d;d--,b++)if(this.roundingMode==this.ROUNDS[b]){c=this.ROUNDWORDS[b];break a}return"digits="+this.digits+" form="+a+" lostDigits="+(this.lostDigits?"1":"0")+" roundingMode="+c};k.prototype.isValidRound=function(a){var b=0,c=this.ROUNDS.length,b=0;for(;0<c;c--,
b++)if(a==this.ROUNDS[b])return!0;return!1};k.PLAIN=k.prototype.PLAIN=0;k.SCIENTIFIC=k.prototype.SCIENTIFIC=1;k.ENGINEERING=k.prototype.ENGINEERING=2;k.ROUND_CEILING=k.prototype.ROUND_CEILING=2;k.ROUND_DOWN=k.prototype.ROUND_DOWN=1;k.ROUND_FLOOR=k.prototype.ROUND_FLOOR=3;k.ROUND_HALF_DOWN=k.prototype.ROUND_HALF_DOWN=5;k.ROUND_HALF_EVEN=k.prototype.ROUND_HALF_EVEN=6;k.ROUND_HALF_UP=k.prototype.ROUND_HALF_UP=4;k.ROUND_UNNECESSARY=k.prototype.ROUND_UNNECESSARY=7;k.ROUND_UP=k.prototype.ROUND_UP=0;k.prototype.DEFAULT_FORM=
k.prototype.SCIENTIFIC;k.prototype.DEFAULT_DIGITS=9;k.prototype.DEFAULT_LOSTDIGITS=!1;k.prototype.DEFAULT_ROUNDINGMODE=k.prototype.ROUND_HALF_UP;k.prototype.MIN_DIGITS=0;k.prototype.MAX_DIGITS=999999999;k.prototype.ROUNDS=[k.prototype.ROUND_HALF_UP,k.prototype.ROUND_UNNECESSARY,k.prototype.ROUND_CEILING,k.prototype.ROUND_DOWN,k.prototype.ROUND_FLOOR,k.prototype.ROUND_HALF_DOWN,k.prototype.ROUND_HALF_EVEN,k.prototype.ROUND_UP];k.prototype.ROUNDWORDS="ROUND_HALF_UP ROUND_UNNECESSARY ROUND_CEILING ROUND_DOWN ROUND_FLOOR ROUND_HALF_DOWN ROUND_HALF_EVEN ROUND_UP".split(" ");
k.prototype.DEFAULT=new k(k.prototype.DEFAULT_DIGITS,k.prototype.DEFAULT_FORM,k.prototype.DEFAULT_LOSTDIGITS,k.prototype.DEFAULT_ROUNDINGMODE);m=k;var v,G=function(a,b){return(a-a%b)/b},K=function(a){var b=Array(a),c;for(c=0;c<a;++c)b[c]=0;return b},h=function(){this.ind=0;this.form=m.prototype.PLAIN;this.mant=null;this.exp=0;if(0!=h.arguments.length){var a,b,c;1==h.arguments.length?(a=h.arguments[0],b=0,c=a.length):(a=h.arguments[0],b=h.arguments[1],c=h.arguments[2]);"string"==typeof a&&(a=a.split(""));
var d,e,i,f,g,j=0,l=0;e=!1;var k=l=l=j=0,q=0;f=0;0>=c&&this.bad("BigDecimal(): ",a);this.ind=this.ispos;"-"==a[0]?(c--,0==c&&this.bad("BigDecimal(): ",a),this.ind=this.isneg,b++):"+"==a[0]&&(c--,0==c&&this.bad("BigDecimal(): ",a),b++);e=d=!1;i=0;g=f=-1;k=c;j=b;a:for(;0<k;k--,j++){l=a[j];if("0"<=l&&"9">=l){g=j;i++;continue a}if("."==l){0<=f&&this.bad("BigDecimal(): ",a);f=j-b;continue a}if("e"!=l&&"E"!=l){("0">l||"9"<l)&&this.bad("BigDecimal(): ",a);d=!0;g=j;i++;continue a}j-b>c-2&&this.bad("BigDecimal(): ",
a);e=!1;"-"==a[j+1]?(e=!0,j+=2):j="+"==a[j+1]?j+2:j+1;l=c-(j-b);(0==l||9<l)&&this.bad("BigDecimal(): ",a);c=l;l=j;for(;0<c;c--,l++)k=a[l],"0">k&&this.bad("BigDecimal(): ",a),"9"<k?this.bad("BigDecimal(): ",a):q=k-0,this.exp=10*this.exp+q;e&&(this.exp=-this.exp);e=!0;break a}0==i&&this.bad("BigDecimal(): ",a);0<=f&&(this.exp=this.exp+f-i);q=g-1;j=b;a:for(;j<=q;j++)if(l=a[j],"0"==l)b++,f--,i--;else if("."==l)b++,f--;else break a;this.mant=Array(i);l=b;if(d){b=i;j=0;for(;0<b;b--,j++)j==f&&l++,k=a[l],
"9">=k?this.mant[j]=k-0:this.bad("BigDecimal(): ",a),l++}else{b=i;j=0;for(;0<b;b--,j++)j==f&&l++,this.mant[j]=a[l]-0,l++}0==this.mant[0]?(this.ind=this.iszero,0<this.exp&&(this.exp=0),e&&(this.mant=this.ZERO.mant,this.exp=0)):e&&(this.form=m.prototype.SCIENTIFIC,f=this.exp+this.mant.length-1,(f<this.MinExp||f>this.MaxExp)&&this.bad("BigDecimal(): ",a))}},H=function(){var a;if(1==H.arguments.length)a=H.arguments[0];else if(0==H.arguments.length)a=this.plainMC;else throw"abs(): "+H.arguments.length+
" arguments given; expected 0 or 1";return this.ind==this.isneg?this.negate(a):this.plus(a)},w=function(){var a;if(2==w.arguments.length)a=w.arguments[1];else if(1==w.arguments.length)a=this.plainMC;else throw"add(): "+w.arguments.length+" arguments given; expected 1 or 2";var b=w.arguments[0],c,d,e,i,f,g,j,l=0;d=l=0;var l=null,k=l=0,q=0,t=0,s=0,n=0;a.lostDigits&&this.checkdigits(b,a.digits);c=this;if(0==c.ind&&a.form!=m.prototype.PLAIN)return b.plus(a);if(0==b.ind&&a.form!=m.prototype.PLAIN)return c.plus(a);
d=a.digits;0<d&&(c.mant.length>d&&(c=this.clone(c).round(a)),b.mant.length>d&&(b=this.clone(b).round(a)));e=new h;i=c.mant;f=c.mant.length;g=b.mant;j=b.mant.length;if(c.exp==b.exp)e.exp=c.exp;else if(c.exp>b.exp){l=f+c.exp-b.exp;if(l>=j+d+1&&0<d)return e.mant=i,e.exp=c.exp,e.ind=c.ind,f<d&&(e.mant=this.extend(c.mant,d),e.exp-=d-f),e.finish(a,!1);e.exp=b.exp;l>d+1&&0<d&&(l=l-d-1,j-=l,e.exp+=l,l=d+1);l>f&&(f=l)}else{l=j+b.exp-c.exp;if(l>=f+d+1&&0<d)return e.mant=g,e.exp=b.exp,e.ind=b.ind,j<d&&(e.mant=
this.extend(b.mant,d),e.exp-=d-j),e.finish(a,!1);e.exp=c.exp;l>d+1&&0<d&&(l=l-d-1,f-=l,e.exp+=l,l=d+1);l>j&&(j=l)}e.ind=c.ind==this.iszero?this.ispos:c.ind;if((c.ind==this.isneg?1:0)==(b.ind==this.isneg?1:0))d=1;else{do{d=-1;do if(b.ind!=this.iszero)if(f<j||c.ind==this.iszero)l=i,i=g,g=l,l=f,f=j,j=l,e.ind=-e.ind;else if(!(f>j)){k=l=0;q=i.length-1;t=g.length-1;c:for(;;){if(l<=q)s=i[l];else{if(k>t){if(a.form!=m.prototype.PLAIN)return this.ZERO;break c}s=0}n=k<=t?g[k]:0;if(s!=n){s<n&&(l=i,i=g,g=l,l=
f,f=j,j=l,e.ind=-e.ind);break c}l++;k++}}while(0)}while(0)}e.mant=this.byteaddsub(i,f,g,j,d,!1);return e.finish(a,!1)},x=function(){var a;if(2==x.arguments.length)a=x.arguments[1];else if(1==x.arguments.length)a=this.plainMC;else throw"compareTo(): "+x.arguments.length+" arguments given; expected 1 or 2";var b=x.arguments[0],c=0,c=0;a.lostDigits&&this.checkdigits(b,a.digits);if(this.ind==b.ind&&this.exp==b.exp){c=this.mant.length;if(c<b.mant.length)return-this.ind;if(c>b.mant.length)return this.ind;
if(c<=a.digits||0==a.digits){a=c;c=0;for(;0<a;a--,c++){if(this.mant[c]<b.mant[c])return-this.ind;if(this.mant[c]>b.mant[c])return this.ind}return 0}}else{if(this.ind<b.ind)return-1;if(this.ind>b.ind)return 1}b=this.clone(b);b.ind=-b.ind;return this.add(b,a).ind},p=function(){var a,b=-1;if(2==p.arguments.length)a="number"==typeof p.arguments[1]?new m(0,m.prototype.PLAIN,!1,p.arguments[1]):p.arguments[1];else if(3==p.arguments.length){b=p.arguments[1];if(0>b)throw"divide(): Negative scale: "+b;a=new m(0,
m.prototype.PLAIN,!1,p.arguments[2])}else if(1==p.arguments.length)a=this.plainMC;else throw"divide(): "+p.arguments.length+" arguments given; expected between 1 and 3";return this.dodivide("D",p.arguments[0],a,b)},y=function(){var a;if(2==y.arguments.length)a=y.arguments[1];else if(1==y.arguments.length)a=this.plainMC;else throw"divideInteger(): "+y.arguments.length+" arguments given; expected 1 or 2";return this.dodivide("I",y.arguments[0],a,0)},z=function(){var a;if(2==z.arguments.length)a=z.arguments[1];
else if(1==z.arguments.length)a=this.plainMC;else throw"max(): "+z.arguments.length+" arguments given; expected 1 or 2";var b=z.arguments[0];return 0<=this.compareTo(b,a)?this.plus(a):b.plus(a)},A=function(){var a;if(2==A.arguments.length)a=A.arguments[1];else if(1==A.arguments.length)a=this.plainMC;else throw"min(): "+A.arguments.length+" arguments given; expected 1 or 2";var b=A.arguments[0];return 0>=this.compareTo(b,a)?this.plus(a):b.plus(a)},B=function(){var a;if(2==B.arguments.length)a=B.arguments[1];
else if(1==B.arguments.length)a=this.plainMC;else throw"multiply(): "+B.arguments.length+" arguments given; expected 1 or 2";var b=B.arguments[0],c,d,e,i=e=null,f,g=0,j,l=0,k=0;a.lostDigits&&this.checkdigits(b,a.digits);c=this;d=0;e=a.digits;0<e?(c.mant.length>e&&(c=this.clone(c).round(a)),b.mant.length>e&&(b=this.clone(b).round(a))):(0<c.exp&&(d+=c.exp),0<b.exp&&(d+=b.exp));c.mant.length<b.mant.length?(e=c.mant,i=b.mant):(e=b.mant,i=c.mant);f=e.length+i.length-1;g=9<e[0]*i[0]?f+1:f;j=new h;var g=
this.createArrayWithZeros(g),m=e.length,l=0;for(;0<m;m--,l++)k=e[l],0!=k&&(g=this.byteaddsub(g,g.length,i,f,k,!0)),f--;j.ind=c.ind*b.ind;j.exp=c.exp+b.exp-d;j.mant=0==d?g:this.extend(g,g.length+d);return j.finish(a,!1)},I=function(){var a;if(1==I.arguments.length)a=I.arguments[0];else if(0==I.arguments.length)a=this.plainMC;else throw"negate(): "+I.arguments.length+" arguments given; expected 0 or 1";var b;a.lostDigits&&this.checkdigits(null,a.digits);b=this.clone(this);b.ind=-b.ind;return b.finish(a,
!1)},J=function(){var a;if(1==J.arguments.length)a=J.arguments[0];else if(0==J.arguments.length)a=this.plainMC;else throw"plus(): "+J.arguments.length+" arguments given; expected 0 or 1";a.lostDigits&&this.checkdigits(null,a.digits);return a.form==m.prototype.PLAIN&&this.form==m.prototype.PLAIN&&(this.mant.length<=a.digits||0==a.digits)?this:this.clone(this).finish(a,!1)},C=function(){var a;if(2==C.arguments.length)a=C.arguments[1];else if(1==C.arguments.length)a=this.plainMC;else throw"pow(): "+
C.arguments.length+" arguments given; expected 1 or 2";var b=C.arguments[0],c,d,e,i=e=0,f,g=0;a.lostDigits&&this.checkdigits(b,a.digits);c=b.intcheck(this.MinArg,this.MaxArg);d=this;e=a.digits;if(0==e){if(b.ind==this.isneg)throw"pow(): Negative power: "+b.toString();e=0}else{if(b.mant.length+b.exp>e)throw"pow(): Too many digits: "+b.toString();d.mant.length>e&&(d=this.clone(d).round(a));i=b.mant.length+b.exp;e=e+i+1}e=new m(e,a.form,!1,a.roundingMode);i=this.ONE;if(0==c)return i;0>c&&(c=-c);f=!1;
g=1;a:for(;;g++){c<<=1;0>c&&(f=!0,i=i.multiply(d,e));if(31==g)break a;if(!f)continue a;i=i.multiply(i,e)}0>b.ind&&(i=this.ONE.divide(i,e));return i.finish(a,!0)},D=function(){var a;if(2==D.arguments.length)a=D.arguments[1];else if(1==D.arguments.length)a=this.plainMC;else throw"remainder(): "+D.arguments.length+" arguments given; expected 1 or 2";return this.dodivide("R",D.arguments[0],a,-1)},E=function(){var a;if(2==E.arguments.length)a=E.arguments[1];else if(1==E.arguments.length)a=this.plainMC;
else throw"subtract(): "+E.arguments.length+" arguments given; expected 1 or 2";var b=E.arguments[0];a.lostDigits&&this.checkdigits(b,a.digits);b=this.clone(b);b.ind=-b.ind;return this.add(b,a)},r=function(){var a,b,c,d;if(6==r.arguments.length)a=r.arguments[2],b=r.arguments[3],c=r.arguments[4],d=r.arguments[5];else if(2==r.arguments.length)b=a=-1,c=m.prototype.SCIENTIFIC,d=this.ROUND_HALF_UP;else throw"format(): "+r.arguments.length+" arguments given; expected 2 or 6";var e=r.arguments[0],i=r.arguments[1],
f,g=0,g=g=0,j=null,l=j=g=0;f=0;g=null;l=j=0;(-1>e||0==e)&&this.badarg("format",1,e);-1>i&&this.badarg("format",2,i);(-1>a||0==a)&&this.badarg("format",3,a);-1>b&&this.badarg("format",4,b);c!=m.prototype.SCIENTIFIC&&c!=m.prototype.ENGINEERING&&(-1==c?c=m.prototype.SCIENTIFIC:this.badarg("format",5,c));if(d!=this.ROUND_HALF_UP)try{-1==d?d=this.ROUND_HALF_UP:new m(9,m.prototype.SCIENTIFIC,!1,d)}catch(h){this.badarg("format",6,d)}f=this.clone(this);-1==b?f.form=m.prototype.PLAIN:f.ind==this.iszero?f.form=
m.prototype.PLAIN:(g=f.exp+f.mant.length,f.form=g>b?c:-5>g?c:m.prototype.PLAIN);if(0<=i)a:for(;;){f.form==m.prototype.PLAIN?g=-f.exp:f.form==m.prototype.SCIENTIFIC?g=f.mant.length-1:(g=(f.exp+f.mant.length-1)%3,0>g&&(g=3+g),g++,g=g>=f.mant.length?0:f.mant.length-g);if(g==i)break a;if(g<i){j=this.extend(f.mant,f.mant.length+i-g);f.mant=j;f.exp-=i-g;if(f.exp<this.MinExp)throw"format(): Exponent Overflow: "+f.exp;break a}g-=i;if(g>f.mant.length){f.mant=this.ZERO.mant;f.ind=this.iszero;f.exp=0;continue a}j=
f.mant.length-g;l=f.exp;f.round(j,d);if(f.exp-l==g)break a}b=f.layout();if(0<e){c=b.length;f=0;a:for(;0<c;c--,f++){if("."==b[f])break a;if("E"==b[f])break a}f>e&&this.badarg("format",1,e);if(f<e){g=Array(b.length+e-f);e-=f;j=0;for(;0<e;e--,j++)g[j]=" ";this.arraycopy(b,0,g,j,b.length);b=g}}if(0<a){e=b.length-1;f=b.length-1;a:for(;0<e;e--,f--)if("E"==b[f])break a;if(0==f){g=Array(b.length+a+2);this.arraycopy(b,0,g,0,b.length);a+=2;j=b.length;for(;0<a;a--,j++)g[j]=" ";b=g}else if(l=b.length-f-2,l>a&&
this.badarg("format",3,a),l<a){g=Array(b.length+a-l);this.arraycopy(b,0,g,0,f+2);a-=l;j=f+2;for(;0<a;a--,j++)g[j]="0";this.arraycopy(b,f+2,g,j,l);b=g}}return b.join("")},F=function(){var a;if(2==F.arguments.length)a=F.arguments[1];else if(1==F.arguments.length)a=this.ROUND_UNNECESSARY;else throw"setScale(): "+F.arguments.length+" given; expected 1 or 2";var b=F.arguments[0],c,d;c=c=0;c=this.scale();if(c==b&&this.form==m.prototype.PLAIN)return this;d=this.clone(this);if(c<=b)c=0==c?d.exp+b:b-c,d.mant=
this.extend(d.mant,d.mant.length+c),d.exp=-b;else{if(0>b)throw"setScale(): Negative scale: "+b;c=d.mant.length-(c-b);d=d.round(c,a);d.exp!=-b&&(d.mant=this.extend(d.mant,d.mant.length+1),d.exp-=1)}d.form=m.prototype.PLAIN;return d};v=function(){var a,b=0,c=0;a=Array(190);b=0;a:for(;189>=b;b++){c=b-90;if(0<=c){a[b]=c%10;h.prototype.bytecar[b]=G(c,10);continue a}c+=100;a[b]=c%10;h.prototype.bytecar[b]=G(c,10)-10}return a};var u=function(){var a,b;if(2==u.arguments.length)a=u.arguments[0],b=u.arguments[1];
else if(1==u.arguments.length)b=u.arguments[0],a=b.digits,b=b.roundingMode;else throw"round(): "+u.arguments.length+" arguments given; expected 1 or 2";var c,d,e=!1,i=0,f;c=null;c=this.mant.length-a;if(0>=c)return this;this.exp+=c;c=this.ind;d=this.mant;0<a?(this.mant=Array(a),this.arraycopy(d,0,this.mant,0,a),e=!0,i=d[a]):(this.mant=this.ZERO.mant,this.ind=this.iszero,e=!1,i=0==a?d[0]:0);f=0;if(b==this.ROUND_HALF_UP)5<=i&&(f=c);else if(b==this.ROUND_UNNECESSARY){if(!this.allzero(d,a))throw"round(): Rounding necessary";
}else if(b==this.ROUND_HALF_DOWN)5<i?f=c:5==i&&(this.allzero(d,a+1)||(f=c));else if(b==this.ROUND_HALF_EVEN)5<i?f=c:5==i&&(this.allzero(d,a+1)?1==this.mant[this.mant.length-1]%2&&(f=c):f=c);else if(b!=this.ROUND_DOWN)if(b==this.ROUND_UP)this.allzero(d,a)||(f=c);else if(b==this.ROUND_CEILING)0<c&&(this.allzero(d,a)||(f=c));else if(b==this.ROUND_FLOOR)0>c&&(this.allzero(d,a)||(f=c));else throw"round(): Bad round value: "+b;0!=f&&(this.ind==this.iszero?(this.mant=this.ONE.mant,this.ind=f):(this.ind==
this.isneg&&(f=-f),c=this.byteaddsub(this.mant,this.mant.length,this.ONE.mant,1,f,e),c.length>this.mant.length?(this.exp++,this.arraycopy(c,0,this.mant,0,this.mant.length)):this.mant=c));if(this.exp>this.MaxExp)throw"round(): Exponent Overflow: "+this.exp;return this};h.prototype.div=G;h.prototype.arraycopy=function(a,b,c,d,e){var i;if(d>b)for(i=e-1;0<=i;--i)c[i+d]=a[i+b];else for(i=0;i<e;++i)c[i+d]=a[i+b]};h.prototype.createArrayWithZeros=K;h.prototype.abs=H;h.prototype.add=w;h.prototype.compareTo=
x;h.prototype.divide=p;h.prototype.divideInteger=y;h.prototype.max=z;h.prototype.min=A;h.prototype.multiply=B;h.prototype.negate=I;h.prototype.plus=J;h.prototype.pow=C;h.prototype.remainder=D;h.prototype.subtract=E;h.prototype.equals=function(a){var b=0,c=null,d=null;if(null==a||!(a instanceof h)||this.ind!=a.ind)return!1;if(this.mant.length==a.mant.length&&this.exp==a.exp&&this.form==a.form){c=this.mant.length;b=0;for(;0<c;c--,b++)if(this.mant[b]!=a.mant[b])return!1}else{c=this.layout();d=a.layout();
if(c.length!=d.length)return!1;a=c.length;b=0;for(;0<a;a--,b++)if(c[b]!=d[b])return!1}return!0};h.prototype.format=r;h.prototype.intValueExact=function(){var a,b=0,c,d=0;a=0;if(this.ind==this.iszero)return 0;a=this.mant.length-1;if(0>this.exp){a+=this.exp;if(!this.allzero(this.mant,a+1))throw"intValueExact(): Decimal part non-zero: "+this.toString();if(0>a)return 0;b=0}else{if(9<this.exp+a)throw"intValueExact(): Conversion overflow: "+this.toString();b=this.exp}c=0;var e=a+b,d=0;for(;d<=e;d++)c*=
10,d<=a&&(c+=this.mant[d]);if(9==a+b&&(a=G(c,1E9),a!=this.mant[0])){if(-2147483648==c&&this.ind==this.isneg&&2==this.mant[0])return c;throw"intValueExact(): Conversion overflow: "+this.toString();}return this.ind==this.ispos?c:-c};h.prototype.movePointLeft=function(a){var b;b=this.clone(this);b.exp-=a;return b.finish(this.plainMC,!1)};h.prototype.movePointRight=function(a){var b;b=this.clone(this);b.exp+=a;return b.finish(this.plainMC,!1)};h.prototype.scale=function(){return 0<=this.exp?0:-this.exp};
h.prototype.setScale=F;h.prototype.signum=function(){return this.ind};h.prototype.toString=function(){return this.layout().join("")};h.prototype.layout=function(){var a,b=0,b=null,c=0,d=0;a=0;var d=null,e,b=0;a=Array(this.mant.length);c=this.mant.length;b=0;for(;0<c;c--,b++)a[b]=this.mant[b]+"";if(this.form!=m.prototype.PLAIN){b="";this.ind==this.isneg&&(b+="-");c=this.exp+a.length-1;if(this.form==m.prototype.SCIENTIFIC)b+=a[0],1<a.length&&(b+="."),b+=a.slice(1).join("");else if(d=c%3,0>d&&(d=3+d),
c-=d,d++,d>=a.length){b+=a.join("");for(a=d-a.length;0<a;a--)b+="0"}else b+=a.slice(0,d).join(""),b=b+"."+a.slice(d).join("");0!=c&&(0>c?(a="-",c=-c):a="+",b+="E",b+=a,b+=c);return b.split("")}if(0==this.exp){if(0<=this.ind)return a;d=Array(a.length+1);d[0]="-";this.arraycopy(a,0,d,1,a.length);return d}c=this.ind==this.isneg?1:0;e=this.exp+a.length;if(1>e){b=c+2-this.exp;d=Array(b);0!=c&&(d[0]="-");d[c]="0";d[c+1]=".";var i=-e,b=c+2;for(;0<i;i--,b++)d[b]="0";this.arraycopy(a,0,d,c+2-e,a.length);return d}if(e>
a.length){d=Array(c+e);0!=c&&(d[0]="-");this.arraycopy(a,0,d,c,a.length);e-=a.length;b=c+a.length;for(;0<e;e--,b++)d[b]="0";return d}b=c+1+a.length;d=Array(b);0!=c&&(d[0]="-");this.arraycopy(a,0,d,c,e);d[c+e]=".";this.arraycopy(a,e,d,c+e+1,a.length-e);return d};h.prototype.intcheck=function(a,b){var c;c=this.intValueExact();if(c<a||c>b)throw"intcheck(): Conversion overflow: "+c;return c};h.prototype.dodivide=function(a,b,c,d){var e,i,f,g,j,l,k,q,t,s=0,n=0,p=0;i=i=n=n=n=0;e=null;e=e=0;e=null;c.lostDigits&&
this.checkdigits(b,c.digits);e=this;if(0==b.ind)throw"dodivide(): Divide by 0";if(0==e.ind)return c.form!=m.prototype.PLAIN?this.ZERO:-1==d?e:e.setScale(d);i=c.digits;0<i?(e.mant.length>i&&(e=this.clone(e).round(c)),b.mant.length>i&&(b=this.clone(b).round(c))):(-1==d&&(d=e.scale()),i=e.mant.length,d!=-e.exp&&(i=i+d+e.exp),i=i-(b.mant.length-1)-b.exp,i<e.mant.length&&(i=e.mant.length),i<b.mant.length&&(i=b.mant.length));f=e.exp-b.exp+e.mant.length-b.mant.length;if(0>f&&"D"!=a)return"I"==a?this.ZERO:
this.clone(e).finish(c,!1);g=new h;g.ind=e.ind*b.ind;g.exp=f;g.mant=this.createArrayWithZeros(i+1);j=i+i+1;f=this.extend(e.mant,j);l=j;k=b.mant;q=j;t=10*k[0]+1;1<k.length&&(t+=k[1]);j=0;a:for(;;){s=0;b:for(;;){if(l<q)break b;if(l==q){c:do{var r=l,n=0;for(;0<r;r--,n++){p=n<k.length?k[n]:0;if(f[n]<p)break b;if(f[n]>p)break c}s++;g.mant[j]=s;j++;f[0]=0;break a}while(0);n=f[0]}else n=10*f[0],1<l&&(n+=f[1]);n=G(10*n,t);0==n&&(n=1);s+=n;f=this.byteaddsub(f,l,k,q,-n,!0);if(0!=f[0])continue b;p=l-2;n=0;c:for(;n<=
p;n++){if(0!=f[n])break c;l--}if(0==n)continue b;this.arraycopy(f,n,f,0,l)}if(0!=j||0!=s){g.mant[j]=s;j++;if(j==i+1)break a;if(0==f[0])break a}if(0<=d&&-g.exp>d)break a;if("D"!=a&&0>=g.exp)break a;g.exp-=1;q--}0==j&&(j=1);if("I"==a||"R"==a){if(j+g.exp>i)throw"dodivide(): Integer overflow";if("R"==a){do{if(0==g.mant[0])return this.clone(e).finish(c,!1);if(0==f[0])return this.ZERO;g.ind=e.ind;i=i+i+1-e.mant.length;g.exp=g.exp-i+e.exp;i=l;n=i-1;b:for(;1<=n&&g.exp<e.exp&&g.exp<b.exp;n--){if(0!=f[n])break b;
i--;g.exp+=1}i<f.length&&(e=Array(i),this.arraycopy(f,0,e,0,i),f=e);g.mant=f;return g.finish(c,!1)}while(0)}}else 0!=f[0]&&(e=g.mant[j-1],0==e%5&&(g.mant[j-1]=e+1));if(0<=d)return j!=g.mant.length&&(g.exp-=g.mant.length-j),e=g.mant.length-(-g.exp-d),g.round(e,c.roundingMode),g.exp!=-d&&(g.mant=this.extend(g.mant,g.mant.length+1),g.exp-=1),g.finish(c,!0);if(j==g.mant.length)g.round(c);else{if(0==g.mant[0])return this.ZERO;e=Array(j);this.arraycopy(g.mant,0,e,0,j);g.mant=e}return g.finish(c,!0)};h.prototype.bad=
function(a,b){throw a+"Not a number: "+b;};h.prototype.badarg=function(a,b,c){throw"Bad argument "+b+" to "+a+": "+c;};h.prototype.extend=function(a,b){var c;if(a.length==b)return a;c=K(b);this.arraycopy(a,0,c,0,a.length);return c};h.prototype.byteaddsub=function(a,b,c,d,e,i){var f,g,j,h,k,m,p=0;f=m=0;f=a.length;g=c.length;b-=1;h=j=d-1;h<b&&(h=b);d=null;i&&h+1==f&&(d=a);null==d&&(d=this.createArrayWithZeros(h+1));k=!1;1==e?k=!0:-1==e&&(k=!0);m=0;p=h;a:for(;0<=p;p--){0<=b&&(b<f&&(m+=a[b]),b--);0<=
j&&(j<g&&(m=k?0<e?m+c[j]:m-c[j]:m+c[j]*e),j--);if(10>m&&0<=m){do{d[p]=m;m=0;continue a}while(0)}m+=90;d[p]=this.bytedig[m];m=this.bytecar[m]}if(0==m)return d;c=null;i&&h+2==a.length&&(c=a);null==c&&(c=Array(h+2));c[0]=m;a=h+1;f=0;for(;0<a;a--,f++)c[f+1]=d[f];return c};h.prototype.diginit=v;h.prototype.clone=function(a){var b;b=new h;b.ind=a.ind;b.exp=a.exp;b.form=a.form;b.mant=a.mant;return b};h.prototype.checkdigits=function(a,b){if(0!=b){if(this.mant.length>b&&!this.allzero(this.mant,b))throw"Too many digits: "+
this.toString();if(null!=a&&a.mant.length>b&&!this.allzero(a.mant,b))throw"Too many digits: "+a.toString();}};h.prototype.round=u;h.prototype.allzero=function(a,b){var c=0;0>b&&(b=0);var d=a.length-1,c=b;for(;c<=d;c++)if(0!=a[c])return!1;return!0};h.prototype.finish=function(a,b){var c=0,d=0,e=null,c=d=0;0!=a.digits&&this.mant.length>a.digits&&this.round(a);if(b&&a.form!=m.prototype.PLAIN){c=this.mant.length;d=c-1;a:for(;1<=d;d--){if(0!=this.mant[d])break a;c--;this.exp++}c<this.mant.length&&(e=Array(c),
this.arraycopy(this.mant,0,e,0,c),this.mant=e)}this.form=m.prototype.PLAIN;c=this.mant.length;d=0;for(;0<c;c--,d++)if(0!=this.mant[d]){0<d&&(e=Array(this.mant.length-d),this.arraycopy(this.mant,d,e,0,this.mant.length-d),this.mant=e);d=this.exp+this.mant.length;if(0<d){if(d>a.digits&&0!=a.digits&&(this.form=a.form),d-1<=this.MaxExp)return this}else-5>d&&(this.form=a.form);d--;if(d<this.MinExp||d>this.MaxExp){b:do{if(this.form==m.prototype.ENGINEERING&&(c=d%3,0>c&&(c=3+c),d-=c,d>=this.MinExp&&d<=this.MaxExp))break b;
throw"finish(): Exponent Overflow: "+d;}while(0)}return this}this.ind=this.iszero;if(a.form!=m.prototype.PLAIN)this.exp=0;else if(0<this.exp)this.exp=0;else if(this.exp<this.MinExp)throw"finish(): Exponent Overflow: "+this.exp;this.mant=this.ZERO.mant;return this};h.prototype.isGreaterThan=function(a){return 0<this.compareTo(a)};h.prototype.isLessThan=function(a){return 0>this.compareTo(a)};h.prototype.isGreaterThanOrEqualTo=function(a){return 0<=this.compareTo(a)};h.prototype.isLessThanOrEqualTo=
function(a){return 0>=this.compareTo(a)};h.prototype.isPositive=function(){return 0<this.compareTo(h.prototype.ZERO)};h.prototype.isNegative=function(){return 0>this.compareTo(h.prototype.ZERO)};h.prototype.isZero=function(){return this.equals(h.prototype.ZERO)};h.ROUND_CEILING=h.prototype.ROUND_CEILING=m.prototype.ROUND_CEILING;h.ROUND_DOWN=h.prototype.ROUND_DOWN=m.prototype.ROUND_DOWN;h.ROUND_FLOOR=h.prototype.ROUND_FLOOR=m.prototype.ROUND_FLOOR;h.ROUND_HALF_DOWN=h.prototype.ROUND_HALF_DOWN=m.prototype.ROUND_HALF_DOWN;
h.ROUND_HALF_EVEN=h.prototype.ROUND_HALF_EVEN=m.prototype.ROUND_HALF_EVEN;h.ROUND_HALF_UP=h.prototype.ROUND_HALF_UP=m.prototype.ROUND_HALF_UP;h.ROUND_UNNECESSARY=h.prototype.ROUND_UNNECESSARY=m.prototype.ROUND_UNNECESSARY;h.ROUND_UP=h.prototype.ROUND_UP=m.prototype.ROUND_UP;h.prototype.ispos=1;h.prototype.iszero=0;h.prototype.isneg=-1;h.prototype.MinExp=-999999999;h.prototype.MaxExp=999999999;h.prototype.MinArg=-999999999;h.prototype.MaxArg=999999999;h.prototype.plainMC=new m(0,m.prototype.PLAIN);
h.prototype.bytecar=Array(190);h.prototype.bytedig=v();h.ZERO=h.prototype.ZERO=new h("0");h.ONE=h.prototype.ONE=new h("1");h.TEN=h.prototype.TEN=new h("10");v=h;"function"===typeof define&&null!=define.amd?define({BigDecimal:v,MathContext:m}):"object"===typeof this&&(this.BigDecimal=v,this.MathContext=m)}).call(this);
@@ -0,0 +1,30 @@
Copyright (c) 2012 Daniel Trebbien and other contributors
Portions Copyright (c) 2003 STZ-IDA and PTV AG, Karlsruhe, Germany
Portions Copyright (c) 1995-2001 International Business Machines Corporation and others
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, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
ICU4J license - ICU4J 1.3.1 and later
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1995-2001 International Business Machines Corporation and others
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, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, provided that the above copyright notice(s) and this permission notice appear in all copies of the Software and that both the above copyright notice(s) and this permission notice appear in supporting documentation.
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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder.
--------------------------------------------------------------------------------
All trademarks and registered trademarks mentioned herein are the property of their respective owners.
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,306 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<meta name="Author" content="M Mclaughlin">
<title>Testing BigNumber against Number</title>
<style>
body, ul, form, h1, div {margin: 0; padding: 0;}
body, pre {font-family: Calibri, Arial, Sans-Serif;}
form {width: 48em; margin: 1.6em auto; border: 2px solid rgb(200, 200, 200);}
h1 {text-align: center; font-size: 1.2em; padding: 0.6em 0;
background-color: rgb(200, 200, 200)}
ul {list-style-type: none; color: rgb(85, 85, 85); padding: 1em 1em 0 2em;}
.input, ul {background-color: rgb(245, 245, 245);}
.input, .output {padding: 0 1em 1em 2em;}
.output, .methods {background-color: rgb(225, 225, 225);}
.methods {padding-bottom: 1em;}
.output {padding-bottom: 2em;}
.size {width: 80%;}
label {width: 10em; color: rgb(0, 0, 0); margin-left: 0.6em;}
label {display: inline-block;}
span, .exLabel, pre {font-size: 0.9em;}
pre {display: inline;}
.exLabel {display: inline; margin-left: 0; width: 2em;}
.arg, .result, .dp {width: 5em; margin-right: 0.8em; margin-top: 1.2em;}
.dp {width: auto;}
.exInput {margin-left: 1em;}
.code {width: 60em; margin: 0 auto; font-family: Courier New, Courier,
monospace; font-size: 0.8em;}
</style>
<script src='../../bignumber.js'></script>
</head>
<body>
<form>
<h1>Testing BigNumber against Number</h1>
<ul class='methods'>
<li>
<input type='radio' id='toExponential' name=1/>
<label for='toExponential'>toExponential</label>
<span>[ decimal places ]</span>
</li>
<li>
<input type='radio' id='toFixed' name=1/>
<label for='toFixed'>toFixed</label>
<span>[ decimal places ]</span>
</li>
<li>
<input type='radio' id='toPrecision' name=1/>
<label for='toPrecision'>toPrecision</label>
<span>[ significant digits ]</span>
</li>
<li>
<input type='radio' id='round' name=1/>
<label for='round'>round</label>
<span>[ decimal places [ , rounding mode ] ]</span>
</li>
<li>
<input type='radio' id='toFraction' name=1/>
<label for='toFraction'>toFraction</label>
<span>[ maximum denominator ]</span>
</li>
<li>
<input type='radio' id='sqrt' name=1/>
<label for='sqrt'>sqrt</label>
</li>
</ul>
<ul id='roundings'>
<li>
<input type='radio' id=0 name=2/>
<label for=0 >UP</label>
<span>Rounds away from zero</span>
</li>
<li>
<input type='radio' id=1 name=2/>
<label for=1 >DOWN</label>
<span>Rounds towards zero</span>
</li>
<li>
<input type='radio' id=2 name=2/>
<label for=2 >CEIL</label>
<span>Rounds towards +Infinity</span>
</li>
<li>
<input type='radio' id=3 name=2/>
<label for=3 >FLOOR</label>
<span>Rounds towards -Infinity</span>
</li>
<li>
<input type='radio' id=4 name=2/>
<label for=4 >HALF_UP</label>
<span>Rounds towards nearest neighbour. If equidistant, rounds up</span>
</li>
<li>
<input type='radio' id=5 name=2/>
<label for=5 >HALF_DOWN</label>
<span>Rounds towards nearest neighbour. If equidistant, rounds down</span>
</li>
<li>
<input type='radio' id=6 name=2/>
<label for=6 >HALF_EVEN</label>
<span>Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour</span>
</li>
<li>
<input type='radio' id=7 name=2/>
<label for=7 >HALF_CEIL</label>
<span>Rounds towards nearest neighbour. If equidistant, rounds towards +Infinity</span>
</li>
<li>
<input type='radio' id=8 name=2/>
<label for=8 >HALF_FLOOR</label>
<span>Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity</span>
</li>
</ul>
<div class='input'>
<div class='dpDiv'>
<label class='dp' id='dpLabel' for='dp'>Decimal places:</label>
<input type='text' id='dp' name='dp' size=20 />
<pre> BigNumber ERRORS:</pre>
<input class='exInput' type='radio' id='exTrue' name=3/>
<label class='exLabel' for='exTrue'>true</label>
<input class='exInput' type='radio' id='exFalse' name=3/>
<label class='exLabel' for='exFalse'>false</label>
</div>
<label class='arg' for='input'>Input:</label>
<input class='size' type='text' id='input' name='input' />
</div>
<div class='output'>
<label class='result' for='bignumber'>BigNumber:</label>
<input class='size' type='text' id='bignumber' name='bignumber' readonly />
<div id='number'>
<label class='result' for='num'>Number:</label>
<input class='size' type='text' id='num' name='num' readonly />
</div>
</div>
</form>
<div class= 'code' id='code'></div>
<script>
(function () {
var i, toFraction, lastFocus,
d = document,
$ = function (id) {return d.getElementById(id)},
$input = $('input'),
$dp = $('dp'),
$dpLabel = $('dpLabel'),
$num = $('num'),
$bignumber = $('bignumber'),
$number = $('number'),
$roundings = $('roundings'),
$exceptionsTrue = $('exTrue'),
$exceptionsFalse = $('exFalse'),
$code = $('code'),
$inputs = d.getElementsByTagName('input');
function round() {
var i, rb, method, mode, includeNumber, numVal, bignumberVal, isSqrt,
dp = ($dp.value = $dp.value.replace(/\s+/g, '')),
dpEmpty = dp === '',
input = ($input.value = $input.value.replace(/\s+/g, '')),
exceptions = $exceptionsTrue.checked,
code = 'BigNumber.config({ERRORS : ' + exceptions;
BigNumber.config({ERRORS : exceptions});
if (input) {
for (i = 0; i < 15; i++) {
rb = $inputs[i];
if (rb.checked) {
if (i < 6) method = rb.id;
else mode = rb.id;
}
}
$num.value = $bignumber.value = $code.innerHTML = '';
isSqrt = method == 'sqrt';
if (includeNumber = method != 'toFraction' && method != 'round') {
try {
numVal = isSqrt
? Math.sqrt(input)
: dpEmpty
? Number(input)[method]()
: Number(input)[method](dp);
} catch(e) {
numVal = e;
}
if (isSqrt && !dpEmpty) {
try {
BigNumber.config(dp);
} catch(e) {
$bignumber.value = e;
return;
}
code += ', DECIMAL_PLACES : ' + dp;
}
BigNumber.config({ROUNDING_MODE : mode});
code += ', ROUNDING_MODE : ' + mode;
}
code += "})<br>BigNumber('" + input + "')." + method + "(";
if (!isSqrt) {
if (method == 'round') {
if (dpEmpty) {
dp = undefined;
dpEmpty = false;
}
code += "'" + dp + "', " + mode;
} else if (!dpEmpty) code += "'" + dp + "'";
}
code += ')<br><br>';
if (includeNumber) {
if (isSqrt) {
code += "Math.sqrt('" + input + "')";
} else {
code += "Number('" + input + "')." + method + "(";
if (!dpEmpty) code += "'" + dp + "'";
code += ")";
}
}
try {
bignumberVal = dpEmpty
? new BigNumber(input)[method]()
: new BigNumber(input)[method](dp, mode);
} catch(e) {
bignumberVal = e;
}
setTimeout(function () {
$bignumber.value = bignumberVal;
if (includeNumber) $num.value = numVal;
$code.innerHTML = code;
}, 100);
if (window.console && console.log) {
input = new BigNumber(input);
console.log('\nc: ' + input.c +
'\ne: ' + input.e +
'\ns: ' + input.s);
}
}
lastFocus.focus();
}
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : false,
EXPONENTIAL_AT : 1E9,
RANGE : 1E9
});
$input.value = $dp.value = $num.value = $bignumber.value = '';
setTimeout(function () {$input.focus()}, 0);
for (i = 0; i < 15; i++) {
$inputs[i].checked = false;
$inputs[i].onclick = function () {
if (this.id >= 0) {
round();
} else {
if (this.id == 'toFraction') {
toFraction = true;
$dpLabel.innerHTML = 'Maximum denominator:';
$number.style.display = $roundings.style.display = 'none';
} else {
$dpLabel.innerHTML = this.id == 'toPrecision'
? 'Significant digits:'
: 'Decimal places:';
$number.style.display = this.id == 'round'
? 'none'
: 'block';
$roundings.style.display = 'block';
if (toFraction) toFraction = false;
}
$dp.value = $bignumber.value = $num.value = $code.innerHTML = '';
lastFocus.focus();
}
};
}
$exceptionsTrue.onclick = $exceptionsFalse.onclick = round;
$input.onfocus = $dp.onfocus = function () {
lastFocus = this;
};
$inputs[1].checked = $inputs[10].checked = $exceptionsTrue.checked = true;
document.onkeypress = function (e) {
if ((e || window.event).keyCode == 13) {
round();
return false;
} else $num.value = $bignumber.value = '';
};
})();
</script>
</body>
</html>
@@ -0,0 +1,477 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>BigNumber Errors</title>
<script src='../../bignumber.js'></script>
</head>
<body>
<script>
var n;
document.body.innerHTML = 'BigNumber Errors written to console.';
try {
n = new BigNumber(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
BigNumber.config({ DECIMAL_PLACES : 10.3});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ DECIMAL_PLACES : -1});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ ROUNDING_MODE : 4.3});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ ROUNDING_MODE : 10});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ EXPONENTIAL_AT : 10.3});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ EXPONENTIAL_AT : 1e99});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ RANGE : 1.999});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ RANGE : 1e99});
} catch (e) {
console.error(e + '')
} try {
BigNumber.config({ ERRORS : 'ertg'});
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).pow(10.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow(1e99);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).round(300.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).round(1e99);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).round(null, 3.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).round(null, 9);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).toE(300.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).toE(1e99);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).toF(300.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).toF(1e99);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).toFr(300.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).toFr(-1);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).toP(300.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).toP(0);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).toS(3.3);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).toS(1);
} catch (e) {
console.error(e + '')
}
/*
* cmp, div, eq, gt, gte, lt, lte, minus, mod, plus, pow, times.
*/
try {
n = new BigNumber(2).cmp(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).cmp(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).cmp(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).cmp(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).cmp('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).cmp(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).div(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).div(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).div(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).div(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).div('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).div(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).eq(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).eq(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).eq(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).eq(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).eq('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).eq(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).gt(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gt(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gt(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gt(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gt('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gt(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).gte(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gte(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gte(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gte(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gte('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).gte(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).lt(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lt(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lt(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lt(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lt('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lt(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).lte(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lte(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lte(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lte(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lte('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).lte(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).minus(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).minus(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).minus(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).minus(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).minus('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).minus(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).mod(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).mod(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).mod(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).mod(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).mod('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).mod(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).plus(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).plus(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).plus(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).plus(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).plus('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).plus(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).pow(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).pow(8475698473265965);
} catch (e) {
console.error(e + '')
}
try {
n = new BigNumber(2).times(45324542.452466456546456);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).times(333, 2);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).times(123, 5.6);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).times(123, 37);
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).times('hello');
} catch (e) {
console.error(e + '')
} try {
n = new BigNumber(2).times(8475698473265965);
} catch (e) {
console.error(e + '')
}
</script>
</body>
</html>
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Testing bignumber.js</title>
<style> body {font-family: monospace; font-size: 12px; line-height: 14px;}</style>
<script src='../../bignumber.js'></script>
</head>
<body>
<script>
var arr,
passed = 0,
total = 0,
i = 0,
start = +new Date(),
methods = [
'abs',
'base-in',
'base-out',
'ceil',
'cmp',
'config',
'div',
'floor',
'minus',
'mod',
'neg',
'others',
'plus',
'pow',
'round',
'sqrt',
'times',
'toExponential',
'toFixed',
'toFraction',
'toPrecision',
'toString'
];
function load() {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script");
script.src = '../' + methods[i] + '.js';
if (!methods[i++]) {
document.body.innerHTML += '<br>IN TOTAL: ' + passed + ' of ' + total +
' tests passed in ' + ( (+new Date() - start) / 1000 ) + ' secs.<br>';
document.body.scrollIntoView(false);
return;
}
script.onload = script.onreadystatechange = function () {
if (!script.readyState || /loaded|complete/.test(script.readyState)) {
if (!count) {
document.body.innerHTML +=
'<br><span style="color: red">TEST SCRIPT FAILED - see error console.</span>';
} else {
passed += count[0];
total += count[1];
}
head.removeChild(script);
count = script = null;
document.body.innerHTML += '<br>';
document.body.scrollIntoView(false);
setTimeout(load, 0);
}
};
head.appendChild(script);
}
document.body.innerHTML += 'BIGNUMBER TESTING<br>';
load();
</script>
</body>
</html>
@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Testing bignumber.js</title>
<style> body {font-family: monospace; font-size: 12px; line-height: 14px;}</style>
<script src='../../bignumber.js'></script>
</head>
<body>
<script src='../quick-test.js'></script>
</body>
</html>
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Testing bignumber.js</title>
<style> body {font-family: monospace; font-size: 12px; line-height: 14px;}</style>
<script src='../../bignumber.js'></script>
</head>
<body>
<script src='../abs.js'></script>
<!-- <script src='../base-in.js'></script> -->
<!-- <script src='../base-out.js'></script> -->
<!-- <script src='../ceil.js'></script> -->
<!-- <script src='../config.js'></script> -->
<!-- <script src='../cmp.js'></script> -->
<!-- <script src='../div.js'></script> -->
<!-- <script src='../floor.js'></script> -->
<!-- <script src='../minus.js'></script> -->
<!-- <script src='../mod.js'></script> -->
<!-- <script src='../neg.js'></script> -->
<!-- <script src='../others.js'></script> -->
<!-- <script src='../plus.js'></script> -->
<!-- <script src='../pow.js'></script> -->
<!-- <script src='../round.js'></script> -->
<!-- <script src='../sqrt.js'></script> -->
<!-- <script src='../times.js'></script> -->
<!-- <script src='../toExponential.js'></script> -->
<!-- <script src='../toFixed.js'></script> -->
<!-- <script src='../toFraction.js'></script> -->
<!-- <script src='../toPrecision.js'></script> -->
<!-- <script src='../toString.js'></script> -->
</body>
</html>
+208
View File
@@ -0,0 +1,208 @@
var count = (function ceil(BigNumber) {
var start = +new Date(),
log,
error,
undefined,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function T(expected, value) {
assert(String(expected), new BigNumber(String(value)).ceil().toString());
}
log('\n Testing ceil...');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : 1E9
});
T('-2075364', '-2075364.364286541923');
T('60593539780450631', '60593539780450631');
T('65937898671515', '65937898671515');
T('-39719494751819198566798', '-39719494751819198566798.578');
T('92627382695288166557', '92627382695288166556.8683774524284866028260448205069');
T('-881574', '-881574');
T('-3633239209', '-3633239209.654526163275621746013315304191073405508491056');
T('-23970335459820625362', '-23970335459820625362');
T('131869457416154038', '131869457416154038');
T('-2685', '-2685');
T('-4542227860', '-4542227860.9511298545226');
T('2416872282', '2416872281.963955669484225137349193306323379254936827');
T('-757684868752087594264588207655', '-757684868752087594264588207655.27838048392835556');
T('-438798503526', '-438798503526.2317623894721299587561697');
T('801625782231888715214665', '801625782231888715214665');
T('-91881984778675238', '-91881984778675238');
T('327765350218284325239839632047', '327765350218284325239839632046.91682741746683081459605386');
T('-7469045007691432294', '-7469045007691432294.362757245');
T('8365540212937142194319515218790', '8365540212937142194319515218789.4106658678537421977827');
T('-14108', '-14108.495051214515');
T('49104502', '49104501.10055989379655329194309526150310568683504206945625');
T('131370407', '131370406.330005158136313262837556068534122953');
T('3017', '3017');
T('-689', '-689.6944252229740521128820354989299283');
T('73441822179', '73441822178.572653');
T('-2329', '-2329.42655772223486531483602927572548264457');
T('-834103872107533086', '-834103872107533086');
T('-1501493189970435', '-1501493189970435.74866616700317');
T('70592', '70591.2244675522123484658978887');
T('4446128540401735118', '4446128540401735117.435836700611264749985822486641350492901');
T('-597273', '-597273');
T('729117', '729117');
T('504', '504');
T('4803729546823170064608098091', '4803729546823170064608098091');
T('24147026285420507467578', '24147026285420507467578');
T('-6581532150677269472829', '-6581532150677269472829.38194951340848938896000325718062365494');
T('-131279182164804751', '-131279182164804751.430589952021038264');
T('2949426983040960', '2949426983040959.8911208825380208568451907');
T('25167', '25166.125888418871654557352055849116604612621573251770362');
T('4560569286496', '4560569286495.98300685103599898554605198');
T('14', '13.763105480576616251068323541559825687');
T('176037174185746614410406167888', '176037174185746614410406167887.42317518');
T('9050999219307', '9050999219306.7846946346757664893036971777');
T('39900924', '39900924');
T('115911043168452445', '115911043168452445');
T('20962819101135667464733349384', '20962819101135667464733349383.8959025798517496777183');
T('4125789711001606948192', '4125789711001606948191.4707575965791242737346836');
T('-6935501', '-6935501.294727166142750626019282');
T('-1', '-1.518418076611593764852321765899');
T('-35416', '-35416');
T('6912783515683955988122411164549', '6912783515683955988122411164548.393');
T('658', '657.0353902852');
T('1', '0.0009');
T('1', '0.00000000000000000000000017921822306362413915');
T('1483059355427939255846407888', '1483059355427939255846407887.011361095342689876');
T('7722', '7722');
T('1', '0.00000005');
T('8551283060956479353', '8551283060956479352.5707396');
T('1', '0.000000000000000000000000019904267');
T('321978830777554620127500540', '321978830777554620127500539.339278568133088682532238002577');
T('2074', '2073.532654804291079327244387978249477171032485250998396');
T('677676305592', '677676305591.2');
T('1', '0.0000000000006');
T('39181479479778357', '39181479479778357');
T('1', '0.00000000000000000087964700066672916651');
T('896', '896');
T('115083055948552475', '115083055948552475');
T('9105942082143427451223', '9105942082143427451223');
T('1', '0.0000000000000009');
T('1', '0.00000000000000000000004');
T('1', '0.000250427721966583680168028884692015623739');
T('1', '0.000000000001585613219016120158734661293405081934');
T('1', '0.00009');
T('1', '0.000000090358252973411013592234');
T('276312604693909858428', '276312604693909858427.21965306055697011390137926559');
T('1', '0.0000252');
T(2, new BigNumber('1.000000000000000000000000000000000000001').ceil(NaN));
// ---------------------------------------------------------------- v8 start
T(0, 0);
T(0, '0.000');
T(0, -0);
T(Infinity, Infinity);
T(-Infinity, -Infinity);
T(NaN, NaN);
T(NaN, 'NaN');
T(1, 0.1);
T(1, 0.49999999999999994);
T(1, 0.5);
T(1, 0.7);
T(0, -0.1);
T(0, -0.49999999999999994);
T(0, -0.5);
T(0, -0.7);
T(1, 1);
T(2, 1.1);
T(2, 1.5);
T(2, 1.7);
T(-1, -1);
T(-1, -1.1);
T(-1, -1.5);
T(-1, -1.7);
BigNumber.config({EXPONENTIAL_AT : 100});
T(0, -1e-308);
T(-1e308, -1e308);
T('2.1e+308', '2.1e308');
T(0, '-1e-999');
T(1, '1e-999');
T(1, Number.MIN_VALUE);
T(0, -Number.MIN_VALUE);
T(Number.MAX_VALUE, Number.MAX_VALUE);
T(-Number.MAX_VALUE, -Number.MAX_VALUE);
T(Infinity, Infinity);
T(-Infinity, -Infinity);
var two_30 = 1 << 30;
T(two_30, two_30);
T(two_30 + 1, two_30 + 0.1);
T(two_30 + 1, two_30 + 0.5);
T(two_30 + 1, two_30 + 0.7);
T(two_30 - 1, two_30 - 1);
T(two_30, two_30 - 1 + 0.1);
T(two_30, two_30 - 1 + 0.5);
T(two_30, two_30 - 1 + 0.7);
T(-two_30, -two_30);
T(-two_30 + 1, -two_30 + 0.1);
T(-two_30 + 1, -two_30 + 0.5);
T(-two_30 + 1, -two_30 + 0.7);
T(-two_30 + 1, -two_30 + 1);
T(-two_30 + 2, -two_30 + 1 + 0.1);
T(-two_30 + 2, -two_30 + 1 + 0.5);
T(-two_30 + 2, -two_30 + 1 + 0.7);
var two_52 = (1 << 30) * (1 << 22);
T(two_52, two_52);
T(two_52 + 1, '4503599627370496.1');
T(two_52 + 1, '4503599627370496.5');
T(two_52 + 1, '4503599627370496.7');
T(-two_52, -two_52);
T(-two_52 + 1, '-4503599627370495.1');
T(-two_52 + 1, '-4503599627370495.5');
T(-two_52 + 1, '-4503599627370495.7');
// ------------------------------------------------------------------ v8 end
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
File diff suppressed because it is too large Load Diff
+557
View File
@@ -0,0 +1,557 @@
var count = (function config(BigNumber) {
var start = +new Date(),
log,
error,
obj,
undefined,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function assertException(func, message) {
var actual;
total++;
try {
func();
} catch (e) {
actual = e;
}
if (actual && actual.name == 'BigNumber Error') {
passed++;
//log('\n Expected and actual: ' + actual);
} else {
error('\n Test number: ' + total + ' failed');
error('\n Expected: ' + message + ' to raise a BigNumber Error.');
error(' Actual: ' + (actual || 'no exception'));
//process.exit();
}
}
log('\n Testing config...');
obj = BigNumber.config({
DECIMAL_PLACES : 100,
ROUNDING_MODE : 0,
EXPONENTIAL_AT : 50,
RANGE : 500,
ERRORS : false
});
assert(true, obj.DECIMAL_PLACES === 100 &&
obj.ROUNDING_MODE === 0 &&
obj.EXPONENTIAL_AT[0] === -50 &&
obj.EXPONENTIAL_AT[1] === 50 &&
obj.RANGE[0] === -500 &&
obj.RANGE[1] === 500 &&
obj.ERRORS === false
);
obj = BigNumber.config( 99, 8, 32, 333, 1 );
assert(true, obj.DECIMAL_PLACES === 99 &&
obj.ROUNDING_MODE === 8 &&
obj.EXPONENTIAL_AT[0] === -32 &&
obj.EXPONENTIAL_AT[1] === 32 &&
obj.RANGE[0] === -333 &&
obj.RANGE[1] === 333 &&
obj.ERRORS === true
);
obj = BigNumber.config({
DECIMAL_PLACES : 40,
ROUNDING_MODE : 4,
EXPONENTIAL_AT : 1E9,
RANGE : 1E9,
ERRORS : true
});
obj = BigNumber.config( null, null, null, null, null );
obj = BigNumber.config( undefined, undefined, undefined, undefined, undefined );
assert(true, typeof obj === 'object');
assert(true, obj.DECIMAL_PLACES === 40);
assert(true, obj.ROUNDING_MODE === 4);
assert(true, typeof obj.EXPONENTIAL_AT === 'object');
assert(true, obj.EXPONENTIAL_AT.length === 2);
assert(true, obj.EXPONENTIAL_AT[0] === -1e9);
assert(true, obj.EXPONENTIAL_AT[1] === 1e9);
assert(true, typeof obj.RANGE === 'object');
assert(true, obj.RANGE.length === 2);
assert(true, obj.RANGE[0] === -1e9);
assert(true, obj.RANGE[1] === 1e9);
assert(true, obj.ERRORS === true);
obj = BigNumber.config({EXPONENTIAL_AT : [-7, 21], RANGE : [-324, 308]});
// DECIMAL_PLACES
assert(0, BigNumber.config(0).DECIMAL_PLACES);
assert(1, BigNumber.config(1).DECIMAL_PLACES);
assert(20, BigNumber.config(20).DECIMAL_PLACES);
assert(300000, BigNumber.config(300000).DECIMAL_PLACES);
assert(4e+8, BigNumber.config(4e8).DECIMAL_PLACES);
assert(123456789, BigNumber.config('123456789').DECIMAL_PLACES);
assert(1e9, BigNumber.config(1e9).DECIMAL_PLACES);
assert(0, BigNumber.config({DECIMAL_PLACES : 0}).DECIMAL_PLACES);
assert(1, BigNumber.config({DECIMAL_PLACES : 1}).DECIMAL_PLACES);
assert(20, BigNumber.config({DECIMAL_PLACES : 20}).DECIMAL_PLACES);
assert(300000, BigNumber.config({DECIMAL_PLACES : 300000}).DECIMAL_PLACES);
assert(4e+8, BigNumber.config({DECIMAL_PLACES : 4e8}).DECIMAL_PLACES);
assert(123456789, BigNumber.config({DECIMAL_PLACES : '123456789'}).DECIMAL_PLACES);
assert(1e9, BigNumber.config({DECIMAL_PLACES : 1e9}).DECIMAL_PLACES);
assert(1e9, BigNumber.config(null).DECIMAL_PLACES);
assert(1e9, BigNumber.config(undefined).DECIMAL_PLACES);
assert(1e9, BigNumber.config({DECIMAL_PLACES : null}).DECIMAL_PLACES);
assert(1e9, BigNumber.config({DECIMAL_PLACES : undefined}).DECIMAL_PLACES);
assertException(function () {BigNumber.config({DECIMAL_PLACES : -1})}, "DECIMAL_PLACES : -1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : 0.1})}, "DECIMAL_PLACES : 0.1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : 1.1})}, "DECIMAL_PLACES : 1.1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : -1.1})}, "DECIMAL_PLACES : -1.1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : 8.1})}, "DECIMAL_PLACES : 8.1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : 1e+9 + 1})}, "DECIMAL_PLACES : 1e9 + 1");
assertException(function () {BigNumber.config({DECIMAL_PLACES : []})}, "DECIMAL_PLACES : []");
assertException(function () {BigNumber.config({DECIMAL_PLACES : {}})}, "DECIMAL_PLACES : {}");
assertException(function () {BigNumber.config({DECIMAL_PLACES : ''})}, "DECIMAL_PLACES : ''");
assertException(function () {BigNumber.config({DECIMAL_PLACES : ' '})}, "DECIMAL_PLACES : ' '");
assertException(function () {BigNumber.config({DECIMAL_PLACES : 'hi'})}, "DECIMAL_PLACES : 'hi'");
assertException(function () {BigNumber.config({DECIMAL_PLACES : '1e+9'})}, "DECIMAL_PLACES : '1e+9'");
assertException(function () {BigNumber.config({DECIMAL_PLACES : NaN})}, "DECIMAL_PLACES : NaN");
assertException(function () {BigNumber.config({DECIMAL_PLACES : Infinity})}, "DECIMAL_PLACES : Infinity");
BigNumber.config({ ERRORS : false });
assert(1e9, BigNumber.config(-1).DECIMAL_PLACES);
assert(0, BigNumber.config(0.1).DECIMAL_PLACES);
assert(1, BigNumber.config(1.99).DECIMAL_PLACES);
assert(1, BigNumber.config(-1.1).DECIMAL_PLACES);
assert(8, BigNumber.config(8.7654321).DECIMAL_PLACES);
assert(8, BigNumber.config(1e9 + 1).DECIMAL_PLACES);
assert(8, BigNumber.config([]).DECIMAL_PLACES);
assert(8, BigNumber.config({}).DECIMAL_PLACES);
assert(8, BigNumber.config('').DECIMAL_PLACES);
assert(8, BigNumber.config(' ').DECIMAL_PLACES);
assert(8, BigNumber.config('hi').DECIMAL_PLACES);
assert(1e9, BigNumber.config('1e+9').DECIMAL_PLACES);
assert(1e9, BigNumber.config(NaN).DECIMAL_PLACES);
assert(1e9, BigNumber.config(Infinity).DECIMAL_PLACES);
assert(1e9, BigNumber.config(new Date).DECIMAL_PLACES);
assert(1e9, BigNumber.config(null).DECIMAL_PLACES);
assert(1e9, BigNumber.config(undefined).DECIMAL_PLACES);
BigNumber.config({ ERRORS : 1 });
// ROUNDING_MODE
assert(0, BigNumber.config(null, 0).ROUNDING_MODE);
assert(1, BigNumber.config(null, 1).ROUNDING_MODE);
assert(2, BigNumber.config(null, 2).ROUNDING_MODE);
assert(3, BigNumber.config(null, 3).ROUNDING_MODE);
assert(4, BigNumber.config(null, 4).ROUNDING_MODE);
assert(5, BigNumber.config(null, 5).ROUNDING_MODE);
assert(6, BigNumber.config(null, 6).ROUNDING_MODE);
assert(7, BigNumber.config(null, 7).ROUNDING_MODE);
assert(8, BigNumber.config(null, 8).ROUNDING_MODE);
assert(0, BigNumber.config({ROUNDING_MODE : 0}).ROUNDING_MODE);
assert(1, BigNumber.config({ROUNDING_MODE : 1}).ROUNDING_MODE);
assert(2, BigNumber.config({ROUNDING_MODE : 2}).ROUNDING_MODE);
assert(3, BigNumber.config({ROUNDING_MODE : 3}).ROUNDING_MODE);
assert(4, BigNumber.config({ROUNDING_MODE : 4}).ROUNDING_MODE);
assert(5, BigNumber.config({ROUNDING_MODE : 5}).ROUNDING_MODE);
assert(6, BigNumber.config({ROUNDING_MODE : 6}).ROUNDING_MODE);
assert(7, BigNumber.config({ROUNDING_MODE : 7}).ROUNDING_MODE);
assert(8, BigNumber.config({ROUNDING_MODE : 8}).ROUNDING_MODE);
assert(8, BigNumber.config(null, null).ROUNDING_MODE);
assert(8, BigNumber.config(null, undefined).ROUNDING_MODE);
assert(8, BigNumber.config({ROUNDING_MODE : null}).ROUNDING_MODE);
assert(8, BigNumber.config({ROUNDING_MODE : undefined}).ROUNDING_MODE);
assertException(function () {BigNumber.config({ROUNDING_MODE : -1})}, "ROUNDING_MODE : -1");
assertException(function () {BigNumber.config({ROUNDING_MODE : 0.1})}, "ROUNDING_MODE : 0.1");
assertException(function () {BigNumber.config({ROUNDING_MODE : 1.1})}, "ROUNDING_MODE : 1.1");
assertException(function () {BigNumber.config({ROUNDING_MODE : -1.1})}, "ROUNDING_MODE : -1.1");
assertException(function () {BigNumber.config({ROUNDING_MODE : 8.1})}, "ROUNDING_MODE : 8.1");
assertException(function () {BigNumber.config({ROUNDING_MODE : 9})}, "ROUNDING_MODE : 9");
assertException(function () {BigNumber.config({ROUNDING_MODE : 11})}, "ROUNDING_MODE : 11");
assertException(function () {BigNumber.config({ROUNDING_MODE : []})}, "ROUNDING_MODE : []");
assertException(function () {BigNumber.config({ROUNDING_MODE : {}})}, "ROUNDING_MODE : {}");
assertException(function () {BigNumber.config({ROUNDING_MODE : ''})}, "ROUNDING_MODE : ''");
assertException(function () {BigNumber.config({ROUNDING_MODE : ' '})}, "ROUNDING_MODE : ' '");
assertException(function () {BigNumber.config({ROUNDING_MODE : 'hi'})}, "ROUNDING_MODE : 'hi'");
assertException(function () {BigNumber.config({ROUNDING_MODE : NaN})}, "ROUNDING_MODE : NaN");
assertException(function () {BigNumber.config({ROUNDING_MODE : Infinity})}, "ROUNDING_MODE : Infinity");
BigNumber.config({ ERRORS : 0 });
assert(8, BigNumber.config(0, -1).ROUNDING_MODE);
assert(0, BigNumber.config(0, 0.1).ROUNDING_MODE);
assert(1, BigNumber.config(0, 1.99).ROUNDING_MODE);
assert(1, BigNumber.config(0, -1.1).ROUNDING_MODE);
assert(1, BigNumber.config(0, 8.01).ROUNDING_MODE);
assert(7, BigNumber.config(0, 7.99).ROUNDING_MODE);
assert(7, BigNumber.config(0, 1e9 + 1).ROUNDING_MODE);
assert(7, BigNumber.config(0, []).ROUNDING_MODE);
assert(7, BigNumber.config(0, {}).ROUNDING_MODE);
assert(7, BigNumber.config(0, '').ROUNDING_MODE);
assert(7, BigNumber.config(0, ' ').ROUNDING_MODE);
assert(7, BigNumber.config(0, 'hi').ROUNDING_MODE);
assert(1, BigNumber.config(0, '1e+0').ROUNDING_MODE);
assert(1, BigNumber.config(0, NaN).ROUNDING_MODE);
assert(1, BigNumber.config(0, Infinity).ROUNDING_MODE);
assert(1, BigNumber.config(0, new Date).ROUNDING_MODE);
assert(1, BigNumber.config(0, null).ROUNDING_MODE);
assert(1, BigNumber.config(0, undefined).ROUNDING_MODE);
BigNumber.config({ ERRORS : true });
// EXPONENTIAL_AT
assert(true, obj.EXPONENTIAL_AT[0] === -7);
assert(true, obj.EXPONENTIAL_AT[1] === 21);
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [0.1, 1]})}, "EXPONENTIAL_AT : [0.1, 1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [-1, -0.1]})}, "EXPONENTIAL_AT : [-1, -0.1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [1, 1]})}, "EXPONENTIAL_AT : [1, 1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [-1, -1]})}, "EXPONENTIAL_AT : [-1, -1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : 1e9 + 1})}, "EXPONENTIAL_AT : 1e9 + 1");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : -1e9 - 1})}, "EXPONENTIAL_AT : -1e9 - 1");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [-1e9 - 1, 1e9]})}, "EXPONENTIAL_AT : [-1e9 - 1, 1e9]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [-1e9, 1e9 + 1]})}, "EXPONENTIAL_AT : [-1e9, 1e9 + 1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [1e9 + 1, -1e9 - 1]})}, "EXPONENTIAL_AT : [1e9 + 1, -1e9 - 1]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [-Infinity, Infinity]})}, "EXPONENTIAL_AT : [Infinity, -Infinity]");
assertException(function () {BigNumber.config({EXPONENTIAL_AT : [Infinity, -Infinity]})}, "EXPONENTIAL_AT : [Infinity, -Infinity]");
obj = BigNumber.config();
assert(true, obj.EXPONENTIAL_AT[0] === -7);
assert(true, obj.EXPONENTIAL_AT[1] === 21);
assert(1, BigNumber.config({EXPONENTIAL_AT : 1}).EXPONENTIAL_AT[1]);
assert(-1, BigNumber.config({EXPONENTIAL_AT : 1}).EXPONENTIAL_AT[0]);
obj = BigNumber.config({EXPONENTIAL_AT : 0});
assert(true, obj.EXPONENTIAL_AT[0] === 0 && obj.EXPONENTIAL_AT[1] === 0);
obj = BigNumber.config({EXPONENTIAL_AT : -1});
assert(true, obj.EXPONENTIAL_AT[0] === -1 && obj.EXPONENTIAL_AT[1] === 1);
BigNumber.config({ ERRORS : false });
assert(1, BigNumber.config(0, 0, -1).EXPONENTIAL_AT[1]);
assert(0, BigNumber.config(0, 0, 0.1).EXPONENTIAL_AT[0]);
assert(1, BigNumber.config(0, 0, 1.99).EXPONENTIAL_AT[1]);
assert(-2, BigNumber.config(0, 0, -2.1).EXPONENTIAL_AT[0]);
assert(8, BigNumber.config(0, 0, 8.01).EXPONENTIAL_AT[1]);
assert(-7, BigNumber.config(0, 0, -7.99).EXPONENTIAL_AT[0]);
assert(7, BigNumber.config(0, 0, 1e9 + 1).EXPONENTIAL_AT[1]);
assert(7, BigNumber.config(0, 0, -1e9 - 1).EXPONENTIAL_AT[1]);
assert(-7, BigNumber.config(0, 0, []).EXPONENTIAL_AT[0]);
assert(7, BigNumber.config(0, 0, {}).EXPONENTIAL_AT[1]);
assert(-7, BigNumber.config(0, 0, '').EXPONENTIAL_AT[0]);
assert(7, BigNumber.config(0, 0, ' ').EXPONENTIAL_AT[1]);
assert(-7, BigNumber.config(0, 0, 'hi').EXPONENTIAL_AT[0]);
assert(13000, BigNumber.config(0, 0, '1.3e+4').EXPONENTIAL_AT[1]);
assert(-13000, BigNumber.config(0, 0, NaN).EXPONENTIAL_AT[0]);
assert(13000, BigNumber.config(0, 0, Infinity).EXPONENTIAL_AT[1]);
assert(-13000, BigNumber.config(0, 0, new Date).EXPONENTIAL_AT[0]);
assert(13000, BigNumber.config(0, 0, null).EXPONENTIAL_AT[1]);
assert(-13000, BigNumber.config(0, 0, undefined).EXPONENTIAL_AT[0]);
assert(-98765, BigNumber.config(0, 0, 98765.4321).EXPONENTIAL_AT[0]);
assert(98765, BigNumber.config(0, 0, -98765.4321).EXPONENTIAL_AT[1]);
assert(1, BigNumber.config(0, 0, [-98765.4321, 1]).EXPONENTIAL_AT[1]);
assert(-1, BigNumber.config(0, 0, [-1, 98765.4321]).EXPONENTIAL_AT[0]);
assert(98765, BigNumber.config(0, 0, [-1, 98765.4321]).EXPONENTIAL_AT[1]);
assert(98765, BigNumber.config(0, 0, [-1, null]).EXPONENTIAL_AT[1]);
assert(98765, BigNumber.config(0, 0, [null, 98765.4321]).EXPONENTIAL_AT[1]);
assert(-1, BigNumber.config(0, 0, [null, 98765.4321]).EXPONENTIAL_AT[0]);
BigNumber.config({ ERRORS : true });
// RANGE
assert(true, obj.RANGE[0] === -324);
assert(true, obj.RANGE[1] === 308);
assertException(function () {BigNumber.config({RANGE : [-0.9, 1]})}, "RANGE : [-0.9, 1]");
assertException(function () {BigNumber.config({RANGE : [-1, 0.9]})}, "RANGE : [-1, 0.9]");
assertException(function () {BigNumber.config({RANGE : [0, 1]})}, "RANGE : [0, 1]");
assertException(function () {BigNumber.config({RANGE : [-1, 0]})}, "RANGE : [-1, 0]");
assertException(function () {BigNumber.config({RANGE : 0})}, "RANGE : 0");
assertException(function () {BigNumber.config({RANGE : 1e9 + 1})}, "RANGE : 1e9 + 1");
assertException(function () {BigNumber.config({RANGE : -1e9 - 1})}, "RANGE : -1e9 - 1");
assertException(function () {BigNumber.config({RANGE : [-1e9 - 1, 1e9 + 1]})}, "RANGE : [-1e9 - 1, 1e9 + 1]");
assertException(function () {BigNumber.config({RANGE : [1e9 + 1, -1e9 - 1]})}, "RANGE : [1e9 + 1, -1e9 - 1]");
assertException(function () {BigNumber.config({RANGE : Infinity})}, "RANGE : Infinity");
assertException(function () {BigNumber.config({RANGE : "-Infinity"})}, "RANGE : '-Infinity'");
assertException(function () {BigNumber.config({RANGE : [-Infinity, Infinity]})}, "RANGE : [-Infinity, Infinity]");
assertException(function () {BigNumber.config({RANGE : [Infinity, -Infinity]})}, "RANGE : [Infinity, -Infinity]");
obj = BigNumber.config();
assert(true, obj.RANGE[0] === -324);
assert(true, obj.RANGE[1] === 308);
assert(1, BigNumber.config({RANGE : 1}).RANGE[1]);
assert(-1, BigNumber.config({RANGE : 1}).RANGE[0]);
obj = BigNumber.config({RANGE : 1});
assert(true, obj.RANGE[0] === -1 && obj.RANGE[1] === 1);
obj = BigNumber.config({RANGE : -1});
assert(true, obj.RANGE[0] === -1 && obj.RANGE[1] === 1);
BigNumber.config({ ERRORS : 0 });
assert(1, BigNumber.config(0, 0, 0, -1).RANGE[1]);
assert(-1, BigNumber.config(0, 0, 0, 0.1).RANGE[0]);
assert(1, BigNumber.config(0, 0, 0, 1.99).RANGE[1]);
assert(-2, BigNumber.config(0, 0, 0, -2.1).RANGE[0]);
assert(8, BigNumber.config(0, 0, 0, 8.01).RANGE[1]);
assert(-7, BigNumber.config(0, 0, 0, -7.99).RANGE[0]);
assert(7, BigNumber.config(0, 0, 0, 1e9 + 1).RANGE[1]);
assert(7, BigNumber.config(0, 0, 0, -1e9 - 1).RANGE[1]);
assert(-7, BigNumber.config(0, 0, 0, []).RANGE[0]);
assert(7, BigNumber.config(0, 0, 0, {}).RANGE[1]);
assert(-7, BigNumber.config(0, 0, 0, '').RANGE[0]);
assert(7, BigNumber.config(0, 0, 0, ' ').RANGE[1]);
assert(-7, BigNumber.config(0, 0, 0, 'hi').RANGE[0]);
assert(13000, BigNumber.config(0, 0, 0, '1.3e+4').RANGE[1]);
assert(-13000, BigNumber.config(0, 0, 0, NaN).RANGE[0]);
assert(13000, BigNumber.config(0, 0, 0, Infinity).RANGE[1]);
assert(-13000, BigNumber.config(0, 0, 0, new Date).RANGE[0]);
assert(13000, BigNumber.config(0, 0, 0, null).RANGE[1]);
assert(-13000, BigNumber.config(0, 0, 0, undefined).RANGE[0]);
assert(-98765, BigNumber.config(0, 0, 0, 98765.4321).RANGE[0]);
assert(98765, BigNumber.config(0, 0, 0, -98765.4321).RANGE[1]);
assert(1, BigNumber.config(0, 0, 0, [-98765.4321, 1]).RANGE[1]);
assert(-1, BigNumber.config(0, 0, 0, [-1, 98765.4321]).RANGE[0]);
assert(98765, BigNumber.config(0, 0, 0, [-1, 98765.4321]).RANGE[1]);
assert(98765, BigNumber.config(0, 0, 0, [-1, null]).RANGE[1]);
assert(98765, BigNumber.config(0, 0, 0, [null, 98765.4321]).RANGE[1]);
assert(-1, BigNumber.config(0, 0, 0, [null, 98765.4321]).RANGE[0]);
BigNumber.config({ ERRORS : true });
// ERRORS
assert(false, BigNumber.config(null, null, null, null, 0).ERRORS);
assert(true, BigNumber.config(null, null, null, null, 1).ERRORS);
assert(false, BigNumber.config(null, null, null, null, false).ERRORS);
assert(true, BigNumber.config(null, null, null, null, true).ERRORS);
assert(false, BigNumber.config({ERRORS : 0}).ERRORS);
assert(true, BigNumber.config({ERRORS : 1}).ERRORS);
assert(false, BigNumber.config({ERRORS : false}).ERRORS);
assert(true, BigNumber.config({ERRORS : true}).ERRORS);
assert(true, BigNumber.config(null, null, null, null, null).ERRORS);
assert(true, BigNumber.config(null, null, null, null, undefined).ERRORS);
assert(true, BigNumber.config({ERRORS : null}).ERRORS);
assert(true, BigNumber.config({ERRORS : undefined}).ERRORS);
assertException(function () {BigNumber.config({ERRORS : 'hiya'})}, "ERRORS : 'hiya'");
assertException(function () {BigNumber.config({ERRORS : 'true'})}, "ERRORS : 'true'");
assertException(function () {BigNumber.config({ERRORS : 'false'})}, "ERRORS : 'false'");
assertException(function () {BigNumber.config({ERRORS : '0'})}, "ERRORS : '0'");
assertException(function () {BigNumber.config({ERRORS : '1'})}, "ERRORS : '1'");
assertException(function () {BigNumber.config({ERRORS : -1})}, "ERRORS : -1");
assertException(function () {BigNumber.config({ERRORS : 0.1})}, "ERRORS : 0.1");
assertException(function () {BigNumber.config({ERRORS : 1.1})}, "ERRORS : 1.1");
assertException(function () {BigNumber.config({ERRORS : []})}, "ERRORS : []");
assertException(function () {BigNumber.config({ERRORS : {}})}, "ERRORS : {}");
assertException(function () {BigNumber.config({ERRORS : ''})}, "ERRORS : ''");
assertException(function () {BigNumber.config({ERRORS : ' '})}, "ERRORS : ' '");
assertException(function () {BigNumber.config({ERRORS : NaN})}, "ERRORS : NaN");
assertException(function () {BigNumber.config({ERRORS : Infinity})}, "ERRORS : Infinity");
assert(true, BigNumber.config().ERRORS);
BigNumber.config({ ERRORS : false });
assert(false, BigNumber.config(null, null, null, null, 0).ERRORS);
assert(false, BigNumber.config(null, null, null, null, 1.1).ERRORS);
assert(false, BigNumber.config(null, null, null, null, false).ERRORS);
assert(true, BigNumber.config(null, null, null, null, 1).ERRORS);
assert(false, BigNumber.config(null, null, null, null, 0).ERRORS);
assert(false, BigNumber.config(null, null, null, null, '1').ERRORS);
assert(false, BigNumber.config(null, null, null, null, 'true').ERRORS);
assert(false, BigNumber.config(null, null, null, null, false).ERRORS);
assert(false, BigNumber.config({ERRORS : null}).ERRORS);
assert(false, BigNumber.config({ERRORS : undefined}).ERRORS);
assert(false, BigNumber.config({ERRORS : NaN}).ERRORS);
assert(false, BigNumber.config({ERRORS : 'd'}).ERRORS);
assert(false, BigNumber.config({ERRORS : []}).ERRORS);
assert(false, BigNumber.config({ERRORS : {}}).ERRORS);
assert(false, BigNumber.config({ERRORS : new Date}).ERRORS);
assert(true, BigNumber.config({ERRORS : Boolean(1)}).ERRORS);
assert(true, BigNumber.config({ERRORS : Boolean(true)}).ERRORS);
assert(false, BigNumber.config({ERRORS : Boolean(0)}).ERRORS);
assert(false, BigNumber.config({ERRORS : Boolean(false)}).ERRORS);
assert(true, BigNumber.config({ERRORS : Boolean('false')}).ERRORS);
// Test constructor parsing.
BigNumber.config({
DECIMAL_PLACES : 40,
ROUNDING_MODE : 4,
EXPONENTIAL_AT : 1E9,
RANGE : 1E9,
ERRORS : true
});
assert('NaN', new BigNumber(NaN).toS());
assert('NaN', new BigNumber('NaN').toS());
assert('NaN', new BigNumber(' NaN').toS());
assert('NaN', new BigNumber('NaN ').toS());
assert('NaN', new BigNumber(' NaN ').toS());
assert('NaN', new BigNumber('+NaN').toS());
assert('NaN', new BigNumber(' +NaN').toS());
assert('NaN', new BigNumber('+NaN ').toS());
assert('NaN', new BigNumber(' +NaN ').toS());
assert('NaN', new BigNumber('-NaN').toS());
assert('NaN', new BigNumber(' -NaN').toS());
assert('NaN', new BigNumber('-NaN ').toS());
assert('NaN', new BigNumber(' -NaN ').toS());
assertException(function () {new BigNumber('+ NaN')}, "+ NaN");
assertException(function () {new BigNumber('- NaN')}, "- NaN");
assertException(function () {new BigNumber(' + NaN')}, " + NaN");
assertException(function () {new BigNumber(' - NaN')}, " - NaN");
assertException(function () {new BigNumber('. NaN')}, ". NaN");
assertException(function () {new BigNumber('.-NaN')}, ".-NaN");
assertException(function () {new BigNumber('.+NaN')}, ".+NaN");
assertException(function () {new BigNumber('-.NaN')}, "-.NaN");
assertException(function () {new BigNumber('+.NaN')}, "+.NaN");
assert('Infinity', new BigNumber(Infinity).toS());
assert('Infinity', new BigNumber('Infinity').toS());
assert('Infinity', new BigNumber(' Infinity').toS());
assert('Infinity', new BigNumber('Infinity ').toS());
assert('Infinity', new BigNumber(' Infinity ').toS());
assert('Infinity', new BigNumber('+Infinity').toS());
assert('Infinity', new BigNumber(' +Infinity').toS());
assert('Infinity', new BigNumber('+Infinity ').toS());
assert('Infinity', new BigNumber(' +Infinity ').toS());
assert('-Infinity', new BigNumber('-Infinity').toS());
assert('-Infinity', new BigNumber(' -Infinity').toS());
assert('-Infinity', new BigNumber('-Infinity ').toS());
assert('-Infinity', new BigNumber(' -Infinity ').toS());
assertException(function () {new BigNumber('+ Infinity')}, "+ Infinity");
assertException(function () {new BigNumber(' + Infinity')}, " + Infinity");
assertException(function () {new BigNumber('- Infinity')}, "- Infinity");
assertException(function () {new BigNumber(' - Infinity')}, " - Infinity");
assertException(function () {new BigNumber('.Infinity')}, ".Infinity");
assertException(function () {new BigNumber('. Infinity')}, ". Infinity");
assertException(function () {new BigNumber('.-Infinity')}, ".-Infinity");
assertException(function () {new BigNumber('.+Infinity')}, ".+Infinity");
assertException(function () {new BigNumber('-.Infinity')}, "-.Infinity");
assertException(function () {new BigNumber('+.Infinity')}, "+.Infinity");
assert('0', new BigNumber(0).toS());
assert('0', new BigNumber(-0).toS());
assert('0', new BigNumber('+0').toS());
assert('0', new BigNumber('-0').toS());
assert('0', new BigNumber(' +0').toS());
assert('0', new BigNumber(' -0').toS());
assert('0', new BigNumber(' +0 ').toS());
assert('0', new BigNumber(' -0 ').toS());
assert('0', new BigNumber('+.0').toS());
assert('0', new BigNumber('-.0').toS());
assert('0', new BigNumber(' +.0').toS());
assert('0', new BigNumber(' -.0').toS());
assert('0', new BigNumber(' +.0 ').toS());
assert('0', new BigNumber(' -.0 ').toS());
assertException(function () {new BigNumber('+-0')}, "+-0");
assertException(function () {new BigNumber('-+0')}, "-+0");
assertException(function () {new BigNumber('--0')}, "--0");
assertException(function () {new BigNumber('++0')}, "++0");
assertException(function () {new BigNumber('.-0')}, ".-0");
assertException(function () {new BigNumber('.+0')}, ".+0");
assertException(function () {new BigNumber('. 0')}, ". 0");
assertException(function () {new BigNumber('..0')}, "..0");
assertException(function () {new BigNumber('+.-0')}, "+.-0");
assertException(function () {new BigNumber('-.+0')}, "-.+0");
assertException(function () {new BigNumber('+. 0')}, "+. 0");
assertException(function () {new BigNumber('-. 0')}, "-. 0");
assert('2', new BigNumber('+2').toS());
assert('-2', new BigNumber('-2').toS());
assert('2', new BigNumber(' +2').toS());
assert('-2', new BigNumber(' -2').toS());
assert('2', new BigNumber(' +2 ').toS());
assert('-2', new BigNumber(' -2 ').toS());
assert('0.2', new BigNumber('+.2').toS());
assert('-0.2', new BigNumber('-.2').toS());
assert('0.2', new BigNumber(' +.2').toS());
assert('-0.2', new BigNumber(' -.2').toS());
assert('0.2', new BigNumber(' +.2 ').toS());
assert('-0.2', new BigNumber(' -.2 ').toS());
assertException(function () {new BigNumber('+-2')}, "+-2");
assertException(function () {new BigNumber('-+2')}, "-+2");
assertException(function () {new BigNumber('--2')}, "--2");
assertException(function () {new BigNumber('++2')}, "++2");
assertException(function () {new BigNumber('.-2')}, ".-2");
assertException(function () {new BigNumber('.+2')}, ".+2");
assertException(function () {new BigNumber('. 2')}, ". 2");
assertException(function () {new BigNumber('..2')}, "..2");
assertException(function () {new BigNumber('+.-2')}, "+.-2");
assertException(function () {new BigNumber('-.+2')}, "-.+2");
assertException(function () {new BigNumber('+. 2')}, "+. 2");
assertException(function () {new BigNumber('-. 2')}, "-. 2");
assertException(function () {new BigNumber('+2..')}, "+2..");
assertException(function () {new BigNumber('-2..')}, "-2..");
assertException(function () {new BigNumber('-.2.')}, "-.2.");
assertException(function () {new BigNumber('+.2.')}, "+.2.");
assertException(function () {new BigNumber('.-20.')}, ".-20.");
assertException(function () {new BigNumber('.+20.')}, ".+20.");
assertException(function () {new BigNumber('. 20.')}, ". 20.");
assertException(function () {new BigNumber(undefined)}, "undefined");
assertException(function () {new BigNumber([])}, "[]");
assertException(function () {new BigNumber('')}, "''");
assertException(function () {new BigNumber(null)}, "null");
assertException(function () {new BigNumber(' ')}, "' '");
assertException(function () {new BigNumber('nan')}, "nan");
assertException(function () {new BigNumber('23er')}, "23er");
assertException(function () {new BigNumber('e4')}, "e4");
assertException(function () {new BigNumber('0x434')}, "0x434");
assertException(function () {new BigNumber('--45')}, "--45");
assertException(function () {new BigNumber('+-2')}, "+-2");
assertException(function () {new BigNumber('0 0')}, "0 0");
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
File diff suppressed because it is too large Load Diff
+39
View File
@@ -0,0 +1,39 @@
var arr,
passed = 0,
total = 0,
start = +new Date();
console.log( '\n STARTING TESTS...\n' );
[
'abs',
'base-in',
'base-out',
'ceil',
'cmp',
'config',
'div',
'floor',
'minus',
'mod',
'neg',
'others',
'plus',
'pow',
'round',
'sqrt',
'times',
'toExponential',
'toFixed',
'toFraction',
'toPrecision',
'toString'
]
.forEach( function (method) {
arr = require('./' + method);
passed += arr[0];
total += arr[1];
});
console.log( '\n IN TOTAL: ' + passed + ' of ' + total + ' tests passed in ' +
( (+new Date() - start) / 1000 ) + ' secs.\n' );
+216
View File
@@ -0,0 +1,216 @@
var count = (function floor(BigNumber) {
var start = +new Date(),
log,
error,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function T(expected, value) {
assert(String(expected), new BigNumber(String(value)).floor().toString());
}
log('\n Testing floor...');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : 1E9
});
T('-2075365', '-2075364.364286541923');
T('60593539780450631', '60593539780450631');
T('65937898671515', '65937898671515');
T('-39719494751819198566799', '-39719494751819198566798.578');
T('92627382695288166556', '92627382695288166556.8683774524284866028260448205069');
T('-881574', '-881574');
T('-3633239210', '-3633239209.654526163275621746013315304191073405508491056');
T('-23970335459820625362', '-23970335459820625362');
T('131869457416154038', '131869457416154038');
T('-2685', '-2685');
T('-4542227861', '-4542227860.9511298545226');
T('2416872281', '2416872281.963955669484225137349193306323379254936827');
T('-757684868752087594264588207656', '-757684868752087594264588207655.27838048392835556');
T('-438798503527', '-438798503526.2317623894721299587561697');
T('801625782231888715214665', '801625782231888715214665');
T('-91881984778675238', '-91881984778675238');
T('327765350218284325239839632046', '327765350218284325239839632046.91682741746683081459605386');
T('-7469045007691432295', '-7469045007691432294.362757245');
T('8365540212937142194319515218789', '8365540212937142194319515218789.4106658678537421977827');
T('-14109', '-14108.495051214515');
T('49104501', '49104501.10055989379655329194309526150310568683504206945625');
T('131370406', '131370406.330005158136313262837556068534122953');
T('3017', '3017');
T('-690', '-689.6944252229740521128820354989299283');
T('73441822178', '73441822178.572653');
T('-2330', '-2329.42655772223486531483602927572548264457');
T('-834103872107533086', '-834103872107533086');
T('-1501493189970436', '-1501493189970435.74866616700317');
T('70591', '70591.2244675522123484658978887');
T('4446128540401735117', '4446128540401735117.435836700611264749985822486641350492901');
T('-597273', '-597273');
T('729117', '729117');
T('504', '504');
T('4803729546823170064608098091', '4803729546823170064608098091');
T('24147026285420507467578', '24147026285420507467578');
T('-6581532150677269472830', '-6581532150677269472829.38194951340848938896000325718062365494');
T('-131279182164804752', '-131279182164804751.430589952021038264');
T('2949426983040959', '2949426983040959.8911208825380208568451907');
T('25166', '25166.125888418871654557352055849116604612621573251770362');
T('4560569286495', '4560569286495.98300685103599898554605198');
T('13', '13.763105480576616251068323541559825687');
T('176037174185746614410406167887', '176037174185746614410406167887.42317518');
T('9050999219306', '9050999219306.7846946346757664893036971777');
T('39900924', '39900924');
T('115911043168452445', '115911043168452445');
T('20962819101135667464733349383', '20962819101135667464733349383.8959025798517496777183');
T('4125789711001606948191', '4125789711001606948191.4707575965791242737346836');
T('-6935502', '-6935501.294727166142750626019282');
T('-2', '-1.518418076611593764852321765899');
T('-35416', '-35416');
T('6912783515683955988122411164548', '6912783515683955988122411164548.393');
T('657', '657.0353902852');
T('0', '0.0009');
T('0', '0.00000000000000000000000017921822306362413915');
T('1483059355427939255846407887', '1483059355427939255846407887.011361095342689876');
T('7722', '7722');
T('0', '0.00000005');
T('8551283060956479352', '8551283060956479352.5707396');
T('0', '0.000000000000000000000000019904267');
T('321978830777554620127500539', '321978830777554620127500539.339278568133088682532238002577');
T('2073', '2073.532654804291079327244387978249477171032485250998396');
T('677676305591', '677676305591.2');
T('0', '0.0000000000006');
T('39181479479778357', '39181479479778357');
T('0', '0.00000000000000000087964700066672916651');
T('896', '896');
T('115083055948552475', '115083055948552475');
T('9105942082143427451223', '9105942082143427451223');
T('0', '0.0000000000000009');
T('0', '0.00000000000000000000004');
T('0', '0.000250427721966583680168028884692015623739');
T('0', '0.000000000001585613219016120158734661293405081934');
T('0', '0.00009');
T('0', '0.000000090358252973411013592234');
T('276312604693909858427', '276312604693909858427.21965306055697011390137926559');
T('0', '0.0000252');
// ---------------------------------------------------------------- v8 start
T(0, 0);
T(0, '0.000');
T(-0, -0);
T(Infinity, Infinity);
T(-Infinity, -Infinity);
T(NaN, NaN);
T(0, 0.1);
T(0, 0.49999999999999994);
T(0, 0.5);
T(0, 0.7);
T(-1, -0.1);
T(-1, -0.49999999999999994);
T(-1, -0.5);
T(-1, -0.7);
T(1, 1);
T(1, 1.1);
T(1, 1.5);
T(1, 1.7);
T(-1, -1);
T(-2, -1.1);
T(-2, -1.5);
T(-2, -1.7);
BigNumber.config({EXPONENTIAL_AT : 100});
T(-1, -1e-308);
T(-1e308, -1e308);
T('2.1e+308', '2.1e308');
T(-1, '-1e-999');
T(0, '1e-999');
T(0, Number.MIN_VALUE);
T(-1, -Number.MIN_VALUE);
T(Number.MAX_VALUE, Number.MAX_VALUE);
T(-Number.MAX_VALUE, -Number.MAX_VALUE);
T(Infinity, Infinity);
T(-Infinity, -Infinity);
var two_30 = 1 << 30;
T(two_30, two_30);
T(two_30, two_30 + 0.1);
T(two_30, two_30 + 0.5);
T(two_30, two_30 + 0.7);
T(two_30 - 1, two_30 - 1);
T(two_30 - 1, two_30 - 1 + 0.1);
T(two_30 - 1, two_30 - 1 + 0.5);
T(two_30 - 1, two_30 - 1 + 0.7);
T(-two_30, -two_30);
T(-two_30, -two_30 + 0.1);
T(-two_30, -two_30 + 0.5);
T(-two_30, -two_30 + 0.7);
T(-two_30 + 1, -two_30 + 1);
T(-two_30 + 1, -two_30 + 1 + 0.1);
T(-two_30 + 1, -two_30 + 1 + 0.5);
T(-two_30 + 1, -two_30 + 1 + 0.7);
var two_52 = (1 << 30) * (1 << 22);
T(two_52, two_52);
T(two_52, two_52 + 0.1);
T(two_52, two_52 + 0.5);
T(two_52 + 1, two_52 + 0.7);
T(two_52 - 1, two_52 - 1);
T(two_52 - 1, two_52 - 1 + 0.1);
T(two_52 - 1, two_52 - 1 + 0.5);
T(two_52 - 1, two_52 - 1 + 0.7);
T(-two_52, -two_52);
T(-two_52, -two_52 + 0.1);
T(-two_52, -two_52 + 0.5);
T(-two_52, -two_52 + 0.7);
T(-two_52 + 1, -two_52 + 1);
T(-two_52 + 1, -two_52 + 1 + 0.1);
T(-two_52 + 1, -two_52 + 1 + 0.5);
T(-two_52 + 1, -two_52 + 1 + 0.7);
// ------------------------------------------------------------------ v8 end
assert('1', new BigNumber('1.9999999999').floor(NaN).toString());
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+544
View File
@@ -0,0 +1,544 @@
var count = (function neg(BigNumber) {
var start = +new Date(),
log,
error,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function T(expected, value){
assert(String(expected), new BigNumber(value).neg().toString());
}
function isMinusZero(n) {
return n.toString() === '0' && n.s == -1;
}
log('\n Testing neg...');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : [-7, 21]
});
T(-4, 4);
T(-2147483648, 2147483648);
T(-0.25, 0.25);
T(-0.0625, 0.0625);
T(-1, 1);
T(1, -1);
T(0, 0);
T(NaN, NaN);
T(-Infinity, Infinity);
T(-Infinity, +Infinity);
T(Infinity, -Infinity);
T(+Infinity, -Infinity);
T('0', '0');
T('-238', '238');
T('1.3e-11', '-0.000000000013');
T('-33.1', '33.1');
T('2.61', '-2.61');
T('-4', '4.0');
T('-5.8', '5.8');
T('-3.52e-7', '0.000000352');
T('190', '-190');
T('4.47', '-4.47');
T('6.9525e-12', '-0.0000000000069525');
T('1.3', '-1.3');
T('-6.21', '6.21');
T('2', '-2');
T('-1', '1');
T('147.857', '-147.857');
T('-26.517', '26.517');
T('-3', '3');
T('5', '-5');
T('204', '-204');
T('2.1e-8', '-0.000000021');
T('3.7015e-7', '-0.00000037015');
T('-50.1839', '50.1839');
T('44768.1', '-44768.1');
T('3.8e-15', '-0.0000000000000038');
T('-7.4379', '7.4379');
T('1.5', '-1.5');
T('6.0399', '-6.0399');
T('109.07', '-109.070');
T('1582', '-1582');
T('-772', '772');
T('-6.7824e-14', '0.000000000000067824');
T('-1.819e-8', '0.00000001819');
T('-3e-15', '0.0000000000000030');
T('-424120', '424120');
T('-1814.54', '1814.54');
T('-4.295e-17', '0.00000000000000004295');
T('-5', '5');
T('2152', '-2152');
T('4.6', '-4.6');
T('1.9', '-1.9');
T('-2', '2.0');
T('-0.00036', '0.00036');
T('-0.000006962', '0.000006962');
T('3.6', '-3.6');
T('-1.1495e-14', '0.000000000000011495');
T('-312.4', '312.4');
T('4.3e-10', '-0.00000000043');
T('5', '-5');
T('-1.8911e-8', '0.000000018911');
T('4963.53', '-4963.53');
T('-4.3934e-10', '0.00000000043934');
T('-1.3', '1.30');
T('-1', '1.0');
T('-68.32', '68.32');
T('0.014836', '-0.014836');
T('8', '-8');
T('2.1351', '-2.13510');
T('162224', '-162224');
T('3e-19', '-0.00000000000000000030');
T('0.00004985', '-0.00004985');
T('28.9321', '-28.9321');
T('-2', '2');
T('-16688', '16688');
T('-1', '1');
T('5', '-5');
T('-20', '20.0');
T('-1.9', '1.9');
T('3', '-3');
T('185640', '-185640');
T('-0.0000058', '0.0000058');
T('9.67e-13', '-0.000000000000967');
T('-707.98', '707.98');
T('2.57917', '-2.57917');
T('-1.3', '1.3');
T('-4.2655', '4.2655');
T('-149.6', '149.6');
T('-1.32383', '1.32383');
T('-26.925', '26.925');
T('-0.00013', '0.00013');
T('-6868', '6868');
T('7', '-7');
T('-5e-9', '0.0000000050');
T('3.2555e-16', '-0.00000000000000032555');
T('1.42768e-13', '-0.000000000000142768');
T('11.2962', '-11.2962');
T('3186.7', '-3186.7');
T('-6.9', '6.9');
T('-6.2618e-7', '0.00000062618');
T('8', '-8');
T('-8.04', '8.04');
T('-22', '22');
T('-750.6', '750.6');
T('12.803', '-12.803');
T('-20513.4', '20513.4');
T('114781', '-114781');
T('-16.9046', '16.9046');
T('4.6e-7', '-0.00000046');
T('-31399', '31399');
T('1.04', '-1.04');
T('-51.2544', '51.2544');
T('1.023e-15', '-0.000000000000001023');
T('281', '-281');
T('-128315', '128315');
T('20.2', '-20.2');
T('9', '-9');
T('-10', '10');
T('-1.92262e-17', '0.0000000000000000192262');
T('-0.0023', '0.0023');
T('5', '-5');
T('7', '-7');
T('13.72', '-13.72');
T('98068', '-98068');
T('3.2', '-3.2');
T('1.1', '-1.1');
T('-3.97e-18', '0.000000000000000003970');
T('0.00334824', '-0.00334824');
T('-5.4892e-8', '0.000000054892');
T('-1', '1.0');
T('-2.8135e-8', '0.000000028135');
T('-1.816e-13', '0.0000000000001816');
T('199724', '-199724');
T('-19.4', '19.40');
T('-12.74', '12.74');
T('-2171.8', '2171.8');
T('-2.7', '2.7');
T('1', '-1.0');
T('21779', '-21779');
T('8.9e-12', '-0.0000000000089');
T('-4.51', '4.51');
T('2.6', '-2.6');
T('-0.00016', '0.000160');
T('6', '-6');
T('50.566', '-50.566');
T('-16.2', '16.2');
T('-7.9156e-20', '0.000000000000000000079156');
T('-2262.4', '2262.4');
T('6468.59', '-6468.59');
T('0.077', '-0.077');
T('-465.83', '465.83');
T('-604.59', '604.59');
T('-0.0014917', '0.0014917');
T('-2.8954', '2.8954');
T('1', '-1');
T('1942', '-1942');
T('-182.308', '182.308');
T('-17.8', '17.8');
T('39472.5', '-39472.5');
T('214.21', '-214.21');
T('-40.11', '40.11');
T('-3', '3');
T('141149', '-141149');
T('-8', '8.0');
T('-2.9', '2.9');
T('44.51', '-44.51');
T('-5.3', '5.3');
T('0.05498', '-0.054980');
T('7', '-7');
T('-922', '922.0');
T('-1.5146e-14', '0.000000000000015146');
T('-0.000008117', '0.000008117');
T('1', '-1');
T('5452.81', '-5452.81');
T('751745', '-751745');
T('-2.7', '2.7');
T('5.1', '-5.1');
T('-1', '1');
T('-524124', '524124');
T('-183.5', '183.50');
T('44856.8', '-44856.8');
T('0.00000387', '-0.00000387');
T('-3.0544e-14', '0.000000000000030544');
T('1.3', '-1.3');
T('-0.0019273', '0.0019273');
T('75428', '-75428');
T('-91.7925', '91.7925');
T('44.5', '-44.5');
T('-2', '2');
T('5.3', '-5.3');
T('-57', '57');
T('-2.53e-9', '0.00000000253');
T('18258', '-18258');
T('0.829', '-0.829');
T('-4', '4');
T('-1', '1');
T('10.289', '-10.289');
T('319', '-319');
T('2.4', '-2.4');
T('89.9207', '-89.9207');
T('-9.06122e-17', '0.0000000000000000906122');
T('-102.639', '102.639');
T('948.5', '-948.50');
T('-610.7', '610.7');
T('-1.61', '1.61');
T('-99.042', '99.042');
T('3.0232', '-3.0232');
T('-15', '15');
T('-3.835', '3.835');
T('-7', '7');
T('1', '-1');
T('21.46', '-21.46');
T('2', '-2');
T('-2077.79', '2077.79');
T('-14.7446', '14.7446');
T('-9.11e-12', '0.00000000000911');
T('1.2', '-1.2');
T('-105851', '105851');
T('24.561', '-24.561');
T('780', '-780');
T('3.82122', '-3.82122');
T('9564', '-9564');
T('-13.21', '13.21');
T('25020.5', '-25020.5');
T('-5678.6', '5678.6');
T('1', '-1.0');
T('2.6', '-2.6');
T('9.6e-16', '-0.000000000000000960');
T('12.6', '-12.6');
T('-5', '5');
T('-537', '537');
T('-85', '85');
T('758.15', '-758.15');
T('-67.55', '67.55');
T('-9444', '9444');
T('21.4', '-21.4');
T('2.5', '-2.5');
T('489311', '-489311');
T('6.8', '-6.8');
T('4.29', '-4.29');
T('23982', '-23982.0');
T('-0.0111781', '0.0111781');
T('4.96e-20', '-0.0000000000000000000496');
T('-40.5481', '40.5481');
T('-32.52', '32.52');
T('-7.4', '7.4');
T('1008', '-1008');
T('1.2', '-1.2');
T('-5', '5.0');
T('-2463.4', '2463.4');
T('7.363', '-7.363');
T('2.8', '-2.8');
T('-14498', '14498');
T('201', '-201');
T('3.2', '-3.2');
T('-3.05', '3.05');
T('1.1', '-1.1');
T('-380.4', '380.4');
T('13399', '-13399');
T('-20.44', '20.44');
T('1.6', '-1.6');
T('2.1234e-10', '-0.00000000021234');
T('4404.1', '-4404.1');
T('2.4345', '-2.4345');
T('-117.256', '117.256');
T('-6.025', '6.025');
T('18.43', '-18.43');
T('-47.5', '47.5');
T('45.1', '-45.1');
T('-3806.5', '3806.5');
T('-4.6', '4.6');
T('-1.3', '1.3');
T('-74.6', '74.60');
T('-16.2088', '16.2088');
T('788.6', '-788.6');
T('-0.29', '0.29');
T('1', '-1');
T('-4.058', '4.058');
T('5', '-5.0');
T('0.00612', '-0.00612');
T('-14317', '14317');
T('-1.1801', '1.1801');
T('-32.6', '32.6');
T('57248', '-57248');
T('-103', '103');
T('-1.4', '1.4');
T('228', '-228');
T('92.8', '-92.8');
T('3.46e-17', '-0.0000000000000000346');
T('-15747', '15747');
T('16.36', '-16.360');
T('0.00223', '-0.00223');
T('244', '-244');
T('3.8', '-3.8');
T('-604.2', '604.2');
T('1.03', '-1.03');
T('1487', '-1487');
T('7', '-7');
T('45', '-45.00');
T('2.55374e-10', '-0.000000000255374');
T('3', '-3');
T('-5.5', '5.5');
T('-5.4', '5.4');
T('-9', '9');
T('-1627.2', '1627.2');
T('1.0805e-16', '-0.00000000000000010805');
T('-14.0548', '14.0548');
T('-207137', '207137');
T('3.8', '-3.8');
T('-33.4785', '33.4785');
T('4.28626', '-4.28626');
T('-4', '4');
T('-6', '6');
T('-1', '1');
T('-44.951', '44.951');
T('29.7', '-29.7');
T('-121.17', '121.17');
T('480', '-480');
T('-2.696', '2.696');
T('-3708.62', '3708.62');
T('2.8', '-2.8');
T('17842', '-17842');
T('-3', '3');
T('-2', '2');
T('-1.855', '1.855');
T('246866', '-246866');
T('-0.0022', '0.0022');
T('-1', '1');
T('1283', '-1283');
T('2.1', '-2.1');
T('3.289e-12', '-0.000000000003289');
T('-1656', '1656');
T('3.9', '-3.9');
T('1.12', '-1.12');
T('3.54e-16', '-0.000000000000000354');
T('-0.001123', '0.001123');
T('2.06551e-14', '-0.0000000000000206551');
T('-19319.3', '19319.3');
T('3', '-3');
T('-6', '6');
T('5.747e-17', '-0.00000000000000005747');
T('-1.756', '1.756');
T('2.71004e-15', '-0.00000000000000271004');
T('1.4', '-1.4');
T('-0.0000019', '0.00000190');
T('-6', '6');
T('-31.4', '31.4');
T('1', '-1');
T('-39.954', '39.9540');
T('8.4', '-8.40');
T('5.3382e-17', '-0.0000000000000000533820');
T('8.4', '-8.4');
T('-106', '106');
T('905', '-905');
T('-2030.8', '2030.8');
T('0.19358', '-0.193580');
T('50057.4', '-50057.4');
T('8.0731e-15', '-0.0000000000000080731');
T('2.4', '-2.4');
T('-1', '1');
T('0.026038', '-0.026038');
T('-22', '22');
T('-2.8', '2.8');
T('0.00110001', '-0.00110001');
T('7', '-7');
T('-705', '705');
T('-36046', '36046');
T('2.42', '-2.42');
T('-1.225', '1.225');
T('36.8', '-36.8');
T('6.8926', '-6.8926');
T('163575', '-163575');
T('3.29e-16', '-0.000000000000000329');
T('-3.9612e-20', '0.000000000000000000039612');
T('6.3', '-6.3');
T('1.1', '-1.1');
T('-53', '53');
T('-6.3', '6.3');
T('-3.73', '3.73');
T('5.99e-13', '-0.000000000000599');
T('-0.0453', '0.0453');
T('6.2', '-6.2');
T('5', '-5');
T('4.85599e-7', '-0.000000485599');
T('-6.554e-19', '0.0000000000000000006554');
T('245.2', '-245.20');
T('-12.557', '12.557');
T('8.7', '-8.7');
T('-38.7', '38.7');
T('1.1291', '-1.1291');
T('-3', '3');
T('40533.9', '-40533.9');
T('135.1', '-135.1');
T('-213', '213');
T('-271352', '271352');
T('-159.9', '159.9');
T('-103632', '103632');
T('-0.00000225418', '0.00000225418');
T('-2.1e-16', '0.00000000000000021');
T('14.5', '-14.5');
T('48016', '-48016');
T('282', '-282.0');
T('9.3552e-18', '-0.0000000000000000093552');
T('237', '-237');
T('-21.1', '21.1');
T('2.281', '-2.281');
T('-4.68312', '4.68312');
T('7', '-7');
T('6', '-6');
T('5.3', '-5.3');
T('-681.586', '681.586');
T('-1.59e-16', '0.0000000000000001590');
T('-2.94', '2.94');
T('-1', '1');
T('7.03', '-7.03');
T('5.73608e-13', '-0.000000000000573608');
T('2', '-2');
T('-1.26e-18', '0.00000000000000000126');
T('-1.5e-14', '0.000000000000015');
T('2', '-2');
T('-44', '44');
T('-1.3928', '1.3928');
T('18811.4', '-18811.4');
T('6.6', '-6.6');
T('1.99', '-1.99');
T('-6.6496e-14', '0.000000000000066496');
T('27.184', '-27.184');
T('0.00007614', '-0.00007614');
T('5478', '-5478.0');
T('-30.6432', '30.6432');
T('-108', '108');
T('-1', '1');
T('-61', '61');
T('4', '-4');
T('-0.032192', '0.032192');
T('2.6e-8', '-0.000000026');
BigNumber.config({EXPONENTIAL_AT : 0});
T('-5.0600621890668482322956892808849303e+20', '5.0600621890668482322956892808849303e+20');
T('7e+0', '-7e+0');
T('-6.1095374220609e+13', '6.1095374220609e+13');
T('9.01e+2', '-9.01e+2');
T('-1.016984074247269470395836690098169093010136836967e+39', '1.016984074247269470395836690098169093010136836967e+39');
T('-1.497639134680472576e+18', '1.497639134680472576e+18');
T('-4.1717657571404248e+16', '4.1717657571404248e+16');
T('8.983272e+1', '-8.983272e+1');
T('-5.308416e+6', '5.308416e+6');
T('-2.09764e+3', '2.09764e+3');
T('-3.83432050166120236679168e+23', '3.83432050166120236679168e+23');
T('-4.096e+3', '4.096e+3');
T('2.679971527468745095582058350756311201706813294321409e+51', '-2.679971527468745095582058350756311201706813294321409e+51');
T('-5.067853299870089529116832768e+2', '5.067853299870089529116832768e+2');
T('-3.48822062687911109850066182676769e+32', '3.48822062687911109850066182676769e+32');
T('-1e+0', '1e+0');
T('4.2773e+0', '-4.2773e+0');
T('5.8169306081172252508071119604378757744768e+12', '-5.8169306081172252508071119604378757744768e+12');
T('-1e+0', '1e+0');
T('1.51655708279450944384385164853883404204414169862685507e+46', '-1.51655708279450944384385164853883404204414169862685507e+46');
T('-8.1e+1', '8.1e+1');
T('-1.296e+3', '1.296e+3');
T('-2.9e+0', '2.9e+0');
T('-1.764e+3', '1.764e+3');
T('9.3418332730097368870513138581415704704611459349313e+49', '-9.3418332730097368870513138581415704704611459349313e+49');
T('-Infinity', Infinity);
T('-Infinity', 'Infinity');
T('Infinity', -Infinity);
T('Infinity', '-Infinity');
T('NaN', NaN);
T('NaN', 'NaN');
BigNumber.config({EXPONENTIAL_AT : 1e+9});
assert(-1, new BigNumber(2).neg().s);
assert(1, new BigNumber(-2).neg().s);
assert(null, new BigNumber(NaN).neg().s);
assert(null, new BigNumber('-NaN').neg().s);
assert(-1, new BigNumber(Infinity).neg().s);
assert(1, new BigNumber('-Infinity').neg().s);
assert(false, isMinusZero(new BigNumber(1).neg()));
assert(true, isMinusZero(new BigNumber(0).neg()));
assert(true, isMinusZero(new BigNumber(0).neg()));
assert(true, isMinusZero(new BigNumber('0.00000').neg()));
assert(true, isMinusZero(new BigNumber('+0.0').neg()));
assert(false, isMinusZero(new BigNumber(-0).neg()));
assert(false, isMinusZero(new BigNumber('-0').neg()));
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
+361
View File
@@ -0,0 +1,361 @@
var count = (function others(BigNumber) {
var start = +new Date(),
log,
error,
n,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
log('\n Testing others...');
/*
*
* isFinite
* isNaN
* isNegative
* isZero
* equals
* greaterThan
* greaterThanOrEqualTo
* lessThan
* lessThanOrEqualTo
* valueOf
*
*/
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
EXPONENTIAL_AT : 1e+9,
RANGE : 1e+9,
ERRORS : true
});
n = new BigNumber(1);
assert(true, n.isFinite());
assert(false, n.isNaN());
assert(false, n.isNegative());
assert(false, n.isZero());
assert(true, n.equals(n));
assert(true, n.equals(n, 2));
assert(true, n.equals(1, 3));
assert(true, n.equals(n, 4));
assert(true, n.equals(1, 5));
assert(true, n.equals(n, 6));
assert(true, n.equals(1, 7));
assert(true, n.equals(n, 8));
assert(true, n.equals(1, 9));
assert(true, n.equals(n, 10));
assert(true, n.equals(n, 11));
assert(true, n.equals(1, 12));
assert(true, n.equals(n, 13));
assert(true, n.equals(1, 14));
assert(true, n.equals(n, 15));
assert(true, n.equals(1, 16));
assert(true, n.equals(n, 17));
assert(true, n.equals(1, 18));
assert(true, n.equals(n, 19));
assert(true, n.equals('1.0', 20));
assert(true, n.equals('1.00', 21));
assert(true, n.equals('1.000', 22));
assert(true, n.equals('1.0000', 23));
assert(true, n.equals('1.00000', 24));
assert(true, n.equals('1.000000', 25));
assert(true, n.equals(new BigNumber(1, 10), 26));
assert(true, n.equals(new BigNumber(1), 27));
assert(true, n.equals(1, 28));
assert(true, n.equals(1, 29));
assert(true, n.equals(1, 30));
assert(true, n.equals(1, 31));
assert(true, n.equals(1, 32));
assert(true, n.equals(1, 33));
assert(true, n.equals(1, 34));
assert(true, n.equals(1, 35));
assert(true, n.equals(1, 36));
assert(true, n.greaterThan(0.99999));
assert(false, n.greaterThanOrEqualTo(1.1));
assert(true, n.lessThan(1.001));
assert(true, n.lessThanOrEqualTo(2));
assert(n.toString(), n.valueOf());
n = new BigNumber('-0.1');
assert(true, n.isF());
assert(false, n.isNaN());
assert(true, n.isNeg());
assert(false, n.isZ());
assert(false, n.equals(0.1));
assert(false, n.greaterThan(-0.1));
assert(true, n.greaterThanOrEqualTo(-1));
assert(true, n.lessThan(-0.01));
assert(false, n.lessThanOrEqualTo(-1));
assert(n.toString(), n.valueOf());
n = new BigNumber(Infinity);
assert(false, n.isFinite());
assert(false, n.isNaN());
assert(false, n.isNegative());
assert(false, n.isZero());
assert(true, n.eq('Infinity'));
assert(true, n.eq(1/0));
assert(true, n.gt('9e999'));
assert(true, n.gte(Infinity));
assert(false, n.lt(Infinity));
assert(true, n.lte(Infinity));
assert(n.toString(), n.valueOf());
n = new BigNumber('-Infinity');
assert(false, n.isF());
assert(false, n.isNaN());
assert(true, n.isNeg());
assert(false, n.isZ());
assert(false, n.equals(Infinity));
assert(true, n.equals(-1/0));
assert(false, n.greaterThan(-Infinity));
assert(true, n.greaterThanOrEqualTo('-Infinity', 8));
assert(true, n.lessThan(0));
assert(true, n.lessThanOrEqualTo(Infinity));
assert(n.toString(), n.valueOf());
n = new BigNumber('0.0000000');
assert(true, n.isFinite());
assert(false, n.isNaN());
assert(false, n.isNegative());
assert(true, n.isZero());
assert(true, n.eq(-0));
assert(true, n.gt(-0.000001)); // 81
assert(false, n.gte(0.1));
assert(true, n.lt(0.0001));
assert(true, n.lte(-0));
assert(n.toString(), n.valueOf());
n = new BigNumber(-0);
assert(true, n.isF());
assert(false, n.isNaN());
assert(true, n.isNeg());
assert(true, n.isZ());
assert(true, n.equals('0.000'));
assert(true, n.greaterThan(-1));
assert(false, n.greaterThanOrEqualTo(0.1));
assert(false, n.lessThan(0));
assert(false, n.lessThan(0, 36));
assert(true, n.lessThan(0.1));
assert(true, n.lessThanOrEqualTo(0));
assert(n.toString(), n.valueOf());
n = new BigNumber('NaN');
assert(false, n.isFinite());
assert(true, n.isNaN());
assert(false, n.isNegative());
assert(false, n.isZero());
assert(false, n.eq(NaN));
assert(false, n.eq(Infinity));
assert(false, n.gt(0));
assert(false, n.gte(0)); // 103
assert(false, n.lt(1));
assert(false, n.lte(-0));
assert(false, n.lte(-1));
assert(n.toString(), n.valueOf());
BigNumber.config({ ERRORS : false });
n = new BigNumber('hiya');
assert(false, n.isFinite());
assert(true, n.isNaN());
assert(false, n.isNegative());
assert(false, n.isZero());
assert(false, n.equals(0));
assert(false, n.greaterThan(0));
assert(false, n.greaterThanOrEqualTo(-Infinity));
assert(false, n.lessThan(Infinity));
assert(false, n.lessThanOrEqualTo(0));
assert(n.toString(), n.valueOf());
BigNumber.config({ ERRORS : true });
n = new BigNumber('-1.234e+2');
assert(true, n.isF());
assert(false, n.isNaN());
assert(true, n.isNeg());
assert(false, n.isZ());
assert(true, n.eq(-123.4, 10));
assert(true, n.gt('-ff', 16));
assert(true, n.gte('-1.234e+3'));
assert(true, n.lt(-123.39999));
assert(true, n.lte('-123.4e+0'));
assert(n.toString(), n.valueOf());
n = new BigNumber('5e-200');
assert(true, n.isFinite());
assert(false, n.isNaN());
assert(false, n.isNegative());
assert(false, n.isZero());
assert(true, n.equals(5e-200));
assert(true, n.greaterThan(5e-201));
assert(false, n.greaterThanOrEqualTo(1));
assert(true, n.lessThan(6e-200));
assert(true, n.lessThanOrEqualTo(5.1e-200));
assert(n.toString(), n.valueOf());
n = new BigNumber('1');
assert(true, n.equals(n));
assert(true, n.equals(n.toS()));
assert(true, n.equals(n.toString()));
assert(true, n.equals(n.valueOf()));
assert(true, n.equals(n.toFixed()));
assert(true, n.equals(1));
assert(true, n.equals('1e+0'));
assert(false, n.equals(-1));
assert(false, n.equals(0.1));
BigNumber.config({ ERRORS : false });
assert(false, new BigNumber(NaN).equals(0));
assert(false, new BigNumber(null).equals(0));
assert(false, new BigNumber(undefined).equals(0));
assert(false, new BigNumber(Infinity).equals(0));
assert(false, new BigNumber([]).equals(0));
assert(false, new BigNumber([]).equals(0));
assert(false, new BigNumber({}).equals(0));
assert(false, new BigNumber('').equals(0));
assert(false, new BigNumber(' ').equals(0));
assert(false, new BigNumber('\t').equals(0));
assert(false, new BigNumber('gerg').equals(0));
assert(false, new BigNumber(new Date).equals(0));
assert(false, new BigNumber(new RegExp).equals(0));
assert(false, new BigNumber(0.1).equals(0));
assert(false, new BigNumber(1e9 + 1).equals(1e9));
assert(false, new BigNumber(1e9 - 1).equals(1e9));
assert(true, new BigNumber(1e9 + 1).equals(1e9 + 1));
assert(true, new BigNumber(1).equals(1));
assert(false, new BigNumber(1).equals(-1));
assert(false, new BigNumber(NaN).equals('efffe'));
assert(false, new BigNumber('b').greaterThan('a'));
assert(false, new BigNumber('a').lessThan('b', 10));
assert(true, new BigNumber('a', 16).lessThanOrEqualTo('ff', 16));
assert(true, new BigNumber('b', 16).greaterThanOrEqualTo(9, 16));
BigNumber.config({ ERRORS : true });
assert(true, new BigNumber(10).greaterThan(10, 2));
assert(true, new BigNumber(10).greaterThan(10, 3));
assert(true, new BigNumber(10).greaterThan(10, 4));
assert(true, new BigNumber(10).greaterThan(10, 5));
assert(true, new BigNumber(10).greaterThan(10, 6));
assert(true, new BigNumber(10).greaterThan(10, 7));
assert(true, new BigNumber(10).greaterThan(10, 8));
assert(true, new BigNumber(10).greaterThan(10, 9));
assert(false, new BigNumber(10).greaterThan(10, 10));
assert(false, new BigNumber(10).greaterThan(10, 11));
assert(false, new BigNumber(10).greaterThan(10, 12));
assert(false, new BigNumber(10).greaterThan(10, 13));
assert(true, new BigNumber(10).lessThan(10, 11));
assert(true, new BigNumber(10).lessThan(10, 12));
assert(true, new BigNumber(10).lessThan(10, 13));
assert(true, new BigNumber(10).lessThan(10, 14));
assert(true, new BigNumber(10).lessThan(10, 15));
assert(true, new BigNumber(10).lessThan(10, 16));
assert(true, new BigNumber(10).lessThan(10, 17));
assert(true, new BigNumber(10).lessThan(10, 18));
assert(true, new BigNumber(10).lessThan(10, 19));
assert(true, new BigNumber(10).lessThan(10, 20));
assert(true, new BigNumber(10).lessThan(10, 21));
assert(true, new BigNumber(10).lessThan(10, 22));
assert(true, new BigNumber(10).lessThan(10, 34));
assert(true, new BigNumber(10).lessThan(10, 35));
assert(true, new BigNumber(10).lessThan(10, 36));
assert(false, new BigNumber(NaN).lessThan(NaN));
assert(false, new BigNumber(Infinity).lessThan(-Infinity));
assert(false, new BigNumber(Infinity).lessThan(Infinity));
assert(true, new BigNumber(Infinity, 10).lessThanOrEqualTo(Infinity, 2));
assert(false, new BigNumber(NaN).greaterThanOrEqualTo(NaN));
assert(true, new BigNumber(Infinity).greaterThanOrEqualTo(Infinity));
assert(true, new BigNumber(Infinity).greaterThanOrEqualTo(-Infinity));
assert(false, new BigNumber(NaN).greaterThanOrEqualTo(-Infinity));
assert(true, new BigNumber(-Infinity).greaterThanOrEqualTo(-Infinity));
assert(false, new BigNumber(2, 10).greaterThan(10, 2));
assert(false, new BigNumber(10, 2).lessThan(2, 10));
assert(true, new BigNumber(255).lessThanOrEqualTo('ff', 16));
assert(true, new BigNumber('a', 16).greaterThanOrEqualTo(9, 16));
assert(false, new BigNumber(0).lessThanOrEqualTo('NaN'));
assert(false, new BigNumber(0).greaterThanOrEqualTo(NaN));
assert(false, new BigNumber(NaN, 2).lessThanOrEqualTo('NaN', 36));
assert(false, new BigNumber(NaN, 36).greaterThanOrEqualTo(NaN, 2));
assert(false, new BigNumber(0).lessThanOrEqualTo(-Infinity));
assert(true, new BigNumber(0).greaterThanOrEqualTo(-Infinity));
assert(true, new BigNumber(0).lessThanOrEqualTo('Infinity', 36));
assert(false, new BigNumber(0).greaterThanOrEqualTo('Infinity', 36));
assert(false, new BigNumber(10).lessThanOrEqualTo(20, 4));
assert(true, new BigNumber(10).lessThanOrEqualTo(20, 5));
assert(false, new BigNumber(10).greaterThanOrEqualTo(20, 6));
assert(false, new BigNumber(1.23001e-2).lessThan(1.23e-2));
assert(true, new BigNumber(1.23e-2).lt(1.23001e-2));
assert(false, new BigNumber(1e-2).lessThan(9.999999e-3));
assert(true, new BigNumber(9.999999e-3).lt(1e-2));
assert(false, new BigNumber(1.23001e+2).lessThan(1.23e+2));
assert(true, new BigNumber(1.23e+2).lt(1.23001e+2));
assert(true, new BigNumber(9.999999e+2).lessThan(1e+3));
assert(false, new BigNumber(1e+3).lt(9.9999999e+2));
assert(false, new BigNumber(1.23001e-2).lessThanOrEqualTo(1.23e-2));
assert(true, new BigNumber(1.23e-2).lte(1.23001e-2));
assert(false, new BigNumber(1e-2).lessThanOrEqualTo(9.999999e-3));
assert(true, new BigNumber(9.999999e-3).lte(1e-2));
assert(false, new BigNumber(1.23001e+2).lessThanOrEqualTo(1.23e+2));
assert(true, new BigNumber(1.23e+2).lte(1.23001e+2));
assert(true, new BigNumber(9.999999e+2).lessThanOrEqualTo(1e+3));
assert(false, new BigNumber(1e+3).lte(9.9999999e+2));
assert(true, new BigNumber(1.23001e-2).greaterThan(1.23e-2));
assert(false, new BigNumber(1.23e-2).gt(1.23001e-2));
assert(true, new BigNumber(1e-2).greaterThan(9.999999e-3));
assert(false, new BigNumber(9.999999e-3).gt(1e-2));
assert(true, new BigNumber(1.23001e+2).greaterThan(1.23e+2));
assert(false, new BigNumber(1.23e+2).gt(1.23001e+2));
assert(false, new BigNumber(9.999999e+2).greaterThan(1e+3));
assert(true, new BigNumber(1e+3).gt(9.9999999e+2));
assert(true, new BigNumber(1.23001e-2).greaterThanOrEqualTo(1.23e-2));
assert(false, new BigNumber(1.23e-2).gte(1.23001e-2));
assert(true, new BigNumber(1e-2).greaterThanOrEqualTo(9.999999e-3));
assert(false, new BigNumber(9.999999e-3).gte(1e-2));
assert(true, new BigNumber(1.23001e+2).greaterThanOrEqualTo(1.23e+2));
assert(false, new BigNumber(1.23e+2).gte(1.23001e+2));
assert(false, new BigNumber(9.999999e+2).greaterThanOrEqualTo(1e+3));
assert(true, new BigNumber(1e+3).gte(9.9999999e+2));
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+845
View File
@@ -0,0 +1,845 @@
var count = (function toExponential(BigNumber) {
var start = +new Date(),
log,
error,
undefined,
passed = 0,
total = 0;
if (typeof window === 'undefined') {
log = console.log;
error = console.error;
} else {
log = function (str) { document.body.innerHTML += str.replace('\n', '<br>') };
error = function (str) { document.body.innerHTML += '<div style="color: red">' +
str.replace('\n', '<br>') + '</div>' };
}
if (!BigNumber && typeof require === 'function') BigNumber = require('../bignumber');
function assert(expected, actual) {
total++;
if (expected !== actual) {
error('\n Test number: ' + total + ' failed');
error(' Expected: ' + expected);
error(' Actual: ' + actual);
//process.exit();
}
else {
passed++;
//log('\n Expected and actual: ' + actual);
}
}
function assertException(func, message) {
var actual;
total++;
try {
func();
} catch (e) {
actual = e;
}
if (actual && actual.name == 'BigNumber Error') {
passed++;
//log('\n Expected and actual: ' + actual);
} else {
error('\n Test number: ' + total + ' failed');
error('\n Expected: ' + message + ' to raise a BigNumber Error.');
error(' Actual: ' + (actual || 'no exception'));
//process.exit();
}
}
function T(expected, value, decimalPlaces){
assert(String(expected), new BigNumber(value).toExponential(decimalPlaces));
}
log('\n Testing toExponential...');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : 1E9
});
T('1e+0', 1, undefined);
T('1.1e+1', 11, undefined);
T('1.12e+2', 112, undefined);
T('1e+0', 1, 0);
T('1e+1', 11, 0);
T('1e+2', 112, 0);
T('1.0e+0', 1, 1);
T('1.1e+1', 11, 1);
T('1.1e+2', 112, 1);
T('1.00e+0', 1, 2);
T('1.10e+1', 11, 2);
T('1.12e+2', 112, 2);
T('1.000e+0', 1, 3);
T('1.100e+1', 11, 3);
T('1.120e+2', 112, 3);
T('1e-1', 0.1, undefined);
T('1.1e-1', 0.11, undefined);
T('1.12e-1', 0.112, undefined);
T('1e-1', 0.1, 0);
T('1e-1', 0.11, 0);
T('1e-1', 0.112, 0);
T('1.0e-1', 0.1, 1);
T('1.1e-1', 0.11, 1);
T('1.1e-1', 0.112, 1);
T('1.00e-1', 0.1, 2);
T('1.10e-1', 0.11, 2);
T('1.12e-1', 0.112, 2);
T('1.000e-1', 0.1, 3);
T('1.100e-1', 0.11, 3);
T('1.120e-1', 0.112, 3);
T('-1e+0', -1, undefined);
T('-1.1e+1', -11, undefined);
T('-1.12e+2', -112, undefined);
T('-1e+0', -1, 0);
T('-1e+1', -11, 0);
T('-1e+2', -112, 0);
T('-1.0e+0', -1, 1);
T('-1.1e+1', -11, 1);
T('-1.1e+2', -112, 1);
T('-1.00e+0', -1, 2);
T('-1.10e+1', -11, 2);
T('-1.12e+2', -112, 2);
T('-1.000e+0', -1, 3);
T('-1.100e+1', -11, 3);
T('-1.120e+2', -112, 3);
T('-1e-1', -0.1, undefined);
T('-1.1e-1', -0.11, undefined);
T('-1.12e-1', -0.112, undefined);
T('-1e-1', -0.1, 0);
T('-1e-1', -0.11, 0);
T('-1e-1', -0.112, 0);
T('-1.0e-1', -0.1, 1);
T('-1.1e-1', -0.11, 1);
T('-1.1e-1', -0.112, 1);
T('-1.00e-1', -0.1, 2);
T('-1.10e-1', -0.11, 2);
T('-1.12e-1', -0.112, 2);
T('-1.000e-1', -0.1, 3);
T('-1.100e-1', -0.11, 3);
T('-1.120e-1', -0.112, 3);
T('NaN', NaN, undefined);
T('NaN', -NaN, 2);
T('Infinity', Infinity, undefined);
T('Infinity', Infinity, 10);
T('-Infinity', -Infinity, 0);
T('-Infinity', -Infinity, 1);
T('0e+0', 0, undefined);
T('0e+0', -0, undefined);
T('-5.0e-1', -0.5, 1);
T('0.00e+0', 0, 2);
T('1e+1', 11.2356, 0);
T('1.1236e+1', 11.2356, 4);
T('1.1236e-4', 0.000112356, 4);
T('-1.1236e-4', -0.000112356, 4);
T('1.12356e-4', 0.000112356, undefined);
T('-1.12356e-4', -0.000112356, undefined);
T('1.00e+0', 0.99976, 2);
T('1.00e+2', 99.9979, 2);
T('1.00e+5', '99991.27839', 2);
T('1.000e+2', '99.999', 3);
T('1.000e+7', '9999512.8', 3);
T('1.00e+9', '999702726', 2);
T('1.000e+3', '999.964717', 3);
BigNumber.config({ROUNDING_MODE : 0});
T('-5.3453435435e+8', '-53453.435435E4', undefined);
T('-8.8254658100092746334967191957167916942544e+17', '-882546581000927463.34967191957167916942543286', 40);
T('-4.794121828559674450610889008537305783490457e-9', '-0.00000000479412182855967445061088900853730578349045628396662493370334888944406719979291547717079', 42);
T('3.6149e+33', '3614844933096444884855774574994631.0106397808', 4);
T('5.582954000000000e-12', '0.000000000005582954', 15);
T('-3.88740271991885914774802363151163005925700000000000000000e-24', '-0.000000000000000000000003887402719918859147748023631511630059257', 56);
T('-6.87079645872437277236913190316306435274902613151676421e-20', '-0.00000000000000000006870796458724372772369131903163064352749026131516764202733298056929060151437', 53);
T('3.8181874087278104533737313621586530711155405443818235503358935045749888900678e+35', '381818740872781045337373136215865307.11155405443818235503358935045749888900677769535371296063', 76);
T('-7.11375441247784115059912118586189732891550e+20', '-711375441247784115059.91211858618973289154952986', 41);
T('6.5783e+24', '6578282366667302135641813.7249573246362582', 4);
T('6.000000000000000000000e-20', '0.00000000000000000006', 21);
T('-5.3799672107777e+13', '-53799672107777', 13);
T('-6.949e-23', '-0.00000000000000000000006948849870723', 3);
T('-8.073585184316705309757817e+25', '-80735851843167053097578169.623098209399637950843019109979317', 24);
T('-4.2956483e-12', '-0.0000000000042956482047751', 7);
T('-6.1162155721951440801240154580459651167830311633e+15', '-6116215572195144.0801240154580459651167830311633', 46);
T('-7.263265230767e-21', '-0.000000000000000000007263265230766073544739', 12);
T('-2.3013406115701776345891815e+18', '-2301340611570177634.5891814408272260224632', 25);
T('-6.0299793663e+30', '-6029979366232747481609455093247.705001183386474', 10);
T('-2.97544304967e+21', '-2975443049668038511693.75547178021412', 11);
T('-4.1471192639160032e+10', '-41471192639.1600315953295208128538183546', 16);
T('-3.61201776785294987e+27', '-3612017767852949869824542721.1595027189', 17);
T('-6.9983494044506115115e+17', '-699834940445061151.14676', 19);
T('-1.4580700323629245038287e+20', '-145807003236292450382.86958174', 22);
T('-8.54e+10', '-85390930743', 2);
T('-2.715269856970717e+19', '-27152698569707163435', 15);
T('-5.67681004e+20', '-567681003999187989540.627303416332508226276308449233', 8);
T('-2.06809e+27', '-2068085084336615438842661921.06985539576218546524301', 5);
T('-2.92273061370427012250925e+14', '-292273061370427.0122509240087955481845060858420928631', 23);
T('-4.3355e-17', '-0.0000000000000000433542', 4);
T('-3.491610942584e+21', '-3491610942583064798345', 12);
T('-8.701944635985129980360621e+16', '-87019446359851299.8036062002728328', 24);
T('-4.9e-10', '-0.000000000486409475991', 1);
T('-4.82125e+19', '-48212433366063403866', 5);
T('-7.95593941e-20', '-0.000000000000000000079559394098236', 8);
T('-2.00563e-10', '-0.0000000002005622924388', 5);
T('-6.9777057921142634382521825e+16', '-69777057921142634.3825218243275152606161149381', 25);
T('-8.42591e+14', '-842590769172062', 5);
T('-6.35123264409e+27', '-6351232644080754054285724566', 11);
T('-5.508835492577586495894259979e-28', '-0.00000000000000000000000000055088354925775864958942599785412', 27);
T('-2.667451876e+12', '-2667451875964', 9);
T('-6.6444610474323616283e+26', '-664446104743236162820999716', 19);
T('-2.419775049243e+12', '-2419775049242.726', 12);
T('-5.32e-18', '-0.000000000000000005319', 2);
T('-8.63030355223e-26', '-0.000000000000000000000000086303035522286938593814060049934', 11);
T('-2.5046920981956385048538613818080285657602718e+17', '-250469209819563850.48538613818080285657602717018', 43);
T('-3.78e+15', '-3779392491464393.04412843034387404882622864039', 2);
T('-3.3883802002818774e-21', '-0.0000000000000000000033883802002818773261717', 16);
T('-3.57205e+19', '-35720468100481047658.74549510716', 5);
T('-5.23810604e+18', '-5238106039196464333.4164490675655417554216049', 8);
T('-8.9851705212202749156714435676788925065e+21', '-8985170521220274915671.443567678892506483244', 37);
T('-4.8002620797467441513113e+15', '-4800262079746744.151311270846595944560084461404058322669896', 22);
T('-7.6602835119619761973713784765241687426415076035234065319212e+19', '-76602835119619761973.713784765241687426415076035234065319212', 58);
T('-5.381812197644510770977641728943e+29', '-538181219764451077097764172894.2045958494', 30);
T('-6.04171e+30', '-6041702557251805571827972925970.859227', 5);
T('-3.995516696587253269e+28', '-39955166965872532681529528721.070757896455736015403', 18);
T('-7.597966e+15', '-7597965080819292', 6);
T('-5.302339e+10', '-53023381796.8478', 6);
T('-9.02545540564356e+13', '-90254554056435.587103358700012', 14);
T('-4.90010261765297775855e+21', '-4900102617652977758549.72018756787751358174277326416937', 20);
T('-5.078904359675664732215233579164e+14', '-507890435967566.473221523357916309238214', 30);
T('-5.521012629302366870801695374639196986679745208450805993e+22', '-55210126293023668708016.9537463919698667974520845080599201807', 54);
T('-5.2937835496774926e-19', '-0.00000000000000000052937835496774925027979577384249493104941', 16);
T('-2.3554653675126963e+18', '-2355465367512696228', 16);
T('-2.891052510655698093e-17', '-0.000000000000000028910525106556980924149216708779185331', 18);
T('-3.68377e-16', '-0.0000000000000003683765961604816288244373051', 5);
T('-3.95708e+25', '-39570783738574043219687566.965221194063889914', 5);
T('-3.584456985168021826814122e-17', '-0.0000000000000000358445698516802182681412158196413726', 24);
T('-8.556316744104688591686120874555554808035e+28', '-85563167441046885916861208745.55554808034964', 39);
T('-6.02219e+18', '-6022186164465021650.884475588', 5);
T('-7.790612428288e+18', '-7790612428287383595.5394047', 12);
BigNumber.config({ROUNDING_MODE : 1});
T('0e+0', '-0.0E-0', undefined);
T('-2.856376815219143184897347685012382222462687620998915470135915e+6', '-2856376.815219143184897347685012382222462687620998915470135915511363444', 60);
T('7.75700e-24', '0.000000000000000000000007757', 5);
T('7.0e-1', '0.7', 1);
T('5.2109749078977455423107465583658126e+37', '52109749078977455423107465583658126637', 34);
T('3.631093819552528994444977110063007461579154042777868294000e-29', '0.00000000000000000000000000003631093819552528994444977110063007461579154042777868294', 57);
T('-9.893937860425888e+8', '-989393786.042588804219191', 15);
T('8.7978043622607467e+42', '8797804362260746751563912625017414439944006.5804807', 16);
T('-4.6561702764394602621e-7', '-0.000000465617027643946026213823955447791862428108248596086901464075785390015', 19);
T('-2.542770482242902215596924884302407e+8', '-254277048.224290221559692488430240765024783', 33);
T('2.70000000e-8', '0.000000027', 8);
T('-8.0291821891769794408790934252924453237e+16', '-80291821891769794.408790934252924453237503615825249362166', 37);
T('-8.05295923004057358545854771e-16', '-0.0000000000000008052959230040573585458547716514262', 26);
T('-2.786758e-21', '-0.00000000000000000000278675879025858093817787290334306', 6);
T('-8.0160835624737225803853824687641777660406527e+20', '-801608356247372258038.538246876417776604065270622886204812876', 43);
T('-7.2849054887999144694619191770897589e+27', '-7284905488799914469461919177.08975892527524', 34);
T('-7.586e-17', '-0.00000000000000007586908', 3);
T('-5.9508150933636580674249602941673984254864e+20', '-595081509336365806742.496029416739842548642249', 40);
T('-3.526911897e-18', '-0.000000000000000003526911897770082481187', 9);
T('-5.774e-22', '-0.0000000000000000000005774729035676859', 3);
T('-6.4700957007714124190210074e-13', '-0.00000000000064700957007714124190210074383', 25);
T('-5.610492e+21', '-5610492566512449795573', 6);
T('-6.015e+23', '-601556443593022914280678', 3);
T('-6.0673361553344e+11', '-606733615533.448288878', 13);
T('-3.1e+26', '-315617199368461055533962323.071668327669249', 1);
T('-9.1391079512104562032343e+24', '-9139107951210456203234346', 22);
T('-2.0441e+21', '-2044198307917443182711', 4);
T('-8.21283723216249535240085606500821783973097233e+23', '-821283723216249535240085.606500821783973097233814324', 44);
T('-6.375e+14', '-637540984314799.4', 3);
T('-2.17797482005219478530856429744726e+29', '-217797482005219478530856429744.7268928676963181', 32);
T('-3.9547e+11', '-395476721391', 4);
T('-6.8927e+21', '-6892798573971046301111', 4);
T('-6.33842141402916538926e-12', '-0.000000000006338421414029165389261335065112712777', 20);
T('-4.5727e-30', '-0.000000000000000000000000000004572725511159166', 4);
T('-7.8847457779026882221249217577974e-17', '-0.000000000000000078847457779026882221249217577974', 31);
T('-2.64916231640264927e+12', '-2649162316402.649271824', 17);
T('-1.73604404e+28', '-17360440496948254515028685124.37795415803082546457797184294', 8);
T('-8.680224985623e+16', '-86802249856236148.11694273469092873', 12);
T('-4.3e-19', '-0.00000000000000000043859841576346037715462713764211635', 1);
T('-7.68867535389098159141717105e-11', '-0.000000000076886753538909815914171710501337139', 26);
T('-5.24325038611090505928389422325001606e+21', '-5243250386110905059283.894223250016067979080420266', 35);
T('-1.38e-21', '-0.0000000000000000000013874592057586367688528204069850262406', 2);
T('-7.308601949094508589445770582074109410615037e+24', '-7308601949094508589445770.5820741094106150373221910779', 42);
T('-3.2638e+13', '-32638405387645.3309565877781780222317335852159983', 4);
T('-3.55454737448094719019291183206515059962378e+22', '-35545473744809471901929.118320651505996237856336054914', 41);
T('-5.3906242252792e-11', '-0.00000000005390624225279268530907215395611', 13);
T('-8.86760873811213105078e+15', '-8867608738112131.050787', 20);
T('-4.78129254835567e-23', '-0.00000000000000000000004781292548355671480462711435866243551', 14);
T('-6.4694208834502691835879021438795583630205e-19', '-0.00000000000000000064694208834502691835879021438795583630205', 40);
T('-9.324e-25', '-0.00000000000000000000000093242969', 3);
T('-6.922220589076408182786e+19', '-69222205890764081827.8655148459740694252038421', 21);
T('-4.193207546161458e+19', '-41932075461614585862.215078', 15);
T('-7.98e+20', '-798827417648620333729.80696458197', 2);
T('-2.53e-27', '-0.0000000000000000000000000025361014542495516754818606153', 2);
T('-1.4930677606201e-20', '-0.0000000000000000000149306776062013560263804', 13);
T('-2.4385708957357e+19', '-24385708957357294486.03887038886025345320045340124898971786', 13);
T('-2.3170650157672525597815028610843e+18', '-2317065015767252559.781502861084367708776250552', 31);
T('-6.9178198e+18', '-6917819884210952360.76327902290237387108459707859893972', 7);
T('-5.8557793e-24', '-0.000000000000000000000005855779377', 7);
T('-2.9760848e-12', '-0.00000000000297608486674725722', 7);
T('-5.994209456542723342157e+23', '-599420945654272334215750.2697081334512770109182770472941827', 21);
T('-2.176318765141873189550724e+24', '-2176318765141873189550724', 24);
T('-3.015068240172763167642991583362591462e+17', '-301506824017276316.76429915833625914624', 36);
T('-4.092360120459492827213341546580282588568024330771e+25', '-40923601204594928272133415.465802825885680243307714368088538', 48);
T('-1.241037736e-28', '-0.00000000000000000000000000012410377364', 9);
BigNumber.config({ROUNDING_MODE : 2});
T('0e+0', '0E0000000000', undefined);
T('0e+0', '-0E01', undefined);
T('0.00e+0', '-0E00000000001', 2);
T('3.0465655253692145345165166442116e-14', '0.0000000000000304656552536921453451651664421156', 31);
T('9.0573943842008592406279608542923313381394286641978907203396551e+22', '90573943842008592406279.60854292331338139428664197890720339655043720040907662489784', 61);
T('-1.17181502970008783734855040984899000e-1', '-0.117181502970008783734855040984899', 35);
T('-5.28860565e-16', '-0.00000000000000052886056528317233012115396784629214632', 8);
T('6.4114675970838738000e-18', '0.0000000000000000064114675970838738', 19);
T('8.00000000000000000000e-20', '0.00000000000000000008', 20);
T('2.74000064578288771723078597711103520450391668117802304078152085625023633681179e+24', '2740000645782887717230785.977111035204503916681178023040781520856250236336811781347278', 77);
T('8.1936742669491704846805837777816457628e-16', '0.00000000000000081936742669491704846805837777816457628', 37);
T('-7.2157448e+14', '-721574484716710.00141299844961546', 7);
T('-5.321807464703650000000e-15', '-0.00000000000000532180746470365', 21);
T('-4.449e+27', '-4449471658582621135143349142.228707647170080816912435271162', 3);
T('-4.922915821313919623758e+19', '-49229158213139196237.584', 21);
T('-6.996668225774098e-14', '-0.000000000000069966682257740984029052', 15);
T('-8.6856039174822133942616012424795168e+11', '-868560391748.2213394261601242479516861829472792', 34);
T('-8.461e+21', '-8461810373307862460504', 3);
T('-3.898716627703194625824411967e+25', '-38987166277031946258244119.67718', 27);
T('-2.821935496755e+26', '-282193549675582402670759843.23655', 12);
T('-3.49e-22', '-0.0000000000000000000003491662482987', 2);
T('-3.362111778576231615366457333e-14', '-0.0000000000000336211177857623161536645733316587527475522615', 27);
T('-5.9933e-13', '-0.00000000000059933412636903331', 4);
T('-2.77927721e+29', '-277927721100404435781172100113.4136636412460458083951', 8);
T('-1.876833722329e-10', '-0.0000000001876833722329987477942', 12);
T('-6.5e+14', '-653341175209856', 1);
T('-8.627291840173867961e+14', '-862729184017386.7961', 18);
T('-3.9137457165597668391301218029e-11', '-0.00000000003913745716559766839130121802935022889', 28);
T('-8.95e+10', '-89532775488', 2);
T('-2.1395541875015568986238e-17', '-0.000000000000000021395541875015568986238771696', 22);
T('-4.98575853353890809143399546448630559732119628e-12', '-0.00000000000498575853353890809143399546448630559732119628509', 44);
T('-8.99e+16', '-89989591559494822', 2);
T('-3.49346327e+22', '-34934632714180035424463', 8);
T('-3.5699537605753905457597e-14', '-0.00000000000003569953760575390545759785014980652333323889116', 22);
T('-2.9892536880349975618286e+12', '-2989253688034.9975618286212199904979534461637613', 22);
T('-3.04383919217904949618e+10', '-30438391921.790494961888803732171', 20);
T('-8.232411544e+17', '-823241154405701456', 9);
T('-5.809151226990464016815e-16', '-0.00000000000000058091512269904640168152354', 21);
T('-8.522042397326932431e+13', '-85220423973269.324312660179132118', 18);
T('-7.5210942e-22', '-0.000000000000000000000752109428925015', 7);
T('-5.2018321449543e+23', '-520183214495439298725191.09', 13);
T('-6.04084045453711395629268198016245611021901815e+21', '-6040840454537113956292.68198016245611021901815486929628647', 44);
T('-1.495478178996755138125934544343674798e-13', '-0.00000000000014954781789967551381259345443436747983317353423', 36);
T('-6.881484497510733524151245220630282259985306546537e+16', '-68814844975107335.241512452206302822599853065465371507616758', 48);
T('-4.7121389019956e-14', '-0.00000000000004712138901995619', 13);
T('-8.8332728504053108443425344711e-15', '-0.00000000000000883327285040531084434253447119282', 28);
T('-8.2e+14', '-822000812447305', 1);
T('-7.772164697477093877214551050634072755e+21', '-7772164697477093877214.55105063407275517068350805', 36);
T('-3.9087122838427126623505550357872e+10', '-39087122838.4271266235055503578721071128', 31);
T('-2.312032777966762704192668904908578897e+20', '-231203277796676270419.266890490857889726891117', 36);
T('-6.145717261905789834140342e+10', '-61457172619.0578983414034269108488849155084479', 24);
T('-1.22122395777234009028954105999904e+23', '-122122395777234009028954.10599990431', 32);
T('-8.11092557e-19', '-0.000000000000000000811092557221182808185409783', 8);
T('-2.0148183904e+12', '-2014818390421', 10);
T('-8.5895e+12', '-8589543094837', 4);
T('-4.52948430169449249063e+13', '-45294843016944.92490631367483828208567689248', 20);
T('-5.5627328016242253171e+18', '-5562732801624225317.15482034912', 19);
T('-2.299e+22', '-22994771657263381474221.8393766046648504992', 3);
T('-4.886104291748549e+15', '-4886104291748549.177', 15);
T('-3.7192656464776e-11', '-0.00000000003719265646477604172611', 13);
T('-6.135956620537e+25', '-61359566205370067856449153.5', 12);
T('-3.35703853285800120218674208960269655701e-14', '-0.000000000000033570385328580012021867420896026965570155917', 38);
T('-8.713884178791321311224703e+22', '-87138841787913213112247.03564225163096', 24);
T('-7.073358e+12', '-7073358766762', 6);
T('-6.829e+30', '-6829360758600890577632541121747.862424035', 3);
T('-3.05687463293e+22', '-30568746329329110731433.300963185825462157574537899186', 11);
T('-8.761781e+24', '-8761781624975891699172893.0141633817001124644', 6);
T('-1.477e+12', '-1477134517234.0307742', 3);
T('-5.78904078729758522168774487851811e+16', '-57890407872975852.216877448785181168776187771353947582', 32);
T('-7.74939714942520320266429137e+12', '-7749397149425.20320266429137053013', 26);
T('-8.3224649681672648581370532515e-14', '-0.00000000000008322464968167264858137053251586527433370546682', 28);
T('-7.04146154016765195683657078079536e-22', '-0.000000000000000000000704146154016765195683657078079536', 32);
T('-1.914289454756549529781861916925090389e+16', '-19142894547565495.29781861916925090389840210707205', 36);
T('-8.840670154325523051759462672e+27', '-8840670154325523051759462672.142803216', 27);
T('-2.823e-11', '-0.00000000002823852806134378210195515771768582269146178698', 3);
T('-1.5186417607496557534159723950506e+29', '-151864176074965575341597239505.06547275781526923', 31);
T('-7.397218e+16', '-73972184449181471.152912157', 6);
T('-3.581193819284374099989e+22', '-35811938192843740999895.1573225646377886389016478830802218237', 21);
T('-4.563585432210043885759681337791545e+29', '-456358543221004388575968133779.154510217739887576756399', 33);
T('-1.8176465832459836335875e-18', '-0.0000000000000000018176465832459836335875559', 22);
T('-3.784854627631e+20', '-378485462763141736445.9462626829154663', 12);
T('-3.8510536744200399243363367786406618e+23', '-385105367442003992433633.6778640661831754293129488068676868', 34);
T('-8.7323e+22', '-87323916569164596208111.88101028771355420576029037973', 4);
T('-7.578e+11', '-757882758255.76', 3);
T('-8.5977102122033e+20', '-859771021220338061040.041580289025031', 13);
T('-7.3998697893908579137880913e+17', '-739986978939085791.37880913509684330685', 25);
T('-6.71117252123290052432148305375254e-19', '-0.00000000000000000067111725212329005243214830537525418', 32);
T('-6.6762993760195471322427204620426381935201299178096e+11', '-667629937601.9547132242720462042638193520129917809665', 49);
T('-2.852022020015364818597602e+15', '-2852022020015364.818597602673413917443', 24);
T('-3.151044e+30', '-3151044929117854676102403114231.56823295246', 6);
T('-4.47120537692951873038916592e+10', '-44712053769.29518730389165927694', 26);
T('-7.4041969e+23', '-740419699691346150775964.049522110341852844412207474667958', 7);
T('-6.311838e-10', '-0.000000000631183849892543191', 6);
T('-7.2570104326587672213e+16', '-72570104326587672.213076838263780308795144628367752', 19);
T('-4.445769230869049803541e+15', '-4445769230869049.80354196820931591782233498498378174385', 21);
BigNumber.config({ROUNDING_MODE : 3});
T('-9.99999999000000009e+8', '-999999999.000000009e-0', undefined);
T('-3.99764422903251220452704763278376060858663250289320247532595e+24', '-3997644229032512204527047.63278376060858663250289320247532594416986984981431156065660613', 59);
T('5.534083545686157907280686578717428772e+12', '5534083545686.157907280686578717428772', 36);
T('5.00000000e-9', '0.000000005', 8);
T('-4.08363116583051e+14', '-408363116583051', 14);
T('9.278230415634296945273818e+19', '92782304156342969452.738186255580532649103987374718221928871873054827841260470670536425', 24);
T('-1.08732508998603085454662e-12', '-0.000000000001087325089986030854546619968259691229662152159029641023997866843605032534351388775075', 23);
T('3.5288804517377606688698e+32', '352888045173776066886981811418233.218955856086', 22);
T('4.32188781438877554e+16', '43218878143887755.42593887518334667202', 17);
T('-8.15e+2', '-815', 2);
T('1.515077312590223222678749527e+18', '1515077312590223222.678749527895871363186918977679783240817218232896076765321818445939718165', 27);
T('-8.0538186421664536509917032729912932814374102e+20', '-805381864216645365099.17032729912932814374101821', 43);
T('-3.4367097301002099047381e+14', '-343670973010020.990473804391071456587732173', 22);
T('-5.3421e-12', '-0.0000000000053420288504', 4);
T('-2.6320052e+23', '-263200517731973006983184.60341959097016190770542276', 7);
T('-4.5e-11', '-0.000000000044673422483', 1);
T('-7.232463101115829118145025733451801e-17', '-0.00000000000000007232463101115829118145025733451800457178', 33);
T('-1.18320100044154762448545914170978206041022039e+22', '-11832010004415476244854.5914170978206041022038489', 44);
T('-7.745237371276392645711e+21', '-7745237371276392645710.0521930569226728841707200771', 21);
T('-4.431559500053255695643e-10', '-0.000000000443155950005325569564213010993378905', 21);
T('-2.5e-24', '-0.000000000000000000000002443', 1);
T('-5.005027028439023958391203127005503621542e-11', '-0.0000000000500502702843902395839120312700550362154137', 39);
T('-6.453525377934213334367e-22', '-0.00000000000000000000064535253779342133343665123283565', 21);
T('-4.5594370326121718626850982373529e+13', '-45594370326121.71862685098237352845979966987', 31);
T('-1.709e+16', '-17088248121660259', 3);
T('-3.9047581533864713e+16', '-39047581533864712.6574405', 16);
T('-2.08804202e-17', '-0.000000000000000020880420127397564274443250271135', 8);
T('-6.801694635944774655689008216925036e+15', '-6801694635944774.65568900821692503508025', 33);
T('-8.7691286374104240967931800593734e+19', '-87691286374104240967.93180059373367907299683816381677816389', 31);
T('-2.802257731715238453e-29', '-0.000000000000000000000000000028022577317152384526775320012', 18);
T('-4.4705e+22', '-44704405768781565005877.813010169083', 4);
T('-4.17374908496486449232e-10', '-0.00000000041737490849648644923105632500267064', 20);
T('-2.2707e-10', '-0.00000000022706134122862417334386435', 4);
T('-2.85432e-24', '-0.0000000000000000000000028543100839983854161', 5);
T('-5.79188949e+12', '-5791889489461.643555240257', 8);
T('-7.46e+15', '-7459701910718662.03421293892346992893463534702', 2);
T('-1.0535086280629e+25', '-10535086280628995915087428.2423609320023833125322801559606', 13);
T('-2.9074412651647188367106e+30', '-2907441265164718836710598468491.31550321772', 22);
T('-5.010945976711327691649e+27', '-5010945976711327691648509517.2305', 21);
T('-8.8633960213386533e-20', '-0.0000000000000000000886339602133865324283362544', 16);
T('-3.1891844834898211661452730714015664837805e+19', '-31891844834898211661.45273071401566483780434051217', 40);
T('-5.083380976014365533843229882526437e+28', '-50833809760143655338432298825.264367948359', 33);
T('-6.8e-16', '-0.000000000000000678534987604148025611184', 1);
T('-7.9e+30', '-7838656097386639584904346062976.9346038436', 1);
T('-6.30535781e+20', '-630535780834495012856', 8);
T('-9.663e-30', '-0.00000000000000000000000000000966289400023904753107633012', 3);
T('-2.315198482309e+12', '-2315198482308.7361348', 12);
T('-8.158235289416e+18', '-8158235289415958939', 12);
T('-4.1618890517404316933699206360639988582832624525e+23', '-416188905174043169336992.063606399885828326245241437', 46);
T('-5.97550716981833990839441709632e+21', '-5975507169818339908394.41709631281058258352209', 29);
T('-6.3372e-18', '-0.000000000000000006337122571683959413228', 4);
T('-8.9189088e+18', '-8918908714500548003.38400978696756078013348', 7);
T('-2.30738494e+15', '-2307384939629592.5507643557167543121437', 8);
T('-5.5187220703008771818558364e+20', '-551872207030087718185.58363308126401300424', 25);
T('-6.6221540532808e+16', '-66221540532807215', 13);
T('-7.52280140768218860970644149216497725e+28', '-75228014076821886097064414921.6497724655', 35);
T('-4.50815289e-10', '-0.0000000004508152886241127131780051700309401', 8);
T('-8.05636473909e+28', '-80563647390897795982047004786.9809587987299506647489380735', 11);
T('-8.3e-22', '-0.00000000000000000000082867896643314771124884886449603747139', 1);
T('-8.3783e+13', '-83782644902152', 4);
T('-1.1939712427296807e+16', '-11939712427296807', 16);
T('-6.520492185955083727143468903725e+24', '-6520492185955083727143468.90372469799639', 30);
T('-5.468441290352576854e+22', '-54684412903525768532358.76123265640787599117379', 18);
T('-6.3213239044187e-12', '-0.000000000006321323904418628', 13);
T('-6.80758136e+10', '-68075813559.812083737218313494618879237157412', 8);
T('-2.32394435705096500766e+20', '-232394435705096500765.423311444507670516532857314906', 20);
T('-5.35396744204815374979010975360864002355e+14', '-535396744204815.374979010975360864002354465685768494008245896', 38);
T('-1.8388340153656061115e-24', '-0.0000000000000000000000018388340153656061114681', 19);
T('-2.09349812455746e+24', '-2093498124557455120865520.476275227', 14);
T('-2.888450139093515656e-25', '-0.0000000000000000000000002888450139093515656', 18);
T('-6.97756838052316890676e+30', '-6977568380523168906759075718628.73360426401485819654038588804', 20);
T('-8.05604538646883624239398132377048820023e+24', '-8056045386468836242393981.323770488200227820839', 38);
T('-4.13045948e+29', '-413045947014551860341804907208.7067642881758676', 8);
T('-7.990552461602111454165337515e+23', '-799055246160211145416533.75144940262265224221931', 27);
T('-7.84498851993324e+11', '-784498851993.323271787115869178093231451893938531755482687806', 14);
T('-8.63875584973951951712658379e-21', '-0.000000000000000000008638755849739519517126583785754757065', 26);
T('-8.61609302272300237447639006834635e-14', '-0.00000000000008616093022723002374476390068346342187746', 32);
T('-7.01300801762e+17', '-701300801761204790.177590913310762', 11);
T('-8.0318131135482342451545e-11', '-0.0000000000803181311354823424515442372680533', 22);
T('-8.310034087753417316659936093943321e+25', '-83100340877534173166599360.9394332099174859', 33);
T('-7.716088095718838665380730070082633435173897567e+30', '-7716088095718838665380730070082.6334351738975662966', 45);
T('-6.5207000918869e-14', '-0.00000000000006520700091886862177', 13);
T('-6.579884485936605389e+14', '-657988448593660.538847871', 18);
T('-5.31961604251455760419e+30', '-5319616042514557604183392605338.36600372994596807972708', 20);
T('-7.87765329352729e+16', '-78776532935272856.77806', 14);
T('-8.23e+11', '-822427564609', 2);
T('-1.2946e+16', '-12945401038582508.297183225785515084520662225', 4);
T('-4.3885535805231634787626423119240512694696e+14', '-438855358052316.347876264231192405126946952', 40);
T('-6.4067449547192616381924351e-29', '-0.00000000000000000000000000006406744954719261638192435066816', 25);
T('-9.41834953e+18', '-9418349527156084224.2', 8);
T('-3.19716162829318952418046452988e+13', '-31971616282931.895241804645298754890905582545633', 29);
BigNumber.config({ROUNDING_MODE : 4});
T('-5.002239116605888927178702930656e-39', '-0.00000000000000000000000000000000000000500223911660588892717870293065633642', 30);
T('-8.52292947230244775435e+29', '-852292947230244775434968241532.494643593912804433318745222587246680109833509655450267792446', 20);
T('-6.1169514510867e+10', '-61169514510.8673382', 13);
T('-8.05745763527307676170759722175169266017831695215e+48', '-8057457635273076761707597221751692660178316952146', 47);
T('-4.923572102098e+10', '-49235721020.9847017846898652687600227388412980598816', 12);
T('-7.981341661715027117746906076515945e+41', '-798134166171502711774690607651594491039629', 33);
T('-8.00e-3', '-0.008', 2);
T('8.517466793430899278197016892000000000000e-15', '0.000000000000008517466793430899278197016892', 39);
T('-3.032293512e+0', '-3.0322935124071923328711934463341802038', 9);
T('-2.60682904403489305678908771323995810138267385200000000e-20', '-0.00000000000000000002606829044034893056789087713239958101382673852', 53);
T('-3.935816927273980e+20', '-393581692727398036652.850960055902271', 15);
T('-2.98297216346e-27', '-0.00000000000000000000000000298297216346039288935575576076143', 11);
T('-3.01319315e+23', '-301319315398414808376087.572306433', 8);
T('-8.870698526921188e-12', '-0.00000000000887069852692118832284144110732', 15);
T('-3.27e+23', '-326739927744903524706793.652546266488323001284674736489440831', 2);
T('-8.614e+12', '-8613828413581', 3);
T('-6.1382445990593346026804e+12', '-6138244599059.3346026803630253203', 22);
T('-7.9111971e+12', '-7911197130975', 7);
T('-8.5902152501051e+29', '-859021525010507210136559039003.689834129033952321238', 13);
T('-7.24491e-30', '-0.00000000000000000000000000000724490826045045451271534', 5);
T('-8.4948070285349193974989221504919380656715136165603325e+24', '-8494807028534919397498922.15049193806567151361656033246', 52);
T('-6.3295239596e-17', '-0.00000000000000006329523959626011114164', 10);
T('-3.1725692353e+30', '-3172569235260846783669130724638.711', 10);
T('-4.065727077e+11', '-406572707673.336570352310681187663765', 9);
T('-6.82883869249998075574247223155497e+18', '-6828838692499980755.7424722315549682855987375899188309581152', 32);
T('-2.56144400427045214943786338e+24', '-2561444004270452149437863.38354535663028539', 26);
T('-4.97637439956044400125498868e+23', '-497637439956044400125498.8682100590602459937304614141772', 26);
T('-4.307891929198702822746534506143e+29', '-430789192919870282274653450614.349564081', 30);
T('-8.55e-27', '-0.00000000000000000000000000855367295711812079', 2);
T('-7.906e+11', '-790612526329.410459220189562', 3);
T('-3.1841363e-22', '-0.00000000000000000000031841363', 7);
T('-6.2068049304845006e+20', '-620680493048450055389.3227069760888437941041', 16);
T('-8.4809476e+18', '-8480947614295114807.320148688', 7);
T('-2.287988570734255855e+23', '-228798857073425585542366.399034916953775', 18);
T('-8.148647139762925073276164486240320698e+21', '-8148647139762925073276.1644862403206980851079', 36);
T('-6.87643138785664756e-12', '-0.0000000000068764313878566475604352570287089535238582267443', 17);
T('-3.709587e+18', '-3709586618852569033.55141868', 6);
T('-6.8086794224e+28', '-68086794224433270564431694468.814537646575833889824621540849', 10);
T('-4.966301085179e+19', '-49663010851788946007', 12);
T('-5.34439184068052811184219234494114e+26', '-534439184068052811184219234.494113670484623394', 32);
T('-2.798732412e+16', '-27987324119455299', 9);
T('-1.554430791885961957e+15', '-1554430791885961.956863404519493346081223', 18);
T('-6.90619083822075003978e+24', '-6906190838220750039778836.289105048686876596', 20);
T('-1.108034176809770578315e+12', '-1108034176809.7705783154', 21);
T('-1.43e+22', '-14266566332440117777110.63461224926682073525873105', 2);
T('-9.15e+13', '-91477543307040.916791223', 2);
T('-1.1001e+26', '-110010856476508992391958436.9355559264588205214557001854', 4);
T('-1.2e+16', '-12148027447349021', 1);
T('-4.4e+13', '-44268551660889.40880208546489742632181832780494', 1);
T('-8.62058920338555484081691e+19', '-86205892033855548408.169086865949596390775', 23);
T('-5.2e-13', '-0.00000000000051876025261394172', 1);
T('-4.88063953404884862027221562057786242658496407473e-11', '-0.0000000000488063953404884862027221562057786242658496407473', 47);
T('-5.255e+18', '-5254530327311322805.9528217', 3);
T('-6.4630488003995117e-11', '-0.0000000000646304880039951167486', 16);
T('-3.15214e-23', '-0.00000000000000000000003152137339126187', 5);
T('-8.86563136e+11', '-886563136251.626990531858472111699416852', 8);
T('-8.638990742871e-16', '-0.0000000000000008638990742870608', 12);
T('-1.57817750020560815944470062e+12', '-1578177500205.60815944470062002898187', 26);
T('-3.6558384593093900422637e-27', '-0.00000000000000000000000000365583845930939004226367940618', 22);
T('-7.5e+12', '-7540535487033', 1);
T('-6.7647935206791247e+19', '-67647935206791246567', 16);
T('-3.0204818086245915027e+30', '-3020481808624591502749101182536.872936744534671794', 19);
T('-8.40498662e+12', '-8404986622734.85', 8);
T('-2.944135296894e-18', '-0.0000000000000000029441352968942548971', 12);
T('-8.826099694855290261753e+11', '-882609969485.52902617534731', 21);
T('-1.9717565867734925e-13', '-0.000000000000197175658677349252855292223369', 16);
T('-4.91451975824866130376722e+20', '-491451975824866130376.722358803861287205044883122152013315', 23);
T('-5.111649e+17', '-511164947156144375', 6);
T('-9.496473458673099e+11', '-949647345867.30987953779868637405061', 15);
T('-2.1903308925764762892e+21', '-2190330892576476289225', 19);
T('-3.47598363e+25', '-34759836338593591584288059.755482689269713', 8);
T('-2.9192144584989753156762701431e-24', '-0.0000000000000000000000029192144584989753156762701431', 28);
T('-4.0456517973466503588734928438425e+23', '-404565179734665035887349.28438424933669843', 31);
T('-1.297871549154944904150929e+17', '-129787154915494490.4150929407633398', 24);
T('-1.4566530316908752e+18', '-1456653031690875152.6306667', 16);
T('-3.5521e-12', '-0.00000000000355210483', 4);
T('-9.1838324864110351307221525161e+17', '-918383248641103513.07221525161442', 28);
T('-8.33245633316304149287131334e-22', '-0.00000000000000000000083324563331630414928713133382', 26);
T('-4.593824606634605622464043606094613988489104e+15', '-4593824606634605.62246404360609461398848910424547985108092894', 42);
T('-5.232e-26', '-0.0000000000000000000000000523185958604202852', 3);
T('-3.8319390497954462e+25', '-38319390497954461897251251.444', 16);
T('-1.00157678068191049988073716749599603712e+17', '-100157678068191049.9880737167495996037119953003896147', 38);
T('-4.169977410059689809645035174132294864e+20', '-416997741005968980964.50351741322948635363513285839302', 36);
T('-7.121660153198989278372512656775647e-11', '-0.0000000000712166015319898927837251265677564651728358', 33);
T('-7.98924570545536548623603750084330391943e+19', '-79892457054553654862.360375008433039194317394396964358522', 38);
BigNumber.config({ROUNDING_MODE : 5});
T('4.95474614815842e+38', '495474614815842191683004449862568813538.573064401156', 14);
T('-8.9667567079038139e+16', '-89667567079038139', 16);
T('-7.0e+2', '-703', 1);
T('-2.6249e+33', '-2624861185343559570287214983819906', 4);
T('-6.510119186347371697501169416839709631422185436811698613000000000000000000000000000000e-31', '-0.0000000000000000000000000000006510119186347371697501169416839709631422185436811698613', 84);
T('7.73e+3', '7729', 2);
T('1.4393781011009257793117531801549e+4', '14393.781011009257793117531801548751', 31);
T('8.4e+6', '8404542', 1);
T('8.471284625267663009248667391059202502589207637435209861233007389000000000000000e-35', '0.00000000000000000000000000000000008471284625267663009248667391059202502589207637435209861233007389', 78);
T('-5.26079297227015e+31', '-52607929722701509263909039511536.9266822991', 14);
T('-4.63550600857003551411914120562163394e+15', '-4635506008570035.51411914120562163394396594237358863897062', 35);
T('-7.8219563406482338767189100434751303552919130625101491e+27', '-7821956340648233876718910043.4751303552919130625101491', 52);
T('-6.977184098e+17', '-697718409782854734', 9);
T('-8.1e+15', '-8092701222454628.9934935902179330839653799891168', 1);
T('-3.872944373744596915691884729973e+15', '-3872944373744596.91569188472997336351132980366520033057011287', 30);
T('-1.389676e+11', '-138967565295.146055555208419143848718279114979831585', 6);
T('-2.218316993130903882223e+19', '-22183169931309038822.22612', 21);
T('-3.370809304e-25', '-0.000000000000000000000000337080930401566', 9);
T('-6.1503e+19', '-61503417721509415792.24703', 4);
T('-3.13657134e-22', '-0.00000000000000000000031365713378439345', 8);
T('-1.9e-10', '-0.000000000187981', 1);
T('-2.596508353714425677970049724e+28', '-25965083537144256779700497237.5841327343962292316215149169', 27);
T('-4.151454545748277604112308101174917062e+11', '-415145454574.827760411230810117491706171981266892178', 36);
T('-1.3e-18', '-0.000000000000000001319061308619561567664259803361817', 1);
T('-1.5294854487046553159e+24', '-1529485448704655315921667', 19);
T('-1.9365487654708143765583400538310103350799e-13', '-0.000000000000193654876547081437655834005383101033507988', 40);
T('-3.88128259276357427027515474e+25', '-38812825927635742702751547.353', 26);
T('-5.64525474904155517374289736218e-11', '-0.00000000005645254749041555173742897362182099811344', 29);
T('-8.94963385755006409131430087734467745e+22', '-89496338575500640913143.0087734467744538', 35);
T('-3.7551731901764025e+17', '-375517319017640249', 16);
T('-7.601921e-16', '-0.00000000000000076019214974360137746140339586742455753', 6);
T('-6.93501087055e+20', '-693501087055377288564', 11);
T('-1.283656440009563e+24', '-1283656440009563292695670.575360580373829197017512', 15);
T('-4.9556506e+13', '-49556505932168.7211084603', 7);
T('-8.133584588946e+26', '-813358458894586332533196788.490201803951456991010654609646', 12);
T('-3.824207296e+22', '-38242072955850210158724', 9);
T('-4.2168087e-12', '-0.00000000000421680868317080291', 7);
T('-7.152812829e+15', '-7152812829336253.782723153403637377960530795', 9);
T('-8.0469635248612874571e+16', '-80469635248612874.5712104436', 19);
T('-2.726549954018643349550392804e+11', '-272654995401.8643349550392803783934819148125595437353472547', 27);
T('-2.477986360297097033217143e+30', '-2477986360297097033217143442370.539404', 24);
T('-2.7620555408e+15', '-2762055540757162', 10);
T('-5.044e+10', '-50436788962', 3);
T('-1.51176171306898543927009427965761639e+17', '-151176171306898543.9270094279657616389483779413616294465635', 35);
T('-3.76233131039732974161231568e+13', '-37623313103973.2974161231567776787873083163171', 26);
T('-1.77876313221062362e+17', '-177876313221062362.01', 17);
T('-4.28033364715744300662536e+13', '-42803336471574.430066253616', 23);
T('-6.053e-13', '-0.00000000000060527568964627046163209582', 3);
T('-3.9447068214322315685949701607748761e+16', '-39447068214322315.685949701607748760885392781169754754427622', 34);
T('-4.76203665586552028e+15', '-4762036655865520.285', 17);
T('-7.442141482296791204320219247230530359e+24', '-7442141482296791204320219.2472305303585223494415', 36);
T('-5.96279453376966633e+23', '-596279453376966633175009.6', 17);
T('-3.393419405169789e+24', '-3393419405169788742460001.267', 15);
T('-5.3001e+12', '-5300055380607', 4);
T('-5.6075017651299255742594578e+24', '-5607501765129925574259457.7938331743229', 25);
T('-1.7016332185618e-12', '-0.000000000001701633218561829307163951183908', 13);
T('-8.2586539997288574125e-29', '-0.0000000000000000000000000000825865399972885741250631446', 19);
T('-6.867e+11', '-686673700185', 3);
T('-6.77934398386662123284e+26', '-677934398386662123284378302.457585912', 20);
T('-1.68708254641574159341563239757e+14', '-168708254641574.159341563239757201959', 29);
T('-7.969791397195291274332017902569730510486538e+16', '-79697913971952912.74332017902569730510486538476172', 42);
T('-8.35460490386e+14', '-835460490386401.159749305581999482', 11);
T('-3.4904587e+10', '-34904586685.65531405315150234636', 7);
T('-7.655476116917648649e-10', '-0.0000000007655476116917648649345', 18);
T('-3.035704337e+17', '-303570433749270293', 9);
T('-1.4902739431686400585e-18', '-0.000000000000000001490273943168640058452103113', 19);
T('-2.57617086126164572e+17', '-257617086126164572', 17);
T('-6.9708e+16', '-69708261331391628', 4);
T('-8.61400120130585599610136e-12', '-0.00000000000861400120130585599610136066', 23);
T('-9.0670988886e-19', '-0.000000000000000000906709888862126926', 10);
T('-2.889463982215818248e-26', '-0.00000000000000000000000002889463982215818248', 18);
T('-3.7376459408597195073982491e+26', '-373764594085971950739824910.4572745527', 25);
T('-6.21372353850510695881280108179e-12', '-0.0000000000062137235385051069588128010817907', 29);
T('-2.4240953581712173951958e-21', '-0.00000000000000000000242409535817121739519585', 22);
T('-8.3687559027615173415e+18', '-8368755902761517341.46477685623835786273991', 19);
T('-7.18294352e-11', '-0.0000000000718294352479105', 8);
T('-3.52454012503419773886785e-25', '-0.000000000000000000000000352454012503419773886785342913143', 23);
BigNumber.config({ROUNDING_MODE : 6});
T('-4.3502707501164e+36', '-4350270750116411997402439304498892819', 13);
T('9.5e-21', '0.0000000000000000000094520280724178734152', 1);
T('1.39631186750554172785676012693418617250072200744214625994656047727270672248243741907e+34', '13963118675055417278567601269341861.725007220074421462599465604772727067224824374190703237660781', 83);
T('5.9446570e-26', '0.00000000000000000000000005944657036540768164877637239177740419063920648', 7);
T('7.00000e-12', '0.000000000007', 5);
T('-2.87e+14', '-287060740776209.3950381715', 2);
T('3.411740542875509329e+24', '3411740542875509328514044', 18);
T('-6.20235112738687046118395830000000000000000000000e-29', '-0.000000000000000000000000000062023511273868704611839583', 47);
T('2.94349130121570276626863135396717336528655493e+19', '29434913012157027662.686313539671733652865549279174', 44);
T('4.01255076512828067130306533670644537832e-10', '0.000000000401255076512828067130306533670644537831678294548', 38);
T('-5.4277306444432e+11', '-542773064444.317654960431120452254700391693837992', 13);
T('-4.355706886680889557797360814402e+30', '-4355706886680889557797360814401.536556745674646509159280626', 30);
T('-1.29e-15', '-0.00000000000000128978312277001609181774216296380783932', 2);
T('-1.0588973816292989769e+25', '-10588973816292989768709129.1767038708798755780352204', 19);
T('-3.210569596e+10', '-32105695962.8803639621', 9);
T('-7.18504270173744681360682714959e+28', '-71850427017374468136068271495.87', 29);
T('-4.29794333519778779150824479010034817077204e-10', '-0.0000000004297943335197787791508244790100348170772040392', 41);
T('-4.615682142828269066227773895179987062919e+20', '-461568214282826906622.7773895179987062919071922', 39);
T('-1.3864477517287155526073e+13', '-13864477517287.15552607265', 22);
T('-6.793120028e+13', '-67931200280922.72252141789646787475433427482', 9);
T('-8.075e-18', '-0.000000000000000008074975073002274636799975', 3);
T('-8.360228691054180854419062530687032074820667001e+24', '-8360228691054180854419062.530687032074820667001120752628', 45);
T('-3.0763956760417194035216e-12', '-0.000000000003076395676041719403521594', 22);
T('-2.5288383e+25', '-25288383009460922631988717.84659997837058450749', 7);
T('-4.554185192e+29', '-455418519247311560996997520087.98189', 9);
T('-9.135175372324138467397264e+11', '-913517537232.413846739726417', 24);
T('-8.257259383044471855222900534859251889332388855848e-10', '-0.0000000008257259383044471855222900534859251889332388855848', 48);
T('-7.651597268450922707e-13', '-0.000000000000765159726845092270720405167100094', 18);
T('-8.952011763950994514e+26', '-895201176395099451377549961.34870447', 18);
T('-2.7395479569618982298152060567357e-10', '-0.00000000027395479569618982298152060567357', 31);
T('-1.31151451700453378841431e+24', '-1311514517004533788414313', 23);
T('-5.915297930316863891e-10', '-0.0000000005915297930316863890707686339684395', 18);
T('-1.449e-27', '-0.0000000000000000000000000014487033279693402845128265141859', 3);
T('-3.7e+10', '-36919550406.826974442743517918128', 1);
T('-3.945347688940382499631779106638865e+13', '-39453476889403.824996317791066388653', 33);
T('-8.547704e-29', '-0.0000000000000000000000000000854770378842608635356', 6);
T('-3.76e+25', '-37618296325402619735777629.467812385256281737441412', 2);
T('-8.031066086398624e+28', '-80310660863986235667567286452', 15);
T('-4.038276256088135496e-17', '-0.000000000000000040382762560881354955896694823328777602811', 18);
T('-1.77173574740860868e+25', '-17717357474086086837250852', 17);
T('-1.421967649e+21', '-1421967648805122645888', 9);
T('-4.7e+11', '-469485715327', 1);
T('-7.372223291560455075681748682810527006883e+16', '-73722232915604550.75681748682810527006882666313809409', 39);
T('-8.9539396357e+14', '-895393963565598', 10);
T('-8.14646103854802172250414801405e+10', '-81464610385.48021722504148014045579178726', 29);
T('-1.2053415734425581e+12', '-1205341573442.5581371841633131879', 16);
T('-8.35214176861046133596101313170854966756043001e+28', '-83521417686104613359610131317.0854966756043001041619492', 44);
T('-3.7610694152e-28', '-0.00000000000000000000000000037610694151517628351', 10);
T('-6.71e-12', '-0.00000000000670729337105720320122353', 2);
T('-4.005517304396006251e+13', '-40055173043960.0625088492324182094858', 18);
T('-6.0206e+28', '-60205974155921075891080012488.4566490314762809', 4);
T('-6.36287561326e+11', '-636287561325.9124444291802472', 11);
T('-3.11336117e-16', '-0.000000000000000311336117052129384933053792', 8);
T('-5.3927134886536e+30', '-5392713488653639958906162302264.424436642808', 13);
T('-3.82395446711276e-10', '-0.0000000003823954467112758458806849565215407952986440811', 14);
T('-4.2858082253423e-27', '-0.0000000000000000000000000042858082253422975', 13);
T('-2.9918792622984137284399075479267066e+14', '-299187926229841.3728439907547926706557', 34);
T('-3.1949909651023223034303544498737e+27', '-3194990965102322303430354449.8737', 31);
T('-9.1e-27', '-0.0000000000000000000000000090531861025', 1);
T('-2.8e+11', '-279301037794', 1);
T('-7.126913661498270214611054421e+13', '-71269136614982.70214611054420849', 27);
T('-4.86337579169293342736515180299340135e+13', '-48633757916929.334273651518029934013479777304', 35);
T('-3.406744915848058125e+25', '-34067449158480581246177934.3445612265793', 18);
T('-5.542902272865090080311949446460659235171860088660477e+16', '-55429022728650900.803119494464606592351718600886604770155246', 51);
T('-8.26224854264697737938997145336e+12', '-8262248542646.9773793899714533620028598662842221171', 29);
T('-3.16331e+18', '-3163306186318700887', 5);
T('-9.087531707575372e+25', '-90875317075753723792666377.6466517495', 15);
T('-8.758548512438e+14', '-875854851243824.87435', 12);
T('-3.9e-11', '-0.0000000000387093', 1);
T('-3.987015017148130889206385341736666180313e+11', '-398701501714.813088920638534173666618031251290587', 39);
T('-2.493129998e-11', '-0.00000000002493129997889845697168462', 9);
T('-7.0892393575673871055576e+17', '-708923935756738710.5557595392277447617', 22);
T('-4.931821627225927773384e-20', '-0.00000000000000000004931821627225927773384063578', 21);
T('-5.245261764976094777313893054196562e-17', '-0.0000000000000000524526176497609477731389305419656234', 33);
T('-6.66625797221972034223428591e+23', '-666625797221972034223428.590606426470365', 26);
T('-4.06575860462e+17', '-406575860461750182.91372176567693718', 11);
T('-8.90585675951e+19', '-89058567595113495345', 11);
BigNumber.config({ROUNDING_MODE : 4});
T('-2.033619450856645241153977e+0', '-2.03361945085664524115397653636144859', 24);
T('1.130e+8', '112955590.0430616', 3);
T('-2.1366468193419876852426155614364269e+10', '-21366468193.419876852426155614364269', 34);
T('5.82086615659566151529e+7', '58208661.56595661515285734890860077163', 20);
T('9.1615809372817426111208e+6', '9161580.937281742611120838868847823478250167882379624', 22);
T('3.8976506901061164197e+1', '38.97650690106116419699490320634490920742414', 19);
T('9.0994914931570087194607344641722310104e+6', '9099491.4931570087194607344641722310103895224905', 37);
T('6.06e+5', '605633', 2);
T('2.6999974790473705518992117e+1', '26.9999747904737055189921170044987', 25);
T('6.7108801361722e+6', '6710880.136172156342982663450743452', 13);
T('-8.0e+0', '-8', 1);
T('3.000e-2', '0.03', 3);
T('-4.7e+2', '-469', 1);
T('-6.3000e+0', '-6.3', 4);
T('-5.4e+2', '-542', 1);
T('-5.2000e+0', '-5.2', 4);
T('-9.00000e-2', '-0.09', 5);
T('-3.1000e-1', '-0.31', 4);
T('-4.4e+2', '-436', 1);
T('-3.00e+0', '-3', 2);
T('-5.00e-2', '-0.05', 2);
T('1.00e-2', '0.01', 2);
T('1.230e+2', '12.3e1',BigNumber('3'));
T('1.23e+2', '12.3e1', null);
T('1.23e+2', '12.3e1', undefined);
T('1e+2', '12.3e1', '0');
T('1e+2', '12.3e1', '-0');
T('1e+2', '12.3e1', '-0.000000');
T('1e+2', '12.3e1', 0);
T('1e+2', '12.3e1', -0);
assertException(function () {new BigNumber('1.23').toExponential(NaN)}, "('1.23').toExponential(NaN)");
assertException(function () {new BigNumber('1.23').toExponential('NaN')}, "('1.23').toExponential('NaN')");
assertException(function () {new BigNumber('1.23').toExponential([])}, "('1.23').toExponential([])");
assertException(function () {new BigNumber('1.23').toExponential({})}, "('1.23').toExponential({})");
assertException(function () {new BigNumber('1.23').toExponential('')}, "('1.23').toExponential('')");
assertException(function () {new BigNumber('1.23').toExponential(' ')}, "('1.23').toExponential(' ')");
assertException(function () {new BigNumber('1.23').toExponential('hello')}, "('1.23').toExponential('hello')");
assertException(function () {new BigNumber('1.23').toExponential('\t')}, "('1.23').toExponential('\t')");
assertException(function () {new BigNumber('1.23').toExponential(new Date)}, "('1.23').toExponential(new Date)");
assertException(function () {new BigNumber('1.23').toExponential(new RegExp)}, "('1.23').toExponential(new RegExp)");
assertException(function () {new BigNumber('1.23').toExponential(2.01)}, "('1.23').toExponential(2.01)");
assertException(function () {new BigNumber('1.23').toExponential(10.5)}, "('1.23').toExponential(10.5)");
assertException(function () {new BigNumber('1.23').toExponential('1.1e1')}, "('1.23').toExponential('1.1e1')");
assertException(function () {new BigNumber('1.23').toExponential(true)}, "('1.23').toExponential(true)");
assertException(function () {new BigNumber('1.23').toExponential(false)}, "('1.23').toExponential(false)");
assertException(function () {new BigNumber('1.23').toExponential(function (){})}, "('1.23').toExponential(function (){})");
assertException(function () {new BigNumber(12.3).toExponential('-1')}, ".toExponential('-1')");
assertException(function () {new BigNumber(12.3).toExponential(-23)}, ".toExponential(-23)");
assertException(function () {new BigNumber(12.3).toExponential(1e9 + 1)}, ".toExponential(1e9 + 1)");
assertException(function () {new BigNumber(12.3).toExponential(1e9 + 0.1)}, ".toExponential(1e9 + 0.1)");
assertException(function () {new BigNumber(12.3).toExponential(-0.01)}, ".toExponential(-0.01)");
assertException(function () {new BigNumber(12.3).toExponential('-1e-1')}, ".toExponential('-1e-1')");
assertException(function () {new BigNumber(12.3).toExponential(Infinity)}, ".toExponential(Infinity)");
assertException(function () {new BigNumber(12.3).toExponential('-Infinity')}, ".toExponential('-Infinity')");
BigNumber.config({ERRORS : false});
T('Infinity', Infinity, 0);
T('Infinity', Infinity, NaN);
T('Infinity', Infinity, null);
T('Infinity', Infinity, Infinity);
T('NaN', NaN, -Infinity);
T('1.230e+2', '12.3e1', BigNumber(3));
T('1.23e+2', '12.3e1', null);
T('1.23e+2', '12.3e1', undefined);
T('1.23e+2', '12.3e1', NaN);
T('1.23e+2', '12.3e1', 'NaN');
T('1.23e+2', '12.3e1', []);
T('1.23e+2', '12.3e1', {});
T('1.23e+2', '12.3e1', '');
T('1.23e+2', '12.3e1', ' ');
T('1.23e+2', '12.3e1', 'hello');
T('1.23e+2', '12.3e1', '\t');
T('1.23e+2', '12.3e1', ' ');
T('1.23e+2', '12.3e1', new Date);
T('1.23e+2', '12.3e1', new RegExp);
T('1e+2', '12.3e1', -0);
T('1.2e+2', '12.3e1', 1.999);
T('1.2300000e+2', '12.3e1', 7.5);
T('1.23000000000e+2', '12.3e1', '1.1e1');
T('1.23e+2', '12.3e1', '-1');
T('1.23e+2', '12.3e1', -23);
T('1.23e+2', '12.3e1', 1e9 + 1);
T('1.23e+2', '12.3e1', 1e9 + 0.1);
T('1.23e+2', '12.3e1', -0.01);
T('1.23e+2', '12.3e1', '-1e-1');
T('1.23e+2', '12.3e1', Infinity);
T('1.23e+2', '12.3e1', '-Infinity');
BigNumber.config({
DECIMAL_PLACES : 20,
ROUNDING_MODE : 4,
ERRORS : true,
RANGE : 1E9,
EXPONENTIAL_AT : 1E9
});
log('\n ' + passed + ' of ' + total + ' tests passed in ' + (+new Date() - start) + ' ms \n');
return [passed, total];;
})(this.BigNumber);
if (typeof module !== 'undefined' && module.exports) module.exports = count;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More