mirror of
https://github.com/pocoproject/poco.git
synced 2025-10-20 22:31:31 +02:00
Fix/tsan (#3617)
* fix(Foundation): tsan warnings fixes * fix(Thread_POSIX): tsan warnings fixes; add tsan.suppress * fix(Util): tsan fixes * fix(netSSL_OpenSSL): tsan fixes * fix(Data): tsan warnings fixes * feat(ci): add tsan job * feat(ci): add tsan job, another attempt * feat(ci): add tsan job, 3rd attempt * fix(Foundation): tsan warnings fixes * fix(Thread_POSIX): tsan warnings fixes; add tsan.suppress * fix(Util): tsan fixes * fix(netSSL_OpenSSL): tsan fixes * fix(Data): tsan warnings fixes * feat(ci): add tsan job * feat(ci): add tsan job, another attempt * feat(ci): add tsan job, 3rd attempt * fix(ResultMetadata): memory leak #3474 * feat(ci): disable ActiveDispatcher tests for tsan runs * feat(ci): try to fix tsan options file detection (again) * chore(TestLibrary: correct spelling * fix(ci): fix tsan run; add -y to apt; disable samples build for some jobs * fix(ci): add mysql ports * feat(ci): add VS asan * feat(double-conversion): Upgrade double-conversion to v3.2.0 #3624 * chore(asan): disable msvc asan build (dll not found) * chore(double-conversion): move NumericString.h before double-conversion includes to prevent min/max collision; reinstate lost loongarch64 * chore(JSON): sync pdjson with upstream * fix(Statement): Poco::Data::Statement becomes unusable after exception #2287
This commit is contained in:

committed by
GitHub

parent
17fec1b985
commit
ff879f5905
55
.github/workflows/ci.yml
vendored
55
.github/workflows/ci.yml
vendored
@@ -15,7 +15,7 @@ jobs:
|
|||||||
- 3306:3306
|
- 3306:3306
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: sudo apt update && sudo apt install libssl-dev unixodbc-dev redis-server libmysqlclient-dev
|
- run: sudo apt -y update && sudo apt -y install libssl-dev unixodbc-dev redis-server libmysqlclient-dev
|
||||||
- run: ./configure --everything --omit=PDF && make all -s -j4 && sudo make install
|
- run: ./configure --everything --omit=PDF && make all -s -j4 && sudo make install
|
||||||
- run: >-
|
- run: >-
|
||||||
sudo -s
|
sudo -s
|
||||||
@@ -24,21 +24,31 @@ jobs:
|
|||||||
|
|
||||||
linux-gcc-make-asan:
|
linux-gcc-make-asan:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
|
services:
|
||||||
|
mysql:
|
||||||
|
image: mysql:latest
|
||||||
|
env:
|
||||||
|
MYSQL_ALLOW_EMPTY_PASSWORD: yes
|
||||||
|
MYSQL_USER: pocotest
|
||||||
|
MYSQL_PASSWORD: pocotest
|
||||||
|
MYSQL_DATABASE: pocotest
|
||||||
|
ports:
|
||||||
|
- 3306:3306
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: sudo apt update && sudo apt install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
- run: sudo apt -y update && sudo apt -y install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
||||||
- run: ./configure --everything --omit=PDF && make all -s -j4 SANITIZEFLAGS=-fsanitize=address && sudo make install
|
- run: ./configure --everything --no-samples --omit=PDF && make all -s -j4 SANITIZEFLAGS=-fsanitize=address && sudo make install
|
||||||
- run: >-
|
- run: >-
|
||||||
sudo -s
|
sudo -s
|
||||||
EXCLUDE_TESTS="Data/MySQL Data/ODBC Data/PostgreSQL MongoDB"
|
EXCLUDE_TESTS="Data/ODBC Data/PostgreSQL MongoDB"
|
||||||
./ci/runtests.sh
|
./ci/runtests.sh
|
||||||
|
|
||||||
linux-gcc-make-asan-no-soo:
|
linux-gcc-make-asan-no-soo:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: sudo apt update && sudo apt install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
- run: sudo apt -y update && sudo apt -y install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
||||||
- run: ./configure --everything --omit=PDF --no-soo && make all -s -j4 SANITIZEFLAGS=-fsanitize=address && sudo make install
|
- run: ./configure --everything --no-samples --omit=PDF --no-soo && make all -s -j4 SANITIZEFLAGS=-fsanitize=address && sudo make install
|
||||||
- run: >-
|
- run: >-
|
||||||
sudo -s
|
sudo -s
|
||||||
EXCLUDE_TESTS="Data/MySQL Data/ODBC Data/PostgreSQL MongoDB"
|
EXCLUDE_TESTS="Data/MySQL Data/ODBC Data/PostgreSQL MongoDB"
|
||||||
@@ -48,18 +58,28 @@ jobs:
|
|||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: sudo apt update && sudo apt install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
- run: sudo apt -y update && sudo apt -y install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
||||||
- run: ./configure --everything --omit=PDF && make all -s -j4 SANITIZEFLAGS=-fsanitize=undefined && sudo make install
|
- run: ./configure --everything --no-samples --omit=PDF && make all -s -j4 SANITIZEFLAGS=-fsanitize=undefined && sudo make install
|
||||||
- run: >-
|
- run: >-
|
||||||
sudo -s
|
sudo -s
|
||||||
EXCLUDE_TESTS="Data/MySQL Data/ODBC Data/PostgreSQL MongoDB"
|
EXCLUDE_TESTS="Data/MySQL Data/ODBC Data/PostgreSQL MongoDB"
|
||||||
./ci/runtests.sh
|
./ci/runtests.sh
|
||||||
|
|
||||||
|
linux-gcc-make-tsan:
|
||||||
|
runs-on: ubuntu-20.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
- run: sudo apt -y update && sudo apt -y install libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
||||||
|
- run: ./configure --everything --no-samples --omit=CppParser,Encodings,Data/MySQL,Data/ODBC,Data/PostgreSQL,MongoDB,PageCompiler,PDF,PocoDoc,ProGen,Redis,SevenZip && make all -s -j4 SANITIZEFLAGS=-fsanitize=thread && sudo make install
|
||||||
|
- run: >-
|
||||||
|
sudo -s
|
||||||
|
./ci/runtests.sh TSAN
|
||||||
|
|
||||||
linux-gcc-cmake:
|
linux-gcc-cmake:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: sudo apt update && sudo apt install cmake ninja-build libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
- run: sudo apt -y update && sudo apt -y install cmake ninja-build libssl-dev unixodbc-dev libmysqlclient-dev redis-server
|
||||||
- run: cmake -H. -Bcmake-build -GNinja -DENABLE_PDF=OFF -DENABLE_TESTS=ON && cmake --build cmake-build --target all
|
- run: cmake -H. -Bcmake-build -GNinja -DENABLE_PDF=OFF -DENABLE_TESTS=ON && cmake --build cmake-build --target all
|
||||||
- run: >-
|
- run: >-
|
||||||
cd cmake-build &&
|
cd cmake-build &&
|
||||||
@@ -72,8 +92,8 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- run: >-
|
- run: >-
|
||||||
sudo apt-get update &&
|
sudo apt-get -y update &&
|
||||||
sudo apt-get install crossbuild-essential-armhf
|
sudo apt-get -y install crossbuild-essential-armhf
|
||||||
- run: >-
|
- run: >-
|
||||||
./configure --config=ARM-Linux --everything --omit=PDF,Crypto,NetSSL_OpenSSL,JWT,Data/MySQL,Data/ODBC,Data/PostgreSQL,PageCompiler,PageCompiler/File2Page &&
|
./configure --config=ARM-Linux --everything --omit=PDF,Crypto,NetSSL_OpenSSL,JWT,Data/MySQL,Data/ODBC,Data/PostgreSQL,PageCompiler,PageCompiler/File2Page &&
|
||||||
make all -s -j4 ARCHFLAGS="-mcpu=cortex-a8 -mfloat-abi=hard -mfpu=neon" TOOL=arm-linux-gnueabihf
|
make all -s -j4 ARCHFLAGS="-mcpu=cortex-a8 -mfloat-abi=hard -mfpu=neon" TOOL=arm-linux-gnueabihf
|
||||||
@@ -139,3 +159,16 @@ jobs:
|
|||||||
- run: >-
|
- run: >-
|
||||||
cd cmake-build;
|
cd cmake-build;
|
||||||
ctest --output-on-failure -E "(DataMySQL)|(DataODBC)|(Redis)|(MongoDB)" -C Release
|
ctest --output-on-failure -E "(DataMySQL)|(DataODBC)|(Redis)|(MongoDB)" -C Release
|
||||||
|
|
||||||
|
# missing asan dll path
|
||||||
|
# windows-2022-msvc-cmake-2022-asan:
|
||||||
|
# runs-on: windows-2022
|
||||||
|
# env:
|
||||||
|
# CPPUNIT_IGNORE: class CppUnit::TestCaller<class PathTest>.testFind,class CppUnit::TestCaller<class ICMPSocketTest>.testSendToReceiveFrom,class CppUnit::TestCaller<class ICMPClientTest>.testPing,class CppUnit::TestCaller<class ICMPClientTest>.testBigPing,class CppUnit::TestCaller<class ICMPSocketTest>.testMTU,class CppUnit::TestCaller<class HTTPSClientSessionTest>.testProxy,class CppUnit::TestCaller<class HTTPSStreamFactoryTest>.testProxy
|
||||||
|
# steps:
|
||||||
|
# - uses: actions/checkout@v2
|
||||||
|
# - run: cmake -S. -Bcmake-build -DPOCO_SANITIZE_ASAN=ON -DENABLE_NETSSL_WIN=ON -DENABLE_NETSSL=OFF -DENABLE_CRYPTO=OFF -DENABLE_JWT=OFF -DENABLE_DATA=ON -DENABLE_DATA_ODBC=ON -DENABLE_DATA_MYSQL=OFF -DENABLE_DATA_POSTGRESQL=OFF -DENABLE_TESTS=ON
|
||||||
|
# - run: cmake --build cmake-build --config Debug
|
||||||
|
# - run: >-
|
||||||
|
# cd cmake-build;
|
||||||
|
# ctest --output-on-failure -E "(DataMySQL)|(DataODBC)|(Redis)|(MongoDB)" -C Debug
|
||||||
|
@@ -78,6 +78,10 @@ if(MSVC)
|
|||||||
if((NOT POCO_DISABLE_INTERNAL_OPENSSL) AND (ENABLE_NETSSL OR ENABLE_CRYPTO OR (ENABLE_DATA_MYSQL AND MINGW)))
|
if((NOT POCO_DISABLE_INTERNAL_OPENSSL) AND (ENABLE_NETSSL OR ENABLE_CRYPTO OR (ENABLE_DATA_MYSQL AND MINGW)))
|
||||||
include(UseEmbeddedOpenSSL)
|
include(UseEmbeddedOpenSSL)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
if(POCO_SANITIZE_ASAN)
|
||||||
|
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /fsanitize=address")
|
||||||
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
option(ENABLE_NETSSL_WIN "Enable NetSSL Windows" OFF)
|
option(ENABLE_NETSSL_WIN "Enable NetSSL Windows" OFF)
|
||||||
|
@@ -71,6 +71,8 @@ public:
|
|||||||
/// Expands the size allocated for column to fit the length of the data.
|
/// Expands the size allocated for column to fit the length of the data.
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
void freeMemory();
|
||||||
|
|
||||||
std::vector<MetaColumn> _columns;
|
std::vector<MetaColumn> _columns;
|
||||||
std::vector<MYSQL_BIND> _row;
|
std::vector<MYSQL_BIND> _row;
|
||||||
std::vector<char*> _buffer;
|
std::vector<char*> _buffer;
|
||||||
|
@@ -147,13 +147,13 @@ namespace MySQL {
|
|||||||
|
|
||||||
ResultMetadata::~ResultMetadata()
|
ResultMetadata::~ResultMetadata()
|
||||||
{
|
{
|
||||||
for (std::vector<char*>::iterator it = _buffer.begin(); it != _buffer.end(); ++it)
|
freeMemory();
|
||||||
std::free(*it);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void ResultMetadata::reset()
|
void ResultMetadata::reset()
|
||||||
{
|
{
|
||||||
|
freeMemory();
|
||||||
_columns.resize(0);
|
_columns.resize(0);
|
||||||
_row.resize(0);
|
_row.resize(0);
|
||||||
_buffer.resize(0);
|
_buffer.resize(0);
|
||||||
@@ -162,14 +162,20 @@ void ResultMetadata::reset()
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void ResultMetadata::freeMemory()
|
||||||
|
{
|
||||||
|
for (std::vector<char*>::iterator it = _buffer.begin(); it != _buffer.end(); ++it)
|
||||||
|
std::free(*it);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void ResultMetadata::init(MYSQL_STMT* stmt)
|
void ResultMetadata::init(MYSQL_STMT* stmt)
|
||||||
{
|
{
|
||||||
ResultMetadataHandle h(stmt);
|
ResultMetadataHandle h(stmt);
|
||||||
|
|
||||||
if (!h)
|
if (!h)
|
||||||
{
|
{
|
||||||
// all right, it is normal
|
// some queries (eg. INSERT) don't have result
|
||||||
// querys such an "INSERT INTO" just does not have result at all
|
|
||||||
reset();
|
reset();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
@@ -78,6 +78,7 @@ public:
|
|||||||
using ResultPtr = SharedPtr<Result>;
|
using ResultPtr = SharedPtr<Result>;
|
||||||
using AsyncExecMethod = ActiveMethod<std::size_t, bool, StatementImpl>;
|
using AsyncExecMethod = ActiveMethod<std::size_t, bool, StatementImpl>;
|
||||||
using AsyncExecMethodPtr = SharedPtr<AsyncExecMethod>;
|
using AsyncExecMethodPtr = SharedPtr<AsyncExecMethod>;
|
||||||
|
using State = StatementImpl::State;
|
||||||
|
|
||||||
static const int WAIT_FOREVER = -1;
|
static const int WAIT_FOREVER = -1;
|
||||||
|
|
||||||
@@ -385,6 +386,9 @@ public:
|
|||||||
/// Sets the row formatter for this statement.
|
/// Sets the row formatter for this statement.
|
||||||
/// Statement takes the ownership of the formatter.
|
/// Statement takes the ownership of the formatter.
|
||||||
|
|
||||||
|
State state() const;
|
||||||
|
/// Returns the statement state.
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
using ImplPtr = StatementImpl::Ptr;
|
using ImplPtr = StatementImpl::Ptr;
|
||||||
|
|
||||||
@@ -791,6 +795,12 @@ inline bool Statement::isAsync() const
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline Statement::State Statement::state() const
|
||||||
|
{
|
||||||
|
return _pImpl->getState();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
inline void Statement::setRowFormatter(RowFormatter::Ptr pRowFormatter)
|
inline void Statement::setRowFormatter(RowFormatter::Ptr pRowFormatter)
|
||||||
{
|
{
|
||||||
_pRowFormatter = pRowFormatter;
|
_pRowFormatter = pRowFormatter;
|
||||||
|
@@ -432,7 +432,7 @@ private:
|
|||||||
|
|
||||||
using CountVec = std::vector<std::size_t>;
|
using CountVec = std::vector<std::size_t>;
|
||||||
|
|
||||||
State _state;
|
std::atomic<State> _state;
|
||||||
Limit _extrLimit;
|
Limit _extrLimit;
|
||||||
std::size_t _lowerLimit;
|
std::size_t _lowerLimit;
|
||||||
std::vector<int> _columnsExtracted;
|
std::vector<int> _columnsExtracted;
|
||||||
|
@@ -69,34 +69,40 @@ StatementImpl::~StatementImpl()
|
|||||||
|
|
||||||
std::size_t StatementImpl::execute(const bool& reset)
|
std::size_t StatementImpl::execute(const bool& reset)
|
||||||
{
|
{
|
||||||
if (reset) resetExtraction();
|
|
||||||
|
|
||||||
if (!_rSession.isConnected())
|
|
||||||
{
|
|
||||||
_state = ST_DONE;
|
|
||||||
throw NotConnectedException(_rSession.connectionString());
|
|
||||||
}
|
|
||||||
|
|
||||||
std::size_t lim = 0;
|
std::size_t lim = 0;
|
||||||
if (_lowerLimit > _extrLimit.value())
|
|
||||||
throw LimitException("Illegal Statement state. Upper limit must not be smaller than the lower limit.");
|
|
||||||
|
|
||||||
do
|
try
|
||||||
{
|
{
|
||||||
compile();
|
if (reset) resetExtraction();
|
||||||
|
|
||||||
|
if (!_rSession.isConnected())
|
||||||
|
throw NotConnectedException(_rSession.connectionString());
|
||||||
|
|
||||||
|
if (_lowerLimit > _extrLimit.value())
|
||||||
|
throw LimitException("Illegal Statement state. Upper limit must not be smaller than the lower limit.");
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
compile();
|
||||||
|
if (_extrLimit.value() == Limit::LIMIT_UNLIMITED)
|
||||||
|
lim += executeWithoutLimit();
|
||||||
|
else
|
||||||
|
lim += executeWithLimit();
|
||||||
|
} while (canCompile());
|
||||||
|
|
||||||
if (_extrLimit.value() == Limit::LIMIT_UNLIMITED)
|
if (_extrLimit.value() == Limit::LIMIT_UNLIMITED)
|
||||||
lim += executeWithoutLimit();
|
_state = ST_DONE;
|
||||||
else
|
|
||||||
lim += executeWithLimit();
|
|
||||||
} while (canCompile());
|
|
||||||
|
|
||||||
if (_extrLimit.value() == Limit::LIMIT_UNLIMITED)
|
if (lim < _lowerLimit)
|
||||||
|
throw LimitException("Did not receive enough data.");
|
||||||
|
|
||||||
|
assignSubTotal(reset);
|
||||||
|
}
|
||||||
|
catch(...)
|
||||||
|
{
|
||||||
_state = ST_DONE;
|
_state = ST_DONE;
|
||||||
|
throw;
|
||||||
if (lim < _lowerLimit)
|
}
|
||||||
throw LimitException("Did not receive enough data.");
|
|
||||||
|
|
||||||
assignSubTotal(reset);
|
|
||||||
|
|
||||||
return lim;
|
return lim;
|
||||||
}
|
}
|
||||||
|
@@ -127,6 +127,8 @@ void DataTest::testSession()
|
|||||||
fail ("must fail");
|
fail ("must fail");
|
||||||
} catch (NotConnectedException&) { }
|
} catch (NotConnectedException&) { }
|
||||||
|
|
||||||
|
assertTrue(stmt.done());
|
||||||
|
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
sess << "SELECT * FROM Strings", now;
|
sess << "SELECT * FROM Strings", now;
|
||||||
@@ -137,6 +139,21 @@ void DataTest::testSession()
|
|||||||
assertTrue (sess.getFeature("connected"));
|
assertTrue (sess.getFeature("connected"));
|
||||||
assertTrue (sess.isConnected());
|
assertTrue (sess.isConnected());
|
||||||
|
|
||||||
|
// ensure that throwing during execution leaves
|
||||||
|
// statement in valid state (ST_DONE)
|
||||||
|
sess.setFeature("throwOnHasNext", true);
|
||||||
|
Statement stmt1 = (sess << "SELECT * FROM Strings", into(str), limit(50));
|
||||||
|
assertTrue (sess.getFeature("throwOnHasNext"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
stmt1.execute();
|
||||||
|
fail ("must trow UnknownDataBaseException");
|
||||||
|
}
|
||||||
|
catch(const Poco::Data::UnknownDataBaseException&) {}
|
||||||
|
assertTrue(stmt1.done());
|
||||||
|
|
||||||
|
// reset session back to normal operation
|
||||||
|
sess.setFeature("throwOnHasNext", false);
|
||||||
sess << "SELECT * FROM Strings", now;
|
sess << "SELECT * FROM Strings", now;
|
||||||
stmt.execute();
|
stmt.execute();
|
||||||
|
|
||||||
|
@@ -26,6 +26,7 @@ SessionImpl::SessionImpl(const std::string& init, std::size_t timeout):
|
|||||||
addFeature("f1", &SessionImpl::setF, &SessionImpl::getF);
|
addFeature("f1", &SessionImpl::setF, &SessionImpl::getF);
|
||||||
addFeature("f2", 0, &SessionImpl::getF);
|
addFeature("f2", 0, &SessionImpl::getF);
|
||||||
addFeature("f3", &SessionImpl::setF, 0);
|
addFeature("f3", &SessionImpl::setF, 0);
|
||||||
|
addFeature("throwOnHasNext", &SessionImpl::setThrowOnHasNext, &SessionImpl::getThrowOnHasNext);
|
||||||
addFeature("connected", &SessionImpl::setConnected, &SessionImpl::getConnected);
|
addFeature("connected", &SessionImpl::setConnected, &SessionImpl::getConnected);
|
||||||
addProperty("p1", &SessionImpl::setP, &SessionImpl::getP);
|
addProperty("p1", &SessionImpl::setP, &SessionImpl::getP);
|
||||||
addProperty("p2", 0, &SessionImpl::getP);
|
addProperty("p2", 0, &SessionImpl::getP);
|
||||||
@@ -73,7 +74,7 @@ std::size_t SessionImpl::getConnectionTimeout() const
|
|||||||
|
|
||||||
StatementImpl::Ptr SessionImpl::createStatementImpl()
|
StatementImpl::Ptr SessionImpl::createStatementImpl()
|
||||||
{
|
{
|
||||||
return new TestStatementImpl(*this);
|
return new TestStatementImpl(*this, _throwOnHasNext);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -139,13 +140,13 @@ bool SessionImpl::getConnected(const std::string& name) const
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void SessionImpl::setConnected(const std::string& name, bool value)
|
void SessionImpl::setConnected(const std::string&, bool value)
|
||||||
{
|
{
|
||||||
_connected = value;
|
_connected = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void SessionImpl::setF(const std::string& name, bool value)
|
void SessionImpl::setF(const std::string&, bool value)
|
||||||
{
|
{
|
||||||
_f = value;
|
_f = value;
|
||||||
}
|
}
|
||||||
@@ -157,6 +158,17 @@ bool SessionImpl::getF(const std::string& name) const
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void SessionImpl::setThrowOnHasNext(const std::string&, bool value)
|
||||||
|
{
|
||||||
|
_throwOnHasNext = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool SessionImpl::getThrowOnHasNext(const std::string& name) const
|
||||||
|
{
|
||||||
|
return _throwOnHasNext;
|
||||||
|
}
|
||||||
|
|
||||||
void SessionImpl::setP(const std::string& name, const Poco::Any& value)
|
void SessionImpl::setP(const std::string& name, const Poco::Any& value)
|
||||||
{
|
{
|
||||||
_p = value;
|
_p = value;
|
||||||
|
@@ -98,11 +98,14 @@ public:
|
|||||||
|
|
||||||
void setF(const std::string& name, bool value);
|
void setF(const std::string& name, bool value);
|
||||||
bool getF(const std::string& name) const;
|
bool getF(const std::string& name) const;
|
||||||
|
void setThrowOnHasNext(const std::string& name, bool value);
|
||||||
|
bool getThrowOnHasNext(const std::string& name) const;
|
||||||
void setP(const std::string& name, const Poco::Any& value);
|
void setP(const std::string& name, const Poco::Any& value);
|
||||||
Poco::Any getP(const std::string& name) const;
|
Poco::Any getP(const std::string& name) const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
bool _f;
|
bool _f;
|
||||||
|
bool _throwOnHasNext = false;
|
||||||
Poco::Any _p;
|
Poco::Any _p;
|
||||||
bool _connected;
|
bool _connected;
|
||||||
std::string _connectionString;
|
std::string _connectionString;
|
||||||
|
@@ -17,9 +17,10 @@ namespace Data {
|
|||||||
namespace Test {
|
namespace Test {
|
||||||
|
|
||||||
|
|
||||||
TestStatementImpl::TestStatementImpl(SessionImpl& rSession):
|
TestStatementImpl::TestStatementImpl(SessionImpl& rSession, bool throwOnHasNext):
|
||||||
Poco::Data::StatementImpl(rSession),
|
Poco::Data::StatementImpl(rSession),
|
||||||
_compiled(false)
|
_compiled(false),
|
||||||
|
_throwOnHasNext(throwOnHasNext)
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,6 +80,8 @@ const MetaColumn& TestStatementImpl::metaColumn(std::size_t pos) const
|
|||||||
|
|
||||||
bool TestStatementImpl::hasNext()
|
bool TestStatementImpl::hasNext()
|
||||||
{
|
{
|
||||||
|
if (_throwOnHasNext)
|
||||||
|
throw Poco::Data::UnknownDataBaseException();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -34,7 +34,7 @@ class TestStatementImpl: public Poco::Data::StatementImpl
|
|||||||
/// A no-op implementation of TestStatementImpl for testing.
|
/// A no-op implementation of TestStatementImpl for testing.
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
TestStatementImpl(SessionImpl& rSession);
|
TestStatementImpl(SessionImpl& rSession, bool throwOnHasNext = false);
|
||||||
/// Creates the TestStatementImpl.
|
/// Creates the TestStatementImpl.
|
||||||
|
|
||||||
~TestStatementImpl();
|
~TestStatementImpl();
|
||||||
@@ -80,7 +80,8 @@ private:
|
|||||||
Poco::SharedPtr<Binder> _ptrBinder;
|
Poco::SharedPtr<Binder> _ptrBinder;
|
||||||
Poco::SharedPtr<Extractor> _ptrExtractor;
|
Poco::SharedPtr<Extractor> _ptrExtractor;
|
||||||
Poco::SharedPtr<Preparator> _ptrPreparation;
|
Poco::SharedPtr<Preparator> _ptrPreparation;
|
||||||
bool _compiled;
|
bool _compiled;
|
||||||
|
bool _throwOnHasNext = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -21,6 +21,7 @@
|
|||||||
#include "Poco/Foundation.h"
|
#include "Poco/Foundation.h"
|
||||||
#include "Poco/Runnable.h"
|
#include "Poco/Runnable.h"
|
||||||
#include "Poco/Thread.h"
|
#include "Poco/Thread.h"
|
||||||
|
#include "Poco/Event.h"
|
||||||
#include "Poco/ActiveStarter.h"
|
#include "Poco/ActiveStarter.h"
|
||||||
#include "Poco/ActiveRunnable.h"
|
#include "Poco/ActiveRunnable.h"
|
||||||
#include "Poco/NotificationQueue.h"
|
#include "Poco/NotificationQueue.h"
|
||||||
|
@@ -148,7 +148,7 @@ private:
|
|||||||
std::string _name;
|
std::string _name;
|
||||||
TaskManager* _pOwner;
|
TaskManager* _pOwner;
|
||||||
float _progress;
|
float _progress;
|
||||||
TaskState _state;
|
std::atomic<TaskState> _state;
|
||||||
Event _cancelEvent;
|
Event _cancelEvent;
|
||||||
mutable FastMutex _mutex;
|
mutable FastMutex _mutex;
|
||||||
|
|
||||||
|
@@ -141,10 +141,10 @@ private:
|
|||||||
std::size_t stackSize;
|
std::size_t stackSize;
|
||||||
bool started;
|
bool started;
|
||||||
bool joined;
|
bool joined;
|
||||||
|
mutable FastMutex mutex;
|
||||||
};
|
};
|
||||||
|
|
||||||
AutoPtr<ThreadData> _pData;
|
AutoPtr<ThreadData> _pData;
|
||||||
|
|
||||||
static CurrentThreadHolder _currentThreadHolder;
|
static CurrentThreadHolder _currentThreadHolder;
|
||||||
|
|
||||||
#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS)
|
#if defined(POCO_OS_FAMILY_UNIX) && !defined(POCO_VXWORKS)
|
||||||
@@ -171,6 +171,7 @@ inline int ThreadImpl::getOSPriorityImpl() const
|
|||||||
|
|
||||||
inline bool ThreadImpl::isRunningImpl() const
|
inline bool ThreadImpl::isRunningImpl() const
|
||||||
{
|
{
|
||||||
|
FastMutex::ScopedLock l(_pData->mutex);
|
||||||
return !_pData->pRunnableTarget.isNull();
|
return !_pData->pRunnableTarget.isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -371,8 +371,8 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
int _fd;
|
std::atomic<int> _fd;
|
||||||
bool _stopped;
|
std::atomic<bool> _stopped;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -13,23 +13,23 @@
|
|||||||
|
|
||||||
|
|
||||||
#include "Poco/Bugcheck.h"
|
#include "Poco/Bugcheck.h"
|
||||||
|
#include "Poco/NumericString.h"
|
||||||
|
|
||||||
// +++ double conversion +++
|
// +++ double conversion +++
|
||||||
// don't collide with standalone double_conversion library
|
// don't collide with standalone double_conversion library
|
||||||
#define double_conversion poco_double_conversion
|
#define double_conversion poco_double_conversion
|
||||||
#define UNIMPLEMENTED poco_bugcheck
|
#define UNIMPLEMENTED poco_bugcheck
|
||||||
#include "diy-fp.cc"
|
#include "double-conversion.h"
|
||||||
#include "cached-powers.cc"
|
#include "cached-powers.cc"
|
||||||
#include "bignum-dtoa.cc"
|
#include "bignum-dtoa.cc"
|
||||||
#include "bignum.cc"
|
#include "bignum.cc"
|
||||||
#include "fast-dtoa.cc"
|
#include "fast-dtoa.cc"
|
||||||
#include "fixed-dtoa.cc"
|
#include "fixed-dtoa.cc"
|
||||||
#include "strtod.cc"
|
#include "strtod.cc"
|
||||||
#include "double-conversion.cc"
|
#include "double-to-string.cc"
|
||||||
|
#include "string-to-double.cc"
|
||||||
// --- double conversion ---
|
// --- double conversion ---
|
||||||
|
|
||||||
#include "Poco/NumericString.h"
|
|
||||||
poco_static_assert(POCO_MAX_FLT_STRING_LEN == double_conversion::kMaxSignificantDecimalDigits);
|
poco_static_assert(POCO_MAX_FLT_STRING_LEN == double_conversion::kMaxSignificantDecimalDigits);
|
||||||
#include "Poco/String.h"
|
#include "Poco/String.h"
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
@@ -43,10 +43,10 @@ TaskManager::~TaskManager()
|
|||||||
void TaskManager::start(Task* pTask)
|
void TaskManager::start(Task* pTask)
|
||||||
{
|
{
|
||||||
TaskPtr pAutoTask(pTask); // take ownership immediately
|
TaskPtr pAutoTask(pTask); // take ownership immediately
|
||||||
FastMutex::ScopedLock lock(_mutex);
|
|
||||||
|
|
||||||
pAutoTask->setOwner(this);
|
pAutoTask->setOwner(this);
|
||||||
pAutoTask->setState(Task::TASK_STARTING);
|
pAutoTask->setState(Task::TASK_STARTING);
|
||||||
|
|
||||||
|
FastMutex::ScopedLock lock(_mutex);
|
||||||
_taskList.push_back(pAutoTask);
|
_taskList.push_back(pAutoTask);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
@@ -188,8 +188,11 @@ void ThreadImpl::setStackSizeImpl(int size)
|
|||||||
|
|
||||||
void ThreadImpl::startImpl(SharedPtr<Runnable> pTarget)
|
void ThreadImpl::startImpl(SharedPtr<Runnable> pTarget)
|
||||||
{
|
{
|
||||||
if (_pData->pRunnableTarget)
|
{
|
||||||
throw SystemException("thread already running");
|
FastMutex::ScopedLock l(_pData->mutex);
|
||||||
|
if (_pData->pRunnableTarget)
|
||||||
|
throw SystemException("thread already running");
|
||||||
|
}
|
||||||
|
|
||||||
pthread_attr_t attributes;
|
pthread_attr_t attributes;
|
||||||
pthread_attr_init(&attributes);
|
pthread_attr_init(&attributes);
|
||||||
@@ -203,12 +206,15 @@ void ThreadImpl::startImpl(SharedPtr<Runnable> pTarget)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_pData->pRunnableTarget = pTarget;
|
|
||||||
if (pthread_create(&_pData->thread, &attributes, runnableEntry, this))
|
|
||||||
{
|
{
|
||||||
_pData->pRunnableTarget = 0;
|
FastMutex::ScopedLock l(_pData->mutex);
|
||||||
pthread_attr_destroy(&attributes);
|
_pData->pRunnableTarget = pTarget;
|
||||||
throw SystemException("cannot start thread");
|
if (pthread_create(&_pData->thread, &attributes, runnableEntry, this))
|
||||||
|
{
|
||||||
|
_pData->pRunnableTarget = 0;
|
||||||
|
pthread_attr_destroy(&attributes);
|
||||||
|
throw SystemException("cannot start thread");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
_pData->started = true;
|
_pData->started = true;
|
||||||
pthread_attr_destroy(&attributes);
|
pthread_attr_destroy(&attributes);
|
||||||
@@ -372,6 +378,7 @@ void* ThreadImpl::runnableEntry(void* pThread)
|
|||||||
ErrorHandler::handle();
|
ErrorHandler::handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
FastMutex::ScopedLock l(pData->mutex);
|
||||||
pData->pRunnableTarget = 0;
|
pData->pRunnableTarget = 0;
|
||||||
pData->done.set();
|
pData->done.set();
|
||||||
return 0;
|
return 0;
|
||||||
|
@@ -35,7 +35,7 @@
|
|||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
static int NormalizedExponent(uint64_t significand, int exponent) {
|
static int NormalizedExponent(uint64_t significand, int exponent) {
|
||||||
ASSERT(significand != 0);
|
DOUBLE_CONVERSION_ASSERT(significand != 0);
|
||||||
while ((significand & Double::kHiddenBit) == 0) {
|
while ((significand & Double::kHiddenBit) == 0) {
|
||||||
significand = significand << 1;
|
significand = significand << 1;
|
||||||
exponent = exponent - 1;
|
exponent = exponent - 1;
|
||||||
@@ -76,26 +76,26 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
// Generates 'requested_digits' after the decimal point.
|
// Generates 'requested_digits' after the decimal point.
|
||||||
static void BignumToFixed(int requested_digits, int* decimal_point,
|
static void BignumToFixed(int requested_digits, int* decimal_point,
|
||||||
Bignum* numerator, Bignum* denominator,
|
Bignum* numerator, Bignum* denominator,
|
||||||
Vector<char>(buffer), int* length);
|
Vector<char> buffer, int* length);
|
||||||
// Generates 'count' digits of numerator/denominator.
|
// Generates 'count' digits of numerator/denominator.
|
||||||
// Once 'count' digits have been produced rounds the result depending on the
|
// Once 'count' digits have been produced rounds the result depending on the
|
||||||
// remainder (remainders of exactly .5 round upwards). Might update the
|
// remainder (remainders of exactly .5 round upwards). Might update the
|
||||||
// decimal_point when rounding up (for example for 0.9999).
|
// decimal_point when rounding up (for example for 0.9999).
|
||||||
static void GenerateCountedDigits(int count, int* decimal_point,
|
static void GenerateCountedDigits(int count, int* decimal_point,
|
||||||
Bignum* numerator, Bignum* denominator,
|
Bignum* numerator, Bignum* denominator,
|
||||||
Vector<char>(buffer), int* length);
|
Vector<char> buffer, int* length);
|
||||||
|
|
||||||
|
|
||||||
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
||||||
Vector<char> buffer, int* length, int* decimal_point) {
|
Vector<char> buffer, int* length, int* decimal_point) {
|
||||||
ASSERT(v > 0);
|
DOUBLE_CONVERSION_ASSERT(v > 0);
|
||||||
ASSERT(!Double(v).IsSpecial());
|
DOUBLE_CONVERSION_ASSERT(!Double(v).IsSpecial());
|
||||||
uint64_t significand;
|
uint64_t significand;
|
||||||
int exponent;
|
int exponent;
|
||||||
bool lower_boundary_is_closer;
|
bool lower_boundary_is_closer;
|
||||||
if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
|
if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
|
||||||
float f = static_cast<float>(v);
|
float f = static_cast<float>(v);
|
||||||
ASSERT(f == v);
|
DOUBLE_CONVERSION_ASSERT(f == v);
|
||||||
significand = Single(f).Significand();
|
significand = Single(f).Significand();
|
||||||
exponent = Single(f).Exponent();
|
exponent = Single(f).Exponent();
|
||||||
lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
|
lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
|
||||||
@@ -134,7 +134,7 @@ void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
|||||||
// 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
|
// 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
|
||||||
// The maximum double is 1.7976931348623157e308 which needs fewer than
|
// The maximum double is 1.7976931348623157e308 which needs fewer than
|
||||||
// 308*4 binary digits.
|
// 308*4 binary digits.
|
||||||
ASSERT(Bignum::kMaxSignificantBits >= 324*4);
|
DOUBLE_CONVERSION_ASSERT(Bignum::kMaxSignificantBits >= 324*4);
|
||||||
InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
|
InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
|
||||||
estimated_power, need_boundary_deltas,
|
estimated_power, need_boundary_deltas,
|
||||||
&numerator, &denominator,
|
&numerator, &denominator,
|
||||||
@@ -163,7 +163,7 @@ void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
|||||||
buffer, length);
|
buffer, length);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
UNREACHABLE();
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
}
|
}
|
||||||
buffer[*length] = '\0';
|
buffer[*length] = '\0';
|
||||||
}
|
}
|
||||||
@@ -195,7 +195,7 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
for (;;) {
|
for (;;) {
|
||||||
uint16_t digit;
|
uint16_t digit;
|
||||||
digit = numerator->DivideModuloIntBignum(*denominator);
|
digit = numerator->DivideModuloIntBignum(*denominator);
|
||||||
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
DOUBLE_CONVERSION_ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
||||||
// digit = numerator / denominator (integer division).
|
// digit = numerator / denominator (integer division).
|
||||||
// numerator = numerator % denominator.
|
// numerator = numerator % denominator.
|
||||||
buffer[(*length)++] = static_cast<char>(digit + '0');
|
buffer[(*length)++] = static_cast<char>(digit + '0');
|
||||||
@@ -241,7 +241,7 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
// loop would have stopped earlier.
|
// loop would have stopped earlier.
|
||||||
// We still have an assert here in case the preconditions were not
|
// We still have an assert here in case the preconditions were not
|
||||||
// satisfied.
|
// satisfied.
|
||||||
ASSERT(buffer[(*length) - 1] != '9');
|
DOUBLE_CONVERSION_ASSERT(buffer[(*length) - 1] != '9');
|
||||||
buffer[(*length) - 1]++;
|
buffer[(*length) - 1]++;
|
||||||
} else {
|
} else {
|
||||||
// Halfway case.
|
// Halfway case.
|
||||||
@@ -252,7 +252,7 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
if ((buffer[(*length) - 1] - '0') % 2 == 0) {
|
if ((buffer[(*length) - 1] - '0') % 2 == 0) {
|
||||||
// Round down => Do nothing.
|
// Round down => Do nothing.
|
||||||
} else {
|
} else {
|
||||||
ASSERT(buffer[(*length) - 1] != '9');
|
DOUBLE_CONVERSION_ASSERT(buffer[(*length) - 1] != '9');
|
||||||
buffer[(*length) - 1]++;
|
buffer[(*length) - 1]++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,9 +264,9 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
// Round up.
|
// Round up.
|
||||||
// Note again that the last digit could not be '9' since this would have
|
// Note again that the last digit could not be '9' since this would have
|
||||||
// stopped the loop earlier.
|
// stopped the loop earlier.
|
||||||
// We still have an ASSERT here, in case the preconditions were not
|
// We still have an DOUBLE_CONVERSION_ASSERT here, in case the preconditions were not
|
||||||
// satisfied.
|
// satisfied.
|
||||||
ASSERT(buffer[(*length) -1] != '9');
|
DOUBLE_CONVERSION_ASSERT(buffer[(*length) -1] != '9');
|
||||||
buffer[(*length) - 1]++;
|
buffer[(*length) - 1]++;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -276,18 +276,18 @@ static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
|||||||
|
|
||||||
// Let v = numerator / denominator < 10.
|
// Let v = numerator / denominator < 10.
|
||||||
// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
|
// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
|
||||||
// from left to right. Once 'count' digits have been produced we decide wether
|
// from left to right. Once 'count' digits have been produced we decide whether
|
||||||
// to round up or down. Remainders of exactly .5 round upwards. Numbers such
|
// to round up or down. Remainders of exactly .5 round upwards. Numbers such
|
||||||
// as 9.999999 propagate a carry all the way, and change the
|
// as 9.999999 propagate a carry all the way, and change the
|
||||||
// exponent (decimal_point), when rounding upwards.
|
// exponent (decimal_point), when rounding upwards.
|
||||||
static void GenerateCountedDigits(int count, int* decimal_point,
|
static void GenerateCountedDigits(int count, int* decimal_point,
|
||||||
Bignum* numerator, Bignum* denominator,
|
Bignum* numerator, Bignum* denominator,
|
||||||
Vector<char> buffer, int* length) {
|
Vector<char> buffer, int* length) {
|
||||||
ASSERT(count >= 0);
|
DOUBLE_CONVERSION_ASSERT(count >= 0);
|
||||||
for (int i = 0; i < count - 1; ++i) {
|
for (int i = 0; i < count - 1; ++i) {
|
||||||
uint16_t digit;
|
uint16_t digit;
|
||||||
digit = numerator->DivideModuloIntBignum(*denominator);
|
digit = numerator->DivideModuloIntBignum(*denominator);
|
||||||
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
DOUBLE_CONVERSION_ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
||||||
// digit = numerator / denominator (integer division).
|
// digit = numerator / denominator (integer division).
|
||||||
// numerator = numerator % denominator.
|
// numerator = numerator % denominator.
|
||||||
buffer[i] = static_cast<char>(digit + '0');
|
buffer[i] = static_cast<char>(digit + '0');
|
||||||
@@ -300,7 +300,7 @@ static void GenerateCountedDigits(int count, int* decimal_point,
|
|||||||
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
||||||
digit++;
|
digit++;
|
||||||
}
|
}
|
||||||
ASSERT(digit <= 10);
|
DOUBLE_CONVERSION_ASSERT(digit <= 10);
|
||||||
buffer[count - 1] = static_cast<char>(digit + '0');
|
buffer[count - 1] = static_cast<char>(digit + '0');
|
||||||
// Correct bad digits (in case we had a sequence of '9's). Propagate the
|
// Correct bad digits (in case we had a sequence of '9's). Propagate the
|
||||||
// carry until we hat a non-'9' or til we reach the first digit.
|
// carry until we hat a non-'9' or til we reach the first digit.
|
||||||
@@ -325,7 +325,7 @@ static void GenerateCountedDigits(int count, int* decimal_point,
|
|||||||
// Input verifies: 1 <= (numerator + delta) / denominator < 10.
|
// Input verifies: 1 <= (numerator + delta) / denominator < 10.
|
||||||
static void BignumToFixed(int requested_digits, int* decimal_point,
|
static void BignumToFixed(int requested_digits, int* decimal_point,
|
||||||
Bignum* numerator, Bignum* denominator,
|
Bignum* numerator, Bignum* denominator,
|
||||||
Vector<char>(buffer), int* length) {
|
Vector<char> buffer, int* length) {
|
||||||
// Note that we have to look at more than just the requested_digits, since
|
// Note that we have to look at more than just the requested_digits, since
|
||||||
// a number could be rounded up. Example: v=0.5 with requested_digits=0.
|
// a number could be rounded up. Example: v=0.5 with requested_digits=0.
|
||||||
// Even though the power of v equals 0 we can't just stop here.
|
// Even though the power of v equals 0 we can't just stop here.
|
||||||
@@ -341,7 +341,7 @@ static void BignumToFixed(int requested_digits, int* decimal_point,
|
|||||||
} else if (-(*decimal_point) == requested_digits) {
|
} else if (-(*decimal_point) == requested_digits) {
|
||||||
// We only need to verify if the number rounds down or up.
|
// We only need to verify if the number rounds down or up.
|
||||||
// Ex: 0.04 and 0.06 with requested_digits == 1.
|
// Ex: 0.04 and 0.06 with requested_digits == 1.
|
||||||
ASSERT(*decimal_point == -requested_digits);
|
DOUBLE_CONVERSION_ASSERT(*decimal_point == -requested_digits);
|
||||||
// Initially the fraction lies in range (1, 10]. Multiply the denominator
|
// Initially the fraction lies in range (1, 10]. Multiply the denominator
|
||||||
// by 10 so that we can compare more easily.
|
// by 10 so that we can compare more easily.
|
||||||
denominator->Times10();
|
denominator->Times10();
|
||||||
@@ -370,7 +370,7 @@ static void BignumToFixed(int requested_digits, int* decimal_point,
|
|||||||
// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
|
// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
|
||||||
// v = f * 2^exponent and 2^52 <= f < 2^53.
|
// v = f * 2^exponent and 2^52 <= f < 2^53.
|
||||||
// v is hence a normalized double with the given exponent. The output is an
|
// v is hence a normalized double with the given exponent. The output is an
|
||||||
// approximation for the exponent of the decimal approimation .digits * 10^k.
|
// approximation for the exponent of the decimal approximation .digits * 10^k.
|
||||||
//
|
//
|
||||||
// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
|
// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
|
||||||
// Note: this property holds for v's upper boundary m+ too.
|
// Note: this property holds for v's upper boundary m+ too.
|
||||||
@@ -420,7 +420,7 @@ static void InitialScaledStartValuesPositiveExponent(
|
|||||||
Bignum* numerator, Bignum* denominator,
|
Bignum* numerator, Bignum* denominator,
|
||||||
Bignum* delta_minus, Bignum* delta_plus) {
|
Bignum* delta_minus, Bignum* delta_plus) {
|
||||||
// A positive exponent implies a positive power.
|
// A positive exponent implies a positive power.
|
||||||
ASSERT(estimated_power >= 0);
|
DOUBLE_CONVERSION_ASSERT(estimated_power >= 0);
|
||||||
// Since the estimated_power is positive we simply multiply the denominator
|
// Since the estimated_power is positive we simply multiply the denominator
|
||||||
// by 10^estimated_power.
|
// by 10^estimated_power.
|
||||||
|
|
||||||
@@ -506,7 +506,7 @@ static void InitialScaledStartValuesNegativeExponentNegativePower(
|
|||||||
// numerator = v * 10^-estimated_power * 2 * 2^-exponent.
|
// numerator = v * 10^-estimated_power * 2 * 2^-exponent.
|
||||||
// Remember: numerator has been abused as power_ten. So no need to assign it
|
// Remember: numerator has been abused as power_ten. So no need to assign it
|
||||||
// to itself.
|
// to itself.
|
||||||
ASSERT(numerator == power_ten);
|
DOUBLE_CONVERSION_ASSERT(numerator == power_ten);
|
||||||
numerator->MultiplyByUInt64(significand);
|
numerator->MultiplyByUInt64(significand);
|
||||||
|
|
||||||
// denominator = 2 * 2^-exponent with exponent < 0.
|
// denominator = 2 * 2^-exponent with exponent < 0.
|
||||||
@@ -548,7 +548,7 @@ static void InitialScaledStartValuesNegativeExponentNegativePower(
|
|||||||
//
|
//
|
||||||
// Let ep == estimated_power, then the returned values will satisfy:
|
// Let ep == estimated_power, then the returned values will satisfy:
|
||||||
// v / 10^ep = numerator / denominator.
|
// v / 10^ep = numerator / denominator.
|
||||||
// v's boundarys m- and m+:
|
// v's boundaries m- and m+:
|
||||||
// m- / 10^ep == v / 10^ep - delta_minus / denominator
|
// m- / 10^ep == v / 10^ep - delta_minus / denominator
|
||||||
// m+ / 10^ep == v / 10^ep + delta_plus / denominator
|
// m+ / 10^ep == v / 10^ep + delta_plus / denominator
|
||||||
// Or in other words:
|
// Or in other words:
|
||||||
|
@@ -25,141 +25,137 @@
|
|||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
#include "bignum.h"
|
#include "bignum.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
Bignum::Bignum()
|
Bignum::Chunk& Bignum::RawBigit(const int index) {
|
||||||
: bigits_buffer_(), bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
|
DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
|
||||||
for (int i = 0; i < kBigitCapacity; ++i) {
|
return bigits_buffer_[index];
|
||||||
bigits_[i] = 0;
|
}
|
||||||
}
|
|
||||||
|
|
||||||
|
const Bignum::Chunk& Bignum::RawBigit(const int index) const {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
|
||||||
|
return bigits_buffer_[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
template<typename S>
|
template<typename S>
|
||||||
static int BitSize(S value) {
|
static int BitSize(const S value) {
|
||||||
(void) value; // Mark variable as used.
|
(void) value; // Mark variable as used.
|
||||||
return 8 * sizeof(value);
|
return 8 * sizeof(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guaranteed to lie in one Bigit.
|
// Guaranteed to lie in one Bigit.
|
||||||
void Bignum::AssignUInt16(uint16_t value) {
|
void Bignum::AssignUInt16(const uint16_t value) {
|
||||||
ASSERT(kBigitSize >= BitSize(value));
|
DOUBLE_CONVERSION_ASSERT(kBigitSize >= BitSize(value));
|
||||||
Zero();
|
Zero();
|
||||||
if (value == 0) return;
|
if (value > 0) {
|
||||||
|
RawBigit(0) = value;
|
||||||
EnsureCapacity(1);
|
used_bigits_ = 1;
|
||||||
bigits_[0] = value;
|
}
|
||||||
used_digits_ = 1;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::AssignUInt64(uint64_t value) {
|
void Bignum::AssignUInt64(uint64_t value) {
|
||||||
const int kUInt64Size = 64;
|
|
||||||
|
|
||||||
Zero();
|
Zero();
|
||||||
if (value == 0) return;
|
for(int i = 0; value > 0; ++i) {
|
||||||
|
RawBigit(i) = value & kBigitMask;
|
||||||
int needed_bigits = kUInt64Size / kBigitSize + 1;
|
value >>= kBigitSize;
|
||||||
EnsureCapacity(needed_bigits);
|
++used_bigits_;
|
||||||
for (int i = 0; i < needed_bigits; ++i) {
|
|
||||||
bigits_[i] = value & kBigitMask;
|
|
||||||
value = value >> kBigitSize;
|
|
||||||
}
|
}
|
||||||
used_digits_ = needed_bigits;
|
|
||||||
Clamp();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::AssignBignum(const Bignum& other) {
|
void Bignum::AssignBignum(const Bignum& other) {
|
||||||
exponent_ = other.exponent_;
|
exponent_ = other.exponent_;
|
||||||
for (int i = 0; i < other.used_digits_; ++i) {
|
for (int i = 0; i < other.used_bigits_; ++i) {
|
||||||
bigits_[i] = other.bigits_[i];
|
RawBigit(i) = other.RawBigit(i);
|
||||||
}
|
}
|
||||||
// Clear the excess digits (if there were any).
|
used_bigits_ = other.used_bigits_;
|
||||||
for (int i = other.used_digits_; i < used_digits_; ++i) {
|
|
||||||
bigits_[i] = 0;
|
|
||||||
}
|
|
||||||
used_digits_ = other.used_digits_;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static uint64_t ReadUInt64(Vector<const char> buffer,
|
static uint64_t ReadUInt64(const Vector<const char> buffer,
|
||||||
int from,
|
const int from,
|
||||||
int digits_to_read) {
|
const int digits_to_read) {
|
||||||
uint64_t result = 0;
|
uint64_t result = 0;
|
||||||
for (int i = from; i < from + digits_to_read; ++i) {
|
for (int i = from; i < from + digits_to_read; ++i) {
|
||||||
int digit = buffer[i] - '0';
|
const int digit = buffer[i] - '0';
|
||||||
ASSERT(0 <= digit && digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9);
|
||||||
result = result * 10 + digit;
|
result = result * 10 + digit;
|
||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::AssignDecimalString(Vector<const char> value) {
|
void Bignum::AssignDecimalString(const Vector<const char> value) {
|
||||||
// 2^64 = 18446744073709551616 > 10^19
|
// 2^64 = 18446744073709551616 > 10^19
|
||||||
const int kMaxUint64DecimalDigits = 19;
|
static const int kMaxUint64DecimalDigits = 19;
|
||||||
Zero();
|
Zero();
|
||||||
int length = value.length();
|
int length = value.length();
|
||||||
unsigned int pos = 0;
|
unsigned pos = 0;
|
||||||
// Let's just say that each digit needs 4 bits.
|
// Let's just say that each digit needs 4 bits.
|
||||||
while (length >= kMaxUint64DecimalDigits) {
|
while (length >= kMaxUint64DecimalDigits) {
|
||||||
uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
|
const uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
|
||||||
pos += kMaxUint64DecimalDigits;
|
pos += kMaxUint64DecimalDigits;
|
||||||
length -= kMaxUint64DecimalDigits;
|
length -= kMaxUint64DecimalDigits;
|
||||||
MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
|
MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
|
||||||
AddUInt64(digits);
|
AddUInt64(digits);
|
||||||
}
|
}
|
||||||
uint64_t digits = ReadUInt64(value, pos, length);
|
const uint64_t digits = ReadUInt64(value, pos, length);
|
||||||
MultiplyByPowerOfTen(length);
|
MultiplyByPowerOfTen(length);
|
||||||
AddUInt64(digits);
|
AddUInt64(digits);
|
||||||
Clamp();
|
Clamp();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static int HexCharValue(char c) {
|
static uint64_t HexCharValue(const int c) {
|
||||||
if ('0' <= c && c <= '9') return c - '0';
|
if ('0' <= c && c <= '9') {
|
||||||
if ('a' <= c && c <= 'f') return 10 + c - 'a';
|
return c - '0';
|
||||||
ASSERT('A' <= c && c <= 'F');
|
}
|
||||||
|
if ('a' <= c && c <= 'f') {
|
||||||
|
return 10 + c - 'a';
|
||||||
|
}
|
||||||
|
DOUBLE_CONVERSION_ASSERT('A' <= c && c <= 'F');
|
||||||
return 10 + c - 'A';
|
return 10 + c - 'A';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Unlike AssignDecimalString(), this function is "only" used
|
||||||
|
// for unit-tests and therefore not performance critical.
|
||||||
void Bignum::AssignHexString(Vector<const char> value) {
|
void Bignum::AssignHexString(Vector<const char> value) {
|
||||||
Zero();
|
Zero();
|
||||||
int length = value.length();
|
// Required capacity could be reduced by ignoring leading zeros.
|
||||||
|
EnsureCapacity(((value.length() * 4) + kBigitSize - 1) / kBigitSize);
|
||||||
int needed_bigits = length * 4 / kBigitSize + 1;
|
DOUBLE_CONVERSION_ASSERT(sizeof(uint64_t) * 8 >= kBigitSize + 4); // TODO: static_assert
|
||||||
EnsureCapacity(needed_bigits);
|
// Accumulates converted hex digits until at least kBigitSize bits.
|
||||||
int string_index = length - 1;
|
// Works with non-factor-of-four kBigitSizes.
|
||||||
for (int i = 0; i < needed_bigits - 1; ++i) {
|
uint64_t tmp = 0; // Accumulates converted hex digits until at least
|
||||||
// These bigits are guaranteed to be "full".
|
for (int cnt = 0; !value.is_empty(); value.pop_back()) {
|
||||||
Chunk current_bigit = 0;
|
tmp |= (HexCharValue(value.last()) << cnt);
|
||||||
for (int j = 0; j < kBigitSize / 4; j++) {
|
if ((cnt += 4) >= kBigitSize) {
|
||||||
current_bigit += HexCharValue(value[string_index--]) << (j * 4);
|
RawBigit(used_bigits_++) = (tmp & kBigitMask);
|
||||||
|
cnt -= kBigitSize;
|
||||||
|
tmp >>= kBigitSize;
|
||||||
}
|
}
|
||||||
bigits_[i] = current_bigit;
|
|
||||||
}
|
}
|
||||||
used_digits_ = needed_bigits - 1;
|
if (tmp > 0) {
|
||||||
|
RawBigit(used_bigits_++) = tmp;
|
||||||
Chunk most_significant_bigit = 0; // Could be = 0;
|
|
||||||
for (int j = 0; j <= string_index; ++j) {
|
|
||||||
most_significant_bigit <<= 4;
|
|
||||||
most_significant_bigit += HexCharValue(value[j]);
|
|
||||||
}
|
|
||||||
if (most_significant_bigit != 0) {
|
|
||||||
bigits_[used_digits_] = most_significant_bigit;
|
|
||||||
used_digits_++;
|
|
||||||
}
|
}
|
||||||
Clamp();
|
Clamp();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::AddUInt64(uint64_t operand) {
|
void Bignum::AddUInt64(const uint64_t operand) {
|
||||||
if (operand == 0) return;
|
if (operand == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
Bignum other;
|
Bignum other;
|
||||||
other.AssignUInt64(operand);
|
other.AssignUInt64(operand);
|
||||||
AddBignum(other);
|
AddBignum(other);
|
||||||
@@ -167,8 +163,8 @@ void Bignum::AddUInt64(uint64_t operand) {
|
|||||||
|
|
||||||
|
|
||||||
void Bignum::AddBignum(const Bignum& other) {
|
void Bignum::AddBignum(const Bignum& other) {
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
ASSERT(other.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
|
||||||
|
|
||||||
// If this has a greater exponent than other append zero-bigits to this.
|
// If this has a greater exponent than other append zero-bigits to this.
|
||||||
// After this call exponent_ <= other.exponent_.
|
// After this call exponent_ <= other.exponent_.
|
||||||
@@ -186,48 +182,52 @@ void Bignum::AddBignum(const Bignum& other) {
|
|||||||
// cccccccccccc 0000
|
// cccccccccccc 0000
|
||||||
// In both cases we might need a carry bigit.
|
// In both cases we might need a carry bigit.
|
||||||
|
|
||||||
EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
|
EnsureCapacity(1 + (std::max)(BigitLength(), other.BigitLength()) - exponent_);
|
||||||
Chunk carry = 0;
|
Chunk carry = 0;
|
||||||
int bigit_pos = other.exponent_ - exponent_;
|
int bigit_pos = other.exponent_ - exponent_;
|
||||||
ASSERT(bigit_pos >= 0);
|
DOUBLE_CONVERSION_ASSERT(bigit_pos >= 0);
|
||||||
for (int i = 0; i < other.used_digits_; ++i) {
|
for (int i = used_bigits_; i < bigit_pos; ++i) {
|
||||||
Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
|
RawBigit(i) = 0;
|
||||||
bigits_[bigit_pos] = sum & kBigitMask;
|
}
|
||||||
carry = sum >> kBigitSize;
|
for (int i = 0; i < other.used_bigits_; ++i) {
|
||||||
bigit_pos++;
|
const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
|
||||||
|
const Chunk sum = my + other.RawBigit(i) + carry;
|
||||||
|
RawBigit(bigit_pos) = sum & kBigitMask;
|
||||||
|
carry = sum >> kBigitSize;
|
||||||
|
++bigit_pos;
|
||||||
}
|
}
|
||||||
|
|
||||||
while (carry != 0) {
|
while (carry != 0) {
|
||||||
Chunk sum = bigits_[bigit_pos] + carry;
|
const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
|
||||||
bigits_[bigit_pos] = sum & kBigitMask;
|
const Chunk sum = my + carry;
|
||||||
|
RawBigit(bigit_pos) = sum & kBigitMask;
|
||||||
carry = sum >> kBigitSize;
|
carry = sum >> kBigitSize;
|
||||||
bigit_pos++;
|
++bigit_pos;
|
||||||
}
|
}
|
||||||
used_digits_ = Max(bigit_pos, used_digits_);
|
used_bigits_ = (std::max)(bigit_pos, static_cast<int>(used_bigits_));
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::SubtractBignum(const Bignum& other) {
|
void Bignum::SubtractBignum(const Bignum& other) {
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
ASSERT(other.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
|
||||||
// We require this to be bigger than other.
|
// We require this to be bigger than other.
|
||||||
ASSERT(LessEqual(other, *this));
|
DOUBLE_CONVERSION_ASSERT(LessEqual(other, *this));
|
||||||
|
|
||||||
Align(other);
|
Align(other);
|
||||||
|
|
||||||
int offset = other.exponent_ - exponent_;
|
const int offset = other.exponent_ - exponent_;
|
||||||
Chunk borrow = 0;
|
Chunk borrow = 0;
|
||||||
int i;
|
int i;
|
||||||
for (i = 0; i < other.used_digits_; ++i) {
|
for (i = 0; i < other.used_bigits_; ++i) {
|
||||||
ASSERT((borrow == 0) || (borrow == 1));
|
DOUBLE_CONVERSION_ASSERT((borrow == 0) || (borrow == 1));
|
||||||
Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
|
const Chunk difference = RawBigit(i + offset) - other.RawBigit(i) - borrow;
|
||||||
bigits_[i + offset] = difference & kBigitMask;
|
RawBigit(i + offset) = difference & kBigitMask;
|
||||||
borrow = difference >> (kChunkSize - 1);
|
borrow = difference >> (kChunkSize - 1);
|
||||||
}
|
}
|
||||||
while (borrow != 0) {
|
while (borrow != 0) {
|
||||||
Chunk difference = bigits_[i + offset] - borrow;
|
const Chunk difference = RawBigit(i + offset) - borrow;
|
||||||
bigits_[i + offset] = difference & kBigitMask;
|
RawBigit(i + offset) = difference & kBigitMask;
|
||||||
borrow = difference >> (kChunkSize - 1);
|
borrow = difference >> (kChunkSize - 1);
|
||||||
++i;
|
++i;
|
||||||
}
|
}
|
||||||
@@ -235,91 +235,105 @@ void Bignum::SubtractBignum(const Bignum& other) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::ShiftLeft(int shift_amount) {
|
void Bignum::ShiftLeft(const int shift_amount) {
|
||||||
if (used_digits_ == 0) return;
|
if (used_bigits_ == 0) {
|
||||||
exponent_ += shift_amount / kBigitSize;
|
return;
|
||||||
int local_shift = shift_amount % kBigitSize;
|
}
|
||||||
EnsureCapacity(used_digits_ + 1);
|
exponent_ += (shift_amount / kBigitSize);
|
||||||
|
const int local_shift = shift_amount % kBigitSize;
|
||||||
|
EnsureCapacity(used_bigits_ + 1);
|
||||||
BigitsShiftLeft(local_shift);
|
BigitsShiftLeft(local_shift);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::MultiplyByUInt32(uint32_t factor) {
|
void Bignum::MultiplyByUInt32(const uint32_t factor) {
|
||||||
if (factor == 1) return;
|
if (factor == 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (factor == 0) {
|
if (factor == 0) {
|
||||||
Zero();
|
Zero();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (used_digits_ == 0) return;
|
if (used_bigits_ == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// The product of a bigit with the factor is of size kBigitSize + 32.
|
// The product of a bigit with the factor is of size kBigitSize + 32.
|
||||||
// Assert that this number + 1 (for the carry) fits into double chunk.
|
// Assert that this number + 1 (for the carry) fits into double chunk.
|
||||||
ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
|
DOUBLE_CONVERSION_ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
|
||||||
DoubleChunk carry = 0;
|
DoubleChunk carry = 0;
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
for (int i = 0; i < used_bigits_; ++i) {
|
||||||
DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
|
const DoubleChunk product = static_cast<DoubleChunk>(factor) * RawBigit(i) + carry;
|
||||||
bigits_[i] = static_cast<Chunk>(product & kBigitMask);
|
RawBigit(i) = static_cast<Chunk>(product & kBigitMask);
|
||||||
carry = (product >> kBigitSize);
|
carry = (product >> kBigitSize);
|
||||||
}
|
}
|
||||||
while (carry != 0) {
|
while (carry != 0) {
|
||||||
EnsureCapacity(used_digits_ + 1);
|
EnsureCapacity(used_bigits_ + 1);
|
||||||
bigits_[used_digits_] = carry & kBigitMask;
|
RawBigit(used_bigits_) = carry & kBigitMask;
|
||||||
used_digits_++;
|
used_bigits_++;
|
||||||
carry >>= kBigitSize;
|
carry >>= kBigitSize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::MultiplyByUInt64(uint64_t factor) {
|
void Bignum::MultiplyByUInt64(const uint64_t factor) {
|
||||||
if (factor == 1) return;
|
if (factor == 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (factor == 0) {
|
if (factor == 0) {
|
||||||
Zero();
|
Zero();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
ASSERT(kBigitSize < 32);
|
if (used_bigits_ == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
DOUBLE_CONVERSION_ASSERT(kBigitSize < 32);
|
||||||
uint64_t carry = 0;
|
uint64_t carry = 0;
|
||||||
uint64_t low = factor & 0xFFFFFFFF;
|
const uint64_t low = factor & 0xFFFFFFFF;
|
||||||
uint64_t high = factor >> 32;
|
const uint64_t high = factor >> 32;
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
for (int i = 0; i < used_bigits_; ++i) {
|
||||||
uint64_t product_low = low * bigits_[i];
|
const uint64_t product_low = low * RawBigit(i);
|
||||||
uint64_t product_high = high * bigits_[i];
|
const uint64_t product_high = high * RawBigit(i);
|
||||||
uint64_t tmp = (carry & kBigitMask) + product_low;
|
const uint64_t tmp = (carry & kBigitMask) + product_low;
|
||||||
bigits_[i] = tmp & kBigitMask;
|
RawBigit(i) = tmp & kBigitMask;
|
||||||
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
|
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
|
||||||
(product_high << (32 - kBigitSize));
|
(product_high << (32 - kBigitSize));
|
||||||
}
|
}
|
||||||
while (carry != 0) {
|
while (carry != 0) {
|
||||||
EnsureCapacity(used_digits_ + 1);
|
EnsureCapacity(used_bigits_ + 1);
|
||||||
bigits_[used_digits_] = carry & kBigitMask;
|
RawBigit(used_bigits_) = carry & kBigitMask;
|
||||||
used_digits_++;
|
used_bigits_++;
|
||||||
carry >>= kBigitSize;
|
carry >>= kBigitSize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::MultiplyByPowerOfTen(int exponent) {
|
void Bignum::MultiplyByPowerOfTen(const int exponent) {
|
||||||
const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
|
static const uint64_t kFive27 = DOUBLE_CONVERSION_UINT64_2PART_C(0x6765c793, fa10079d);
|
||||||
const uint16_t kFive1 = 5;
|
static const uint16_t kFive1 = 5;
|
||||||
const uint16_t kFive2 = kFive1 * 5;
|
static const uint16_t kFive2 = kFive1 * 5;
|
||||||
const uint16_t kFive3 = kFive2 * 5;
|
static const uint16_t kFive3 = kFive2 * 5;
|
||||||
const uint16_t kFive4 = kFive3 * 5;
|
static const uint16_t kFive4 = kFive3 * 5;
|
||||||
const uint16_t kFive5 = kFive4 * 5;
|
static const uint16_t kFive5 = kFive4 * 5;
|
||||||
const uint16_t kFive6 = kFive5 * 5;
|
static const uint16_t kFive6 = kFive5 * 5;
|
||||||
const uint32_t kFive7 = kFive6 * 5;
|
static const uint32_t kFive7 = kFive6 * 5;
|
||||||
const uint32_t kFive8 = kFive7 * 5;
|
static const uint32_t kFive8 = kFive7 * 5;
|
||||||
const uint32_t kFive9 = kFive8 * 5;
|
static const uint32_t kFive9 = kFive8 * 5;
|
||||||
const uint32_t kFive10 = kFive9 * 5;
|
static const uint32_t kFive10 = kFive9 * 5;
|
||||||
const uint32_t kFive11 = kFive10 * 5;
|
static const uint32_t kFive11 = kFive10 * 5;
|
||||||
const uint32_t kFive12 = kFive11 * 5;
|
static const uint32_t kFive12 = kFive11 * 5;
|
||||||
const uint32_t kFive13 = kFive12 * 5;
|
static const uint32_t kFive13 = kFive12 * 5;
|
||||||
const uint32_t kFive1_to_12[] =
|
static const uint32_t kFive1_to_12[] =
|
||||||
{ kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
|
{ kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
|
||||||
kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
|
kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
|
||||||
|
|
||||||
ASSERT(exponent >= 0);
|
DOUBLE_CONVERSION_ASSERT(exponent >= 0);
|
||||||
if (exponent == 0) return;
|
|
||||||
if (used_digits_ == 0) return;
|
|
||||||
|
|
||||||
|
if (exponent == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (used_bigits_ == 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
// We shift by exponent at the end just before returning.
|
// We shift by exponent at the end just before returning.
|
||||||
int remaining_exponent = exponent;
|
int remaining_exponent = exponent;
|
||||||
while (remaining_exponent >= 27) {
|
while (remaining_exponent >= 27) {
|
||||||
@@ -338,8 +352,8 @@ void Bignum::MultiplyByPowerOfTen(int exponent) {
|
|||||||
|
|
||||||
|
|
||||||
void Bignum::Square() {
|
void Bignum::Square() {
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
int product_length = 2 * used_digits_;
|
const int product_length = 2 * used_bigits_;
|
||||||
EnsureCapacity(product_length);
|
EnsureCapacity(product_length);
|
||||||
|
|
||||||
// Comba multiplication: compute each column separately.
|
// Comba multiplication: compute each column separately.
|
||||||
@@ -354,64 +368,64 @@ void Bignum::Square() {
|
|||||||
//
|
//
|
||||||
// Assert that the additional number of bits in a DoubleChunk are enough to
|
// Assert that the additional number of bits in a DoubleChunk are enough to
|
||||||
// sum up used_digits of Bigit*Bigit.
|
// sum up used_digits of Bigit*Bigit.
|
||||||
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
|
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_bigits_) {
|
||||||
UNIMPLEMENTED();
|
DOUBLE_CONVERSION_UNIMPLEMENTED();
|
||||||
}
|
}
|
||||||
DoubleChunk accumulator = 0;
|
DoubleChunk accumulator = 0;
|
||||||
// First shift the digits so we don't overwrite them.
|
// First shift the digits so we don't overwrite them.
|
||||||
int copy_offset = used_digits_;
|
const int copy_offset = used_bigits_;
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
for (int i = 0; i < used_bigits_; ++i) {
|
||||||
bigits_[copy_offset + i] = bigits_[i];
|
RawBigit(copy_offset + i) = RawBigit(i);
|
||||||
}
|
}
|
||||||
// We have two loops to avoid some 'if's in the loop.
|
// We have two loops to avoid some 'if's in the loop.
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
for (int i = 0; i < used_bigits_; ++i) {
|
||||||
// Process temporary digit i with power i.
|
// Process temporary digit i with power i.
|
||||||
// The sum of the two indices must be equal to i.
|
// The sum of the two indices must be equal to i.
|
||||||
int bigit_index1 = i;
|
int bigit_index1 = i;
|
||||||
int bigit_index2 = 0;
|
int bigit_index2 = 0;
|
||||||
// Sum all of the sub-products.
|
// Sum all of the sub-products.
|
||||||
while (bigit_index1 >= 0) {
|
while (bigit_index1 >= 0) {
|
||||||
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
|
||||||
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
|
||||||
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
||||||
bigit_index1--;
|
bigit_index1--;
|
||||||
bigit_index2++;
|
bigit_index2++;
|
||||||
}
|
}
|
||||||
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
|
||||||
accumulator >>= kBigitSize;
|
accumulator >>= kBigitSize;
|
||||||
}
|
}
|
||||||
for (int i = used_digits_; i < product_length; ++i) {
|
for (int i = used_bigits_; i < product_length; ++i) {
|
||||||
int bigit_index1 = used_digits_ - 1;
|
int bigit_index1 = used_bigits_ - 1;
|
||||||
int bigit_index2 = i - bigit_index1;
|
int bigit_index2 = i - bigit_index1;
|
||||||
// Invariant: sum of both indices is again equal to i.
|
// Invariant: sum of both indices is again equal to i.
|
||||||
// Inner loop runs 0 times on last iteration, emptying accumulator.
|
// Inner loop runs 0 times on last iteration, emptying accumulator.
|
||||||
while (bigit_index2 < used_digits_) {
|
while (bigit_index2 < used_bigits_) {
|
||||||
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
|
||||||
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
|
||||||
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
||||||
bigit_index1--;
|
bigit_index1--;
|
||||||
bigit_index2++;
|
bigit_index2++;
|
||||||
}
|
}
|
||||||
// The overwritten bigits_[i] will never be read in further loop iterations,
|
// The overwritten RawBigit(i) will never be read in further loop iterations,
|
||||||
// because bigit_index1 and bigit_index2 are always greater
|
// because bigit_index1 and bigit_index2 are always greater
|
||||||
// than i - used_digits_.
|
// than i - used_bigits_.
|
||||||
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
|
||||||
accumulator >>= kBigitSize;
|
accumulator >>= kBigitSize;
|
||||||
}
|
}
|
||||||
// Since the result was guaranteed to lie inside the number the
|
// Since the result was guaranteed to lie inside the number the
|
||||||
// accumulator must be 0 now.
|
// accumulator must be 0 now.
|
||||||
ASSERT(accumulator == 0);
|
DOUBLE_CONVERSION_ASSERT(accumulator == 0);
|
||||||
|
|
||||||
// Don't forget to update the used_digits and the exponent.
|
// Don't forget to update the used_digits and the exponent.
|
||||||
used_digits_ = product_length;
|
used_bigits_ = product_length;
|
||||||
exponent_ *= 2;
|
exponent_ *= 2;
|
||||||
Clamp();
|
Clamp();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
void Bignum::AssignPowerUInt16(uint16_t base, const int power_exponent) {
|
||||||
ASSERT(base != 0);
|
DOUBLE_CONVERSION_ASSERT(base != 0);
|
||||||
ASSERT(power_exponent >= 0);
|
DOUBLE_CONVERSION_ASSERT(power_exponent >= 0);
|
||||||
if (power_exponent == 0) {
|
if (power_exponent == 0) {
|
||||||
AssignUInt16(1);
|
AssignUInt16(1);
|
||||||
return;
|
return;
|
||||||
@@ -431,7 +445,7 @@ void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
|||||||
tmp_base >>= 1;
|
tmp_base >>= 1;
|
||||||
bit_size++;
|
bit_size++;
|
||||||
}
|
}
|
||||||
int final_size = bit_size * power_exponent;
|
const int final_size = bit_size * power_exponent;
|
||||||
// 1 extra bigit for the shifting, and one for rounded final_size.
|
// 1 extra bigit for the shifting, and one for rounded final_size.
|
||||||
EnsureCapacity(final_size / kBigitSize + 2);
|
EnsureCapacity(final_size / kBigitSize + 2);
|
||||||
|
|
||||||
@@ -452,10 +466,10 @@ void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
|||||||
// Verify that there is enough space in this_value to perform the
|
// Verify that there is enough space in this_value to perform the
|
||||||
// multiplication. The first bit_size bits must be 0.
|
// multiplication. The first bit_size bits must be 0.
|
||||||
if ((power_exponent & mask) != 0) {
|
if ((power_exponent & mask) != 0) {
|
||||||
ASSERT(bit_size > 0);
|
DOUBLE_CONVERSION_ASSERT(bit_size > 0);
|
||||||
uint64_t base_bits_mask =
|
const uint64_t base_bits_mask =
|
||||||
~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
|
~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
|
||||||
bool high_bits_zero = (this_value & base_bits_mask) == 0;
|
const bool high_bits_zero = (this_value & base_bits_mask) == 0;
|
||||||
if (high_bits_zero) {
|
if (high_bits_zero) {
|
||||||
this_value *= base;
|
this_value *= base;
|
||||||
} else {
|
} else {
|
||||||
@@ -485,9 +499,9 @@ void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
|||||||
|
|
||||||
// Precondition: this/other < 16bit.
|
// Precondition: this/other < 16bit.
|
||||||
uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
ASSERT(other.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(other.IsClamped());
|
||||||
ASSERT(other.used_digits_ > 0);
|
DOUBLE_CONVERSION_ASSERT(other.used_bigits_ > 0);
|
||||||
|
|
||||||
// Easy case: if we have less digits than the divisor than the result is 0.
|
// Easy case: if we have less digits than the divisor than the result is 0.
|
||||||
// Note: this handles the case where this == 0, too.
|
// Note: this handles the case where this == 0, too.
|
||||||
@@ -505,34 +519,34 @@ uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
|||||||
// This naive approach is extremely inefficient if `this` divided by other
|
// This naive approach is extremely inefficient if `this` divided by other
|
||||||
// is big. This function is implemented for doubleToString where
|
// is big. This function is implemented for doubleToString where
|
||||||
// the result should be small (less than 10).
|
// the result should be small (less than 10).
|
||||||
ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
|
DOUBLE_CONVERSION_ASSERT(other.RawBigit(other.used_bigits_ - 1) >= ((1 << kBigitSize) / 16));
|
||||||
ASSERT(bigits_[used_digits_ - 1] < 0x10000);
|
DOUBLE_CONVERSION_ASSERT(RawBigit(used_bigits_ - 1) < 0x10000);
|
||||||
// Remove the multiples of the first digit.
|
// Remove the multiples of the first digit.
|
||||||
// Example this = 23 and other equals 9. -> Remove 2 multiples.
|
// Example this = 23 and other equals 9. -> Remove 2 multiples.
|
||||||
result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
|
result += static_cast<uint16_t>(RawBigit(used_bigits_ - 1));
|
||||||
SubtractTimes(other, bigits_[used_digits_ - 1]);
|
SubtractTimes(other, RawBigit(used_bigits_ - 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(BigitLength() == other.BigitLength());
|
DOUBLE_CONVERSION_ASSERT(BigitLength() == other.BigitLength());
|
||||||
|
|
||||||
// Both bignums are at the same length now.
|
// Both bignums are at the same length now.
|
||||||
// Since other has more than 0 digits we know that the access to
|
// Since other has more than 0 digits we know that the access to
|
||||||
// bigits_[used_digits_ - 1] is safe.
|
// RawBigit(used_bigits_ - 1) is safe.
|
||||||
Chunk this_bigit = bigits_[used_digits_ - 1];
|
const Chunk this_bigit = RawBigit(used_bigits_ - 1);
|
||||||
Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
|
const Chunk other_bigit = other.RawBigit(other.used_bigits_ - 1);
|
||||||
|
|
||||||
if (other.used_digits_ == 1) {
|
if (other.used_bigits_ == 1) {
|
||||||
// Shortcut for easy (and common) case.
|
// Shortcut for easy (and common) case.
|
||||||
int quotient = this_bigit / other_bigit;
|
int quotient = this_bigit / other_bigit;
|
||||||
bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
|
RawBigit(used_bigits_ - 1) = this_bigit - other_bigit * quotient;
|
||||||
ASSERT(quotient < 0x10000);
|
DOUBLE_CONVERSION_ASSERT(quotient < 0x10000);
|
||||||
result += static_cast<uint16_t>(quotient);
|
result += static_cast<uint16_t>(quotient);
|
||||||
Clamp();
|
Clamp();
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
int division_estimate = this_bigit / (other_bigit + 1);
|
const int division_estimate = this_bigit / (other_bigit + 1);
|
||||||
ASSERT(division_estimate < 0x10000);
|
DOUBLE_CONVERSION_ASSERT(division_estimate < 0x10000);
|
||||||
result += static_cast<uint16_t>(division_estimate);
|
result += static_cast<uint16_t>(division_estimate);
|
||||||
SubtractTimes(other, division_estimate);
|
SubtractTimes(other, division_estimate);
|
||||||
|
|
||||||
@@ -552,7 +566,7 @@ uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
|||||||
|
|
||||||
template<typename S>
|
template<typename S>
|
||||||
static int SizeInHexChars(S number) {
|
static int SizeInHexChars(S number) {
|
||||||
ASSERT(number > 0);
|
DOUBLE_CONVERSION_ASSERT(number > 0);
|
||||||
int result = 0;
|
int result = 0;
|
||||||
while (number != 0) {
|
while (number != 0) {
|
||||||
number >>= 4;
|
number >>= 4;
|
||||||
@@ -562,29 +576,35 @@ static int SizeInHexChars(S number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static char HexCharOfValue(int value) {
|
static char HexCharOfValue(const int value) {
|
||||||
ASSERT(0 <= value && value <= 16);
|
DOUBLE_CONVERSION_ASSERT(0 <= value && value <= 16);
|
||||||
if (value < 10) return static_cast<char>(value + '0');
|
if (value < 10) {
|
||||||
|
return static_cast<char>(value + '0');
|
||||||
|
}
|
||||||
return static_cast<char>(value - 10 + 'A');
|
return static_cast<char>(value - 10 + 'A');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
bool Bignum::ToHexString(char* buffer, int buffer_size) const {
|
bool Bignum::ToHexString(char* buffer, const int buffer_size) const {
|
||||||
ASSERT(IsClamped());
|
DOUBLE_CONVERSION_ASSERT(IsClamped());
|
||||||
// Each bigit must be printable as separate hex-character.
|
// Each bigit must be printable as separate hex-character.
|
||||||
ASSERT(kBigitSize % 4 == 0);
|
DOUBLE_CONVERSION_ASSERT(kBigitSize % 4 == 0);
|
||||||
const int kHexCharsPerBigit = kBigitSize / 4;
|
static const int kHexCharsPerBigit = kBigitSize / 4;
|
||||||
|
|
||||||
if (used_digits_ == 0) {
|
if (used_bigits_ == 0) {
|
||||||
if (buffer_size < 2) return false;
|
if (buffer_size < 2) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
buffer[0] = '0';
|
buffer[0] = '0';
|
||||||
buffer[1] = '\0';
|
buffer[1] = '\0';
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
// We add 1 for the terminating '\0' character.
|
// We add 1 for the terminating '\0' character.
|
||||||
int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
|
const int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
|
||||||
SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
|
SizeInHexChars(RawBigit(used_bigits_ - 1)) + 1;
|
||||||
if (needed_chars > buffer_size) return false;
|
if (needed_chars > buffer_size) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
int string_index = needed_chars - 1;
|
int string_index = needed_chars - 1;
|
||||||
buffer[string_index--] = '\0';
|
buffer[string_index--] = '\0';
|
||||||
for (int i = 0; i < exponent_; ++i) {
|
for (int i = 0; i < exponent_; ++i) {
|
||||||
@@ -592,15 +612,15 @@ bool Bignum::ToHexString(char* buffer, int buffer_size) const {
|
|||||||
buffer[string_index--] = '0';
|
buffer[string_index--] = '0';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (int i = 0; i < used_digits_ - 1; ++i) {
|
for (int i = 0; i < used_bigits_ - 1; ++i) {
|
||||||
Chunk current_bigit = bigits_[i];
|
Chunk current_bigit = RawBigit(i);
|
||||||
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
||||||
buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
|
buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
|
||||||
current_bigit >>= 4;
|
current_bigit >>= 4;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// And finally the last bigit.
|
// And finally the last bigit.
|
||||||
Chunk most_significant_bigit = bigits_[used_digits_ - 1];
|
Chunk most_significant_bigit = RawBigit(used_bigits_ - 1);
|
||||||
while (most_significant_bigit != 0) {
|
while (most_significant_bigit != 0) {
|
||||||
buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
|
buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
|
||||||
most_significant_bigit >>= 4;
|
most_significant_bigit >>= 4;
|
||||||
@@ -609,25 +629,37 @@ bool Bignum::ToHexString(char* buffer, int buffer_size) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
Bignum::Chunk Bignum::BigitAt(int index) const {
|
Bignum::Chunk Bignum::BigitOrZero(const int index) const {
|
||||||
if (index >= BigitLength()) return 0;
|
if (index >= BigitLength()) {
|
||||||
if (index < exponent_) return 0;
|
return 0;
|
||||||
return bigits_[index - exponent_];
|
}
|
||||||
|
if (index < exponent_) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return RawBigit(index - exponent_);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
int Bignum::Compare(const Bignum& a, const Bignum& b) {
|
int Bignum::Compare(const Bignum& a, const Bignum& b) {
|
||||||
ASSERT(a.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(a.IsClamped());
|
||||||
ASSERT(b.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(b.IsClamped());
|
||||||
int bigit_length_a = a.BigitLength();
|
const int bigit_length_a = a.BigitLength();
|
||||||
int bigit_length_b = b.BigitLength();
|
const int bigit_length_b = b.BigitLength();
|
||||||
if (bigit_length_a < bigit_length_b) return -1;
|
if (bigit_length_a < bigit_length_b) {
|
||||||
if (bigit_length_a > bigit_length_b) return +1;
|
return -1;
|
||||||
for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
|
}
|
||||||
Chunk bigit_a = a.BigitAt(i);
|
if (bigit_length_a > bigit_length_b) {
|
||||||
Chunk bigit_b = b.BigitAt(i);
|
return +1;
|
||||||
if (bigit_a < bigit_b) return -1;
|
}
|
||||||
if (bigit_a > bigit_b) return +1;
|
for (int i = bigit_length_a - 1; i >= (std::min)(a.exponent_, b.exponent_); --i) {
|
||||||
|
const Chunk bigit_a = a.BigitOrZero(i);
|
||||||
|
const Chunk bigit_b = b.BigitOrZero(i);
|
||||||
|
if (bigit_a < bigit_b) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if (bigit_a > bigit_b) {
|
||||||
|
return +1;
|
||||||
|
}
|
||||||
// Otherwise they are equal up to this digit. Try the next digit.
|
// Otherwise they are equal up to this digit. Try the next digit.
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
@@ -635,14 +667,18 @@ int Bignum::Compare(const Bignum& a, const Bignum& b) {
|
|||||||
|
|
||||||
|
|
||||||
int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
|
int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
|
||||||
ASSERT(a.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(a.IsClamped());
|
||||||
ASSERT(b.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(b.IsClamped());
|
||||||
ASSERT(c.IsClamped());
|
DOUBLE_CONVERSION_ASSERT(c.IsClamped());
|
||||||
if (a.BigitLength() < b.BigitLength()) {
|
if (a.BigitLength() < b.BigitLength()) {
|
||||||
return PlusCompare(b, a, c);
|
return PlusCompare(b, a, c);
|
||||||
}
|
}
|
||||||
if (a.BigitLength() + 1 < c.BigitLength()) return -1;
|
if (a.BigitLength() + 1 < c.BigitLength()) {
|
||||||
if (a.BigitLength() > c.BigitLength()) return +1;
|
return -1;
|
||||||
|
}
|
||||||
|
if (a.BigitLength() > c.BigitLength()) {
|
||||||
|
return +1;
|
||||||
|
}
|
||||||
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
|
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
|
||||||
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
|
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
|
||||||
// of 'a'.
|
// of 'a'.
|
||||||
@@ -652,92 +688,83 @@ int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
|
|||||||
|
|
||||||
Chunk borrow = 0;
|
Chunk borrow = 0;
|
||||||
// Starting at min_exponent all digits are == 0. So no need to compare them.
|
// Starting at min_exponent all digits are == 0. So no need to compare them.
|
||||||
int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
|
const int min_exponent = (std::min)((std::min)(a.exponent_, b.exponent_), c.exponent_);
|
||||||
for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
|
for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
|
||||||
Chunk chunk_a = a.BigitAt(i);
|
const Chunk chunk_a = a.BigitOrZero(i);
|
||||||
Chunk chunk_b = b.BigitAt(i);
|
const Chunk chunk_b = b.BigitOrZero(i);
|
||||||
Chunk chunk_c = c.BigitAt(i);
|
const Chunk chunk_c = c.BigitOrZero(i);
|
||||||
Chunk sum = chunk_a + chunk_b;
|
const Chunk sum = chunk_a + chunk_b;
|
||||||
if (sum > chunk_c + borrow) {
|
if (sum > chunk_c + borrow) {
|
||||||
return +1;
|
return +1;
|
||||||
} else {
|
} else {
|
||||||
borrow = chunk_c + borrow - sum;
|
borrow = chunk_c + borrow - sum;
|
||||||
if (borrow > 1) return -1;
|
if (borrow > 1) {
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
borrow <<= kBigitSize;
|
borrow <<= kBigitSize;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (borrow == 0) return 0;
|
if (borrow == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::Clamp() {
|
void Bignum::Clamp() {
|
||||||
while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
|
while (used_bigits_ > 0 && RawBigit(used_bigits_ - 1) == 0) {
|
||||||
used_digits_--;
|
used_bigits_--;
|
||||||
}
|
}
|
||||||
if (used_digits_ == 0) {
|
if (used_bigits_ == 0) {
|
||||||
// Zero.
|
// Zero.
|
||||||
exponent_ = 0;
|
exponent_ = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
bool Bignum::IsClamped() const {
|
|
||||||
return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void Bignum::Zero() {
|
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
|
||||||
bigits_[i] = 0;
|
|
||||||
}
|
|
||||||
used_digits_ = 0;
|
|
||||||
exponent_ = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void Bignum::Align(const Bignum& other) {
|
void Bignum::Align(const Bignum& other) {
|
||||||
if (exponent_ > other.exponent_) {
|
if (exponent_ > other.exponent_) {
|
||||||
// If "X" represents a "hidden" digit (by the exponent) then we are in the
|
// If "X" represents a "hidden" bigit (by the exponent) then we are in the
|
||||||
// following case (a == this, b == other):
|
// following case (a == this, b == other):
|
||||||
// a: aaaaaaXXXX or a: aaaaaXXX
|
// a: aaaaaaXXXX or a: aaaaaXXX
|
||||||
// b: bbbbbbX b: bbbbbbbbXX
|
// b: bbbbbbX b: bbbbbbbbXX
|
||||||
// We replace some of the hidden digits (X) of a with 0 digits.
|
// We replace some of the hidden digits (X) of a with 0 digits.
|
||||||
// a: aaaaaa000X or a: aaaaa0XX
|
// a: aaaaaa000X or a: aaaaa0XX
|
||||||
int zero_digits = exponent_ - other.exponent_;
|
const int zero_bigits = exponent_ - other.exponent_;
|
||||||
EnsureCapacity(used_digits_ + zero_digits);
|
EnsureCapacity(used_bigits_ + zero_bigits);
|
||||||
for (int i = used_digits_ - 1; i >= 0; --i) {
|
for (int i = used_bigits_ - 1; i >= 0; --i) {
|
||||||
bigits_[i + zero_digits] = bigits_[i];
|
RawBigit(i + zero_bigits) = RawBigit(i);
|
||||||
}
|
}
|
||||||
for (int i = 0; i < zero_digits; ++i) {
|
for (int i = 0; i < zero_bigits; ++i) {
|
||||||
bigits_[i] = 0;
|
RawBigit(i) = 0;
|
||||||
}
|
}
|
||||||
used_digits_ += zero_digits;
|
used_bigits_ += zero_bigits;
|
||||||
exponent_ -= zero_digits;
|
exponent_ -= zero_bigits;
|
||||||
ASSERT(used_digits_ >= 0);
|
|
||||||
ASSERT(exponent_ >= 0);
|
DOUBLE_CONVERSION_ASSERT(used_bigits_ >= 0);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(exponent_ >= 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::BigitsShiftLeft(int shift_amount) {
|
void Bignum::BigitsShiftLeft(const int shift_amount) {
|
||||||
ASSERT(shift_amount < kBigitSize);
|
DOUBLE_CONVERSION_ASSERT(shift_amount < kBigitSize);
|
||||||
ASSERT(shift_amount >= 0);
|
DOUBLE_CONVERSION_ASSERT(shift_amount >= 0);
|
||||||
Chunk carry = 0;
|
Chunk carry = 0;
|
||||||
for (int i = 0; i < used_digits_; ++i) {
|
for (int i = 0; i < used_bigits_; ++i) {
|
||||||
Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
|
const Chunk new_carry = RawBigit(i) >> (kBigitSize - shift_amount);
|
||||||
bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
|
RawBigit(i) = ((RawBigit(i) << shift_amount) + carry) & kBigitMask;
|
||||||
carry = new_carry;
|
carry = new_carry;
|
||||||
}
|
}
|
||||||
if (carry != 0) {
|
if (carry != 0) {
|
||||||
bigits_[used_digits_] = carry;
|
RawBigit(used_bigits_) = carry;
|
||||||
used_digits_++;
|
used_bigits_++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void Bignum::SubtractTimes(const Bignum& other, int factor) {
|
void Bignum::SubtractTimes(const Bignum& other, const int factor) {
|
||||||
ASSERT(exponent_ <= other.exponent_);
|
DOUBLE_CONVERSION_ASSERT(exponent_ <= other.exponent_);
|
||||||
if (factor < 3) {
|
if (factor < 3) {
|
||||||
for (int i = 0; i < factor; ++i) {
|
for (int i = 0; i < factor; ++i) {
|
||||||
SubtractBignum(other);
|
SubtractBignum(other);
|
||||||
@@ -745,19 +772,21 @@ void Bignum::SubtractTimes(const Bignum& other, int factor) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
Chunk borrow = 0;
|
Chunk borrow = 0;
|
||||||
int exponent_diff = other.exponent_ - exponent_;
|
const int exponent_diff = other.exponent_ - exponent_;
|
||||||
for (int i = 0; i < other.used_digits_; ++i) {
|
for (int i = 0; i < other.used_bigits_; ++i) {
|
||||||
DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
|
const DoubleChunk product = static_cast<DoubleChunk>(factor) * other.RawBigit(i);
|
||||||
DoubleChunk remove = borrow + product;
|
const DoubleChunk remove = borrow + product;
|
||||||
Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
|
const Chunk difference = RawBigit(i + exponent_diff) - (remove & kBigitMask);
|
||||||
bigits_[i + exponent_diff] = difference & kBigitMask;
|
RawBigit(i + exponent_diff) = difference & kBigitMask;
|
||||||
borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
|
borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
|
||||||
(remove >> kBigitSize));
|
(remove >> kBigitSize));
|
||||||
}
|
}
|
||||||
for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
|
for (int i = other.used_bigits_ + exponent_diff; i < used_bigits_; ++i) {
|
||||||
if (borrow == 0) return;
|
if (borrow == 0) {
|
||||||
Chunk difference = bigits_[i] - borrow;
|
return;
|
||||||
bigits_[i] = difference & kBigitMask;
|
}
|
||||||
|
const Chunk difference = RawBigit(i) - borrow;
|
||||||
|
RawBigit(i) = difference & kBigitMask;
|
||||||
borrow = difference >> (kChunkSize - 1);
|
borrow = difference >> (kChunkSize - 1);
|
||||||
}
|
}
|
||||||
Clamp();
|
Clamp();
|
||||||
|
@@ -39,26 +39,27 @@ class Bignum {
|
|||||||
// exponent.
|
// exponent.
|
||||||
static const int kMaxSignificantBits = 3584;
|
static const int kMaxSignificantBits = 3584;
|
||||||
|
|
||||||
Bignum();
|
Bignum() : used_bigits_(0), exponent_(0) {}
|
||||||
void AssignUInt16(uint16_t value);
|
|
||||||
|
void AssignUInt16(const uint16_t value);
|
||||||
void AssignUInt64(uint64_t value);
|
void AssignUInt64(uint64_t value);
|
||||||
void AssignBignum(const Bignum& other);
|
void AssignBignum(const Bignum& other);
|
||||||
|
|
||||||
void AssignDecimalString(Vector<const char> value);
|
void AssignDecimalString(const Vector<const char> value);
|
||||||
void AssignHexString(Vector<const char> value);
|
void AssignHexString(const Vector<const char> value);
|
||||||
|
|
||||||
void AssignPowerUInt16(uint16_t base, int exponent);
|
void AssignPowerUInt16(uint16_t base, const int exponent);
|
||||||
|
|
||||||
void AddUInt64(uint64_t operand);
|
void AddUInt64(const uint64_t operand);
|
||||||
void AddBignum(const Bignum& other);
|
void AddBignum(const Bignum& other);
|
||||||
// Precondition: this >= other.
|
// Precondition: this >= other.
|
||||||
void SubtractBignum(const Bignum& other);
|
void SubtractBignum(const Bignum& other);
|
||||||
|
|
||||||
void Square();
|
void Square();
|
||||||
void ShiftLeft(int shift_amount);
|
void ShiftLeft(const int shift_amount);
|
||||||
void MultiplyByUInt32(uint32_t factor);
|
void MultiplyByUInt32(const uint32_t factor);
|
||||||
void MultiplyByUInt64(uint64_t factor);
|
void MultiplyByUInt64(const uint64_t factor);
|
||||||
void MultiplyByPowerOfTen(int exponent);
|
void MultiplyByPowerOfTen(const int exponent);
|
||||||
void Times10() { return MultiplyByUInt32(10); }
|
void Times10() { return MultiplyByUInt32(10); }
|
||||||
// Pseudocode:
|
// Pseudocode:
|
||||||
// int result = this / other;
|
// int result = this / other;
|
||||||
@@ -66,7 +67,7 @@ class Bignum {
|
|||||||
// In the worst case this function is in O(this/other).
|
// In the worst case this function is in O(this/other).
|
||||||
uint16_t DivideModuloIntBignum(const Bignum& other);
|
uint16_t DivideModuloIntBignum(const Bignum& other);
|
||||||
|
|
||||||
bool ToHexString(char* buffer, int buffer_size) const;
|
bool ToHexString(char* buffer, const int buffer_size) const;
|
||||||
|
|
||||||
// Returns
|
// Returns
|
||||||
// -1 if a < b,
|
// -1 if a < b,
|
||||||
@@ -110,33 +111,40 @@ class Bignum {
|
|||||||
// grow. There are no checks if the stack-allocated space is sufficient.
|
// grow. There are no checks if the stack-allocated space is sufficient.
|
||||||
static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
|
static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
|
||||||
|
|
||||||
void EnsureCapacity(int size) {
|
static void EnsureCapacity(const int size) {
|
||||||
if (size > kBigitCapacity) {
|
if (size > kBigitCapacity) {
|
||||||
UNREACHABLE();
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
void Align(const Bignum& other);
|
void Align(const Bignum& other);
|
||||||
void Clamp();
|
void Clamp();
|
||||||
bool IsClamped() const;
|
bool IsClamped() const {
|
||||||
void Zero();
|
return used_bigits_ == 0 || RawBigit(used_bigits_ - 1) != 0;
|
||||||
|
}
|
||||||
|
void Zero() {
|
||||||
|
used_bigits_ = 0;
|
||||||
|
exponent_ = 0;
|
||||||
|
}
|
||||||
// Requires this to have enough capacity (no tests done).
|
// Requires this to have enough capacity (no tests done).
|
||||||
// Updates used_digits_ if necessary.
|
// Updates used_bigits_ if necessary.
|
||||||
// shift_amount must be < kBigitSize.
|
// shift_amount must be < kBigitSize.
|
||||||
void BigitsShiftLeft(int shift_amount);
|
void BigitsShiftLeft(const int shift_amount);
|
||||||
// BigitLength includes the "hidden" digits encoded in the exponent.
|
// BigitLength includes the "hidden" bigits encoded in the exponent.
|
||||||
int BigitLength() const { return used_digits_ + exponent_; }
|
int BigitLength() const { return used_bigits_ + exponent_; }
|
||||||
Chunk BigitAt(int index) const;
|
Chunk& RawBigit(const int index);
|
||||||
void SubtractTimes(const Bignum& other, int factor);
|
const Chunk& RawBigit(const int index) const;
|
||||||
|
Chunk BigitOrZero(const int index) const;
|
||||||
|
void SubtractTimes(const Bignum& other, const int factor);
|
||||||
|
|
||||||
|
// The Bignum's value is value(bigits_buffer_) * 2^(exponent_ * kBigitSize),
|
||||||
|
// where the value of the buffer consists of the lower kBigitSize bits of
|
||||||
|
// the first used_bigits_ Chunks in bigits_buffer_, first chunk has lowest
|
||||||
|
// significant bits.
|
||||||
|
int16_t used_bigits_;
|
||||||
|
int16_t exponent_;
|
||||||
Chunk bigits_buffer_[kBigitCapacity];
|
Chunk bigits_buffer_[kBigitCapacity];
|
||||||
// A vector backed by bigits_buffer_. This way accesses to the array are
|
|
||||||
// checked for out-of-bounds errors.
|
|
||||||
Vector<Chunk> bigits_;
|
|
||||||
int used_digits_;
|
|
||||||
// The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
|
|
||||||
int exponent_;
|
|
||||||
|
|
||||||
DC_DISALLOW_COPY_AND_ASSIGN(Bignum);
|
DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(Bignum);
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
@@ -35,6 +35,8 @@
|
|||||||
|
|
||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
|
namespace PowersOfTenCache {
|
||||||
|
|
||||||
struct CachedPower {
|
struct CachedPower {
|
||||||
uint64_t significand;
|
uint64_t significand;
|
||||||
int16_t binary_exponent;
|
int16_t binary_exponent;
|
||||||
@@ -42,103 +44,99 @@ struct CachedPower {
|
|||||||
};
|
};
|
||||||
|
|
||||||
static const CachedPower kCachedPowers[] = {
|
static const CachedPower kCachedPowers[] = {
|
||||||
{UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
|
||||||
{UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
|
||||||
{UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
|
||||||
{UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
|
||||||
{UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
|
||||||
{UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
|
||||||
{UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
|
||||||
{UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
|
||||||
{UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
|
||||||
{UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
|
||||||
{UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
|
||||||
{UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
|
||||||
{UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
|
||||||
{UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
|
||||||
{UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
|
||||||
{UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
|
||||||
{UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
|
||||||
{UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
|
||||||
{UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
|
||||||
{UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
|
||||||
{UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
|
||||||
{UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
|
||||||
{UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
|
||||||
{UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
|
||||||
{UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
|
||||||
{UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
|
||||||
{UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
|
||||||
{UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
|
||||||
{UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
|
||||||
{UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
|
||||||
{UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
|
||||||
{UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
|
||||||
{UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
|
||||||
{UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
|
||||||
{UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
|
||||||
{UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
|
||||||
{UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
|
||||||
{UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
|
||||||
{UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
|
||||||
{UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
|
||||||
{UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
|
||||||
{UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
|
||||||
{UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
|
||||||
{UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
|
||||||
{UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
|
||||||
{UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
|
||||||
{UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
|
||||||
{UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
|
||||||
{UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
|
||||||
{UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
|
||||||
{UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
|
||||||
{UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
|
||||||
{UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
|
||||||
{UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
|
||||||
{UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
|
||||||
{UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
|
||||||
{UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
|
||||||
{UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
|
||||||
{UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
|
||||||
{UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
|
||||||
{UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
|
||||||
{UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
|
||||||
{UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
|
||||||
{UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
|
||||||
{UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
|
||||||
{UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
|
||||||
{UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
|
||||||
{UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
|
||||||
{UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
|
||||||
{UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
|
||||||
{UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
|
||||||
{UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
|
||||||
{UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
|
||||||
{UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
|
||||||
{UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
|
||||||
{UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
|
||||||
{UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
|
||||||
{UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
|
||||||
{UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
|
||||||
{UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
|
||||||
{UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
|
||||||
{UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
|
||||||
{UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
|
||||||
{UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
|
||||||
{UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
|
||||||
{UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
|
||||||
{UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
|
{DOUBLE_CONVERSION_UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
|
||||||
};
|
};
|
||||||
|
|
||||||
static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
|
static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
|
||||||
static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
|
static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
|
||||||
// Difference between the decimal exponents in the table above.
|
|
||||||
const int PowersOfTenCache::kDecimalExponentDistance = 8;
|
|
||||||
const int PowersOfTenCache::kMinDecimalExponent = -348;
|
|
||||||
const int PowersOfTenCache::kMaxDecimalExponent = 340;
|
|
||||||
|
|
||||||
void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
void GetCachedPowerForBinaryExponentRange(
|
||||||
int min_exponent,
|
int min_exponent,
|
||||||
int max_exponent,
|
int max_exponent,
|
||||||
DiyFp* power,
|
DiyFp* power,
|
||||||
@@ -148,28 +146,30 @@ void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
|||||||
int foo = kCachedPowersOffset;
|
int foo = kCachedPowersOffset;
|
||||||
int index =
|
int index =
|
||||||
(foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
|
(foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
|
||||||
ASSERT(0 <= index && index < static_cast<int>(ARRAY_SIZE(kCachedPowers)));
|
DOUBLE_CONVERSION_ASSERT(0 <= index && index < static_cast<int>(DOUBLE_CONVERSION_ARRAY_SIZE(kCachedPowers)));
|
||||||
CachedPower cached_power = kCachedPowers[index];
|
CachedPower cached_power = kCachedPowers[index];
|
||||||
ASSERT(min_exponent <= cached_power.binary_exponent);
|
DOUBLE_CONVERSION_ASSERT(min_exponent <= cached_power.binary_exponent);
|
||||||
(void) max_exponent; // Mark variable as used.
|
(void) max_exponent; // Mark variable as used.
|
||||||
ASSERT(cached_power.binary_exponent <= max_exponent);
|
DOUBLE_CONVERSION_ASSERT(cached_power.binary_exponent <= max_exponent);
|
||||||
*decimal_exponent = cached_power.decimal_exponent;
|
*decimal_exponent = cached_power.decimal_exponent;
|
||||||
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
|
void GetCachedPowerForDecimalExponent(int requested_exponent,
|
||||||
DiyFp* power,
|
DiyFp* power,
|
||||||
int* found_exponent) {
|
int* found_exponent) {
|
||||||
ASSERT(kMinDecimalExponent <= requested_exponent);
|
DOUBLE_CONVERSION_ASSERT(kMinDecimalExponent <= requested_exponent);
|
||||||
ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
|
DOUBLE_CONVERSION_ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
|
||||||
int index =
|
int index =
|
||||||
(requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
|
(requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
|
||||||
CachedPower cached_power = kCachedPowers[index];
|
CachedPower cached_power = kCachedPowers[index];
|
||||||
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
||||||
*found_exponent = cached_power.decimal_exponent;
|
*found_exponent = cached_power.decimal_exponent;
|
||||||
ASSERT(*found_exponent <= requested_exponent);
|
DOUBLE_CONVERSION_ASSERT(*found_exponent <= requested_exponent);
|
||||||
ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
|
DOUBLE_CONVERSION_ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace PowersOfTenCache
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
@@ -32,32 +32,32 @@
|
|||||||
|
|
||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
class PowersOfTenCache {
|
namespace PowersOfTenCache {
|
||||||
public:
|
|
||||||
|
|
||||||
// Not all powers of ten are cached. The decimal exponent of two neighboring
|
// Not all powers of ten are cached. The decimal exponent of two neighboring
|
||||||
// cached numbers will differ by kDecimalExponentDistance.
|
// cached numbers will differ by kDecimalExponentDistance.
|
||||||
static const int kDecimalExponentDistance;
|
static const int kDecimalExponentDistance = 8;
|
||||||
|
|
||||||
static const int kMinDecimalExponent;
|
static const int kMinDecimalExponent = -348;
|
||||||
static const int kMaxDecimalExponent;
|
static const int kMaxDecimalExponent = 340;
|
||||||
|
|
||||||
// Returns a cached power-of-ten with a binary exponent in the range
|
// Returns a cached power-of-ten with a binary exponent in the range
|
||||||
// [min_exponent; max_exponent] (boundaries included).
|
// [min_exponent; max_exponent] (boundaries included).
|
||||||
static void GetCachedPowerForBinaryExponentRange(int min_exponent,
|
void GetCachedPowerForBinaryExponentRange(int min_exponent,
|
||||||
int max_exponent,
|
int max_exponent,
|
||||||
DiyFp* power,
|
DiyFp* power,
|
||||||
int* decimal_exponent);
|
int* decimal_exponent);
|
||||||
|
|
||||||
// Returns a cached power of ten x ~= 10^k such that
|
// Returns a cached power of ten x ~= 10^k such that
|
||||||
// k <= decimal_exponent < k + kCachedPowersDecimalDistance.
|
// k <= decimal_exponent < k + kCachedPowersDecimalDistance.
|
||||||
// The given decimal_exponent must satisfy
|
// The given decimal_exponent must satisfy
|
||||||
// kMinDecimalExponent <= requested_exponent, and
|
// kMinDecimalExponent <= requested_exponent, and
|
||||||
// requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
|
// requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
|
||||||
static void GetCachedPowerForDecimalExponent(int requested_exponent,
|
void GetCachedPowerForDecimalExponent(int requested_exponent,
|
||||||
DiyFp* power,
|
DiyFp* power,
|
||||||
int* found_exponent);
|
int* found_exponent);
|
||||||
};
|
|
||||||
|
} // namespace PowersOfTenCache
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
|
||||||
|
@@ -1,57 +0,0 @@
|
|||||||
// Copyright 2010 the V8 project authors. All rights reserved.
|
|
||||||
// Redistribution and use in source and binary forms, with or without
|
|
||||||
// modification, are permitted provided that the following conditions are
|
|
||||||
// met:
|
|
||||||
//
|
|
||||||
// * Redistributions of source code must retain the above copyright
|
|
||||||
// notice, this list of conditions and the following disclaimer.
|
|
||||||
// * Redistributions in binary form must reproduce the above
|
|
||||||
// copyright notice, this list of conditions and the following
|
|
||||||
// disclaimer in the documentation and/or other materials provided
|
|
||||||
// with the distribution.
|
|
||||||
// * Neither the name of Google Inc. nor the names of its
|
|
||||||
// contributors may be used to endorse or promote products derived
|
|
||||||
// from this software without specific prior written permission.
|
|
||||||
//
|
|
||||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
|
||||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
|
||||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
|
||||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
|
||||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
|
||||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
|
||||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
||||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
|
|
||||||
|
|
||||||
#include "diy-fp.h"
|
|
||||||
#include "utils.h"
|
|
||||||
|
|
||||||
namespace double_conversion {
|
|
||||||
|
|
||||||
void DiyFp::Multiply(const DiyFp& other) {
|
|
||||||
// Simply "emulates" a 128 bit multiplication.
|
|
||||||
// However: the resulting number only contains 64 bits. The least
|
|
||||||
// significant 64 bits are only used for rounding the most significant 64
|
|
||||||
// bits.
|
|
||||||
const uint64_t kM32 = 0xFFFFFFFFU;
|
|
||||||
uint64_t a = f_ >> 32;
|
|
||||||
uint64_t b = f_ & kM32;
|
|
||||||
uint64_t c = other.f_ >> 32;
|
|
||||||
uint64_t d = other.f_ & kM32;
|
|
||||||
uint64_t ac = a * c;
|
|
||||||
uint64_t bc = b * c;
|
|
||||||
uint64_t ad = a * d;
|
|
||||||
uint64_t bd = b * d;
|
|
||||||
uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
|
|
||||||
// By adding 1U << 31 to tmp we round the final result.
|
|
||||||
// Halfway cases will be round up.
|
|
||||||
tmp += 1U << 31;
|
|
||||||
uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
|
|
||||||
e_ += other.e_ + 64;
|
|
||||||
f_ = result_f;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace double_conversion
|
|
@@ -36,36 +36,55 @@ namespace double_conversion {
|
|||||||
// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
|
// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
|
||||||
// have the most significant bit of the significand set.
|
// have the most significant bit of the significand set.
|
||||||
// Multiplication and Subtraction do not normalize their results.
|
// Multiplication and Subtraction do not normalize their results.
|
||||||
// DiyFp are not designed to contain special doubles (NaN and Infinity).
|
// DiyFp store only non-negative numbers and are not designed to contain special
|
||||||
|
// doubles (NaN and Infinity).
|
||||||
class DiyFp {
|
class DiyFp {
|
||||||
public:
|
public:
|
||||||
static const int kSignificandSize = 64;
|
static const int kSignificandSize = 64;
|
||||||
|
|
||||||
DiyFp() : f_(0), e_(0) {}
|
DiyFp() : f_(0), e_(0) {}
|
||||||
DiyFp(uint64_t significand, int exponent) : f_(significand), e_(exponent) {}
|
DiyFp(const uint64_t significand, const int32_t exponent) : f_(significand), e_(exponent) {}
|
||||||
|
|
||||||
// this = this - other.
|
// this -= other.
|
||||||
// The exponents of both numbers must be the same and the significand of this
|
// The exponents of both numbers must be the same and the significand of this
|
||||||
// must be bigger than the significand of other.
|
// must be greater or equal than the significand of other.
|
||||||
// The result will not be normalized.
|
// The result will not be normalized.
|
||||||
void Subtract(const DiyFp& other) {
|
void Subtract(const DiyFp& other) {
|
||||||
ASSERT(e_ == other.e_);
|
DOUBLE_CONVERSION_ASSERT(e_ == other.e_);
|
||||||
ASSERT(f_ >= other.f_);
|
DOUBLE_CONVERSION_ASSERT(f_ >= other.f_);
|
||||||
f_ -= other.f_;
|
f_ -= other.f_;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns a - b.
|
// Returns a - b.
|
||||||
// The exponents of both numbers must be the same and this must be bigger
|
// The exponents of both numbers must be the same and a must be greater
|
||||||
// than other. The result will not be normalized.
|
// or equal than b. The result will not be normalized.
|
||||||
static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
|
static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
|
||||||
DiyFp result = a;
|
DiyFp result = a;
|
||||||
result.Subtract(b);
|
result.Subtract(b);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// this *= other.
|
||||||
// this = this * other.
|
void Multiply(const DiyFp& other) {
|
||||||
void Multiply(const DiyFp& other);
|
// Simply "emulates" a 128 bit multiplication.
|
||||||
|
// However: the resulting number only contains 64 bits. The least
|
||||||
|
// significant 64 bits are only used for rounding the most significant 64
|
||||||
|
// bits.
|
||||||
|
const uint64_t kM32 = 0xFFFFFFFFU;
|
||||||
|
const uint64_t a = f_ >> 32;
|
||||||
|
const uint64_t b = f_ & kM32;
|
||||||
|
const uint64_t c = other.f_ >> 32;
|
||||||
|
const uint64_t d = other.f_ & kM32;
|
||||||
|
const uint64_t ac = a * c;
|
||||||
|
const uint64_t bc = b * c;
|
||||||
|
const uint64_t ad = a * d;
|
||||||
|
const uint64_t bd = b * d;
|
||||||
|
// By adding 1U << 31 to tmp we round the final result.
|
||||||
|
// Halfway cases will be rounded up.
|
||||||
|
const uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32) + (1U << 31);
|
||||||
|
e_ += other.e_ + 64;
|
||||||
|
f_ = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
|
||||||
|
}
|
||||||
|
|
||||||
// returns a * b;
|
// returns a * b;
|
||||||
static DiyFp Times(const DiyFp& a, const DiyFp& b) {
|
static DiyFp Times(const DiyFp& a, const DiyFp& b) {
|
||||||
@@ -75,13 +94,13 @@ class DiyFp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void Normalize() {
|
void Normalize() {
|
||||||
ASSERT(f_ != 0);
|
DOUBLE_CONVERSION_ASSERT(f_ != 0);
|
||||||
uint64_t significand = f_;
|
uint64_t significand = f_;
|
||||||
int exponent = e_;
|
int32_t exponent = e_;
|
||||||
|
|
||||||
// This method is mainly called for normalizing boundaries. In general
|
// This method is mainly called for normalizing boundaries. In general,
|
||||||
// boundaries need to be shifted by 10 bits. We thus optimize for this case.
|
// boundaries need to be shifted by 10 bits, and we optimize for this case.
|
||||||
const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
|
const uint64_t k10MSBits = DOUBLE_CONVERSION_UINT64_2PART_C(0xFFC00000, 00000000);
|
||||||
while ((significand & k10MSBits) == 0) {
|
while ((significand & k10MSBits) == 0) {
|
||||||
significand <<= 10;
|
significand <<= 10;
|
||||||
exponent -= 10;
|
exponent -= 10;
|
||||||
@@ -101,16 +120,16 @@ class DiyFp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uint64_t f() const { return f_; }
|
uint64_t f() const { return f_; }
|
||||||
int e() const { return e_; }
|
int32_t e() const { return e_; }
|
||||||
|
|
||||||
void set_f(uint64_t new_value) { f_ = new_value; }
|
void set_f(uint64_t new_value) { f_ = new_value; }
|
||||||
void set_e(int new_value) { e_ = new_value; }
|
void set_e(int32_t new_value) { e_ = new_value; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
|
static const uint64_t kUint64MSB = DOUBLE_CONVERSION_UINT64_2PART_C(0x80000000, 00000000);
|
||||||
|
|
||||||
uint64_t f_;
|
uint64_t f_;
|
||||||
int e_;
|
int32_t e_;
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
@@ -28,549 +28,7 @@
|
|||||||
#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
||||||
#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
||||||
|
|
||||||
#include "utils.h"
|
#include "string-to-double.h"
|
||||||
|
#include "double-to-string.h"
|
||||||
namespace double_conversion {
|
|
||||||
|
|
||||||
class DoubleToStringConverter {
|
|
||||||
public:
|
|
||||||
// When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
|
|
||||||
// or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
|
|
||||||
// function returns false.
|
|
||||||
static const int kMaxFixedDigitsBeforePoint = 60;
|
|
||||||
static const int kMaxFixedDigitsAfterPoint = 60;
|
|
||||||
|
|
||||||
// When calling ToExponential with a requested_digits
|
|
||||||
// parameter > kMaxExponentialDigits then the function returns false.
|
|
||||||
static const int kMaxExponentialDigits = 120;
|
|
||||||
|
|
||||||
// When calling ToPrecision with a requested_digits
|
|
||||||
// parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
|
|
||||||
// then the function returns false.
|
|
||||||
static const int kMinPrecisionDigits = 1;
|
|
||||||
static const int kMaxPrecisionDigits = 120;
|
|
||||||
|
|
||||||
enum Flags {
|
|
||||||
NO_FLAGS = 0,
|
|
||||||
EMIT_POSITIVE_EXPONENT_SIGN = 1,
|
|
||||||
EMIT_TRAILING_DECIMAL_POINT = 2,
|
|
||||||
EMIT_TRAILING_ZERO_AFTER_POINT = 4,
|
|
||||||
UNIQUE_ZERO = 8
|
|
||||||
};
|
|
||||||
|
|
||||||
// Flags should be a bit-or combination of the possible Flags-enum.
|
|
||||||
// - NO_FLAGS: no special flags.
|
|
||||||
// - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
|
|
||||||
// form, emits a '+' for positive exponents. Example: 1.2e+2.
|
|
||||||
// - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
|
|
||||||
// converted into decimal format then a trailing decimal point is appended.
|
|
||||||
// Example: 2345.0 is converted to "2345.".
|
|
||||||
// - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
|
|
||||||
// emits a trailing '0'-character. This flag requires the
|
|
||||||
// EXMIT_TRAILING_DECIMAL_POINT flag.
|
|
||||||
// Example: 2345.0 is converted to "2345.0".
|
|
||||||
// - UNIQUE_ZERO: "-0.0" is converted to "0.0".
|
|
||||||
//
|
|
||||||
// Infinity symbol and nan_symbol provide the string representation for these
|
|
||||||
// special values. If the string is NULL and the special value is encountered
|
|
||||||
// then the conversion functions return false.
|
|
||||||
//
|
|
||||||
// The exponent_character is used in exponential representations. It is
|
|
||||||
// usually 'e' or 'E'.
|
|
||||||
//
|
|
||||||
// When converting to the shortest representation the converter will
|
|
||||||
// represent input numbers in decimal format if they are in the interval
|
|
||||||
// [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
|
|
||||||
// (lower boundary included, greater boundary excluded).
|
|
||||||
// Example: with decimal_in_shortest_low = -6 and
|
|
||||||
// decimal_in_shortest_high = 21:
|
|
||||||
// ToShortest(0.000001) -> "0.000001"
|
|
||||||
// ToShortest(0.0000001) -> "1e-7"
|
|
||||||
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
|
||||||
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
|
||||||
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
|
||||||
//
|
|
||||||
// When converting to precision mode the converter may add
|
|
||||||
// max_leading_padding_zeroes before returning the number in exponential
|
|
||||||
// format.
|
|
||||||
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
|
||||||
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
|
||||||
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
|
||||||
// Similarily the converter may add up to
|
|
||||||
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
|
||||||
// returning an exponential representation. A zero added by the
|
|
||||||
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
|
||||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
|
||||||
// ToPrecision(230.0, 2) -> "230"
|
|
||||||
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
|
||||||
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
|
||||||
DoubleToStringConverter(int flags,
|
|
||||||
const char* infinity_symbol,
|
|
||||||
const char* nan_symbol,
|
|
||||||
char exponent_character,
|
|
||||||
int decimal_in_shortest_low,
|
|
||||||
int decimal_in_shortest_high,
|
|
||||||
int max_leading_padding_zeroes_in_precision_mode,
|
|
||||||
int max_trailing_padding_zeroes_in_precision_mode)
|
|
||||||
: flags_(flags),
|
|
||||||
infinity_symbol_(infinity_symbol),
|
|
||||||
nan_symbol_(nan_symbol),
|
|
||||||
exponent_character_(exponent_character),
|
|
||||||
decimal_in_shortest_low_(decimal_in_shortest_low),
|
|
||||||
decimal_in_shortest_high_(decimal_in_shortest_high),
|
|
||||||
max_leading_padding_zeroes_in_precision_mode_(
|
|
||||||
max_leading_padding_zeroes_in_precision_mode),
|
|
||||||
max_trailing_padding_zeroes_in_precision_mode_(
|
|
||||||
max_trailing_padding_zeroes_in_precision_mode) {
|
|
||||||
// When 'trailing zero after the point' is set, then 'trailing point'
|
|
||||||
// must be set too.
|
|
||||||
ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
|
|
||||||
!((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns a converter following the EcmaScript specification.
|
|
||||||
static const DoubleToStringConverter& EcmaScriptConverter();
|
|
||||||
|
|
||||||
// Computes the shortest string of digits that correctly represent the input
|
|
||||||
// number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
|
|
||||||
// (see constructor) it then either returns a decimal representation, or an
|
|
||||||
// exponential representation.
|
|
||||||
// Example with decimal_in_shortest_low = -6,
|
|
||||||
// decimal_in_shortest_high = 21,
|
|
||||||
// EMIT_POSITIVE_EXPONENT_SIGN activated, and
|
|
||||||
// EMIT_TRAILING_DECIMAL_POINT deactived:
|
|
||||||
// ToShortest(0.000001) -> "0.000001"
|
|
||||||
// ToShortest(0.0000001) -> "1e-7"
|
|
||||||
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
|
||||||
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
|
||||||
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
|
||||||
//
|
|
||||||
// Note: the conversion may round the output if the returned string
|
|
||||||
// is accurate enough to uniquely identify the input-number.
|
|
||||||
// For example the most precise representation of the double 9e59 equals
|
|
||||||
// "899999999999999918767229449717619953810131273674690656206848", but
|
|
||||||
// the converter will return the shorter (but still correct) "9e59".
|
|
||||||
//
|
|
||||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
|
||||||
// except when the input value is special and no infinity_symbol or
|
|
||||||
// nan_symbol has been given to the constructor.
|
|
||||||
bool ToShortest(double value, StringBuilder* result_builder) const {
|
|
||||||
return ToShortestIeeeNumber(value, result_builder, SHORTEST);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Same as ToShortest, but for single-precision floats.
|
|
||||||
bool ToShortestSingle(float value, StringBuilder* result_builder) const {
|
|
||||||
return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Computes a decimal representation with a fixed number of digits after the
|
|
||||||
// decimal point. The last emitted digit is rounded.
|
|
||||||
//
|
|
||||||
// Examples:
|
|
||||||
// ToFixed(3.12, 1) -> "3.1"
|
|
||||||
// ToFixed(3.1415, 3) -> "3.142"
|
|
||||||
// ToFixed(1234.56789, 4) -> "1234.5679"
|
|
||||||
// ToFixed(1.23, 5) -> "1.23000"
|
|
||||||
// ToFixed(0.1, 4) -> "0.1000"
|
|
||||||
// ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
|
|
||||||
// ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
|
|
||||||
// ToFixed(0.1, 17) -> "0.10000000000000001"
|
|
||||||
//
|
|
||||||
// If requested_digits equals 0, then the tail of the result depends on
|
|
||||||
// the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
|
|
||||||
// Examples, for requested_digits == 0,
|
|
||||||
// let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
|
|
||||||
// - false and false: then 123.45 -> 123
|
|
||||||
// 0.678 -> 1
|
|
||||||
// - true and false: then 123.45 -> 123.
|
|
||||||
// 0.678 -> 1.
|
|
||||||
// - true and true: then 123.45 -> 123.0
|
|
||||||
// 0.678 -> 1.0
|
|
||||||
//
|
|
||||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
|
||||||
// except for the following cases:
|
|
||||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
|
||||||
// been provided to the constructor,
|
|
||||||
// - 'value' > 10^kMaxFixedDigitsBeforePoint, or
|
|
||||||
// - 'requested_digits' > kMaxFixedDigitsAfterPoint.
|
|
||||||
// The last two conditions imply that the result will never contain more than
|
|
||||||
// 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
|
|
||||||
// (one additional character for the sign, and one for the decimal point).
|
|
||||||
bool ToFixed(double value,
|
|
||||||
int requested_digits,
|
|
||||||
StringBuilder* result_builder) const;
|
|
||||||
|
|
||||||
// Computes a representation in exponential format with requested_digits
|
|
||||||
// after the decimal point. The last emitted digit is rounded.
|
|
||||||
// If requested_digits equals -1, then the shortest exponential representation
|
|
||||||
// is computed.
|
|
||||||
//
|
|
||||||
// Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
|
|
||||||
// exponent_character set to 'e'.
|
|
||||||
// ToExponential(3.12, 1) -> "3.1e0"
|
|
||||||
// ToExponential(5.0, 3) -> "5.000e0"
|
|
||||||
// ToExponential(0.001, 2) -> "1.00e-3"
|
|
||||||
// ToExponential(3.1415, -1) -> "3.1415e0"
|
|
||||||
// ToExponential(3.1415, 4) -> "3.1415e0"
|
|
||||||
// ToExponential(3.1415, 3) -> "3.142e0"
|
|
||||||
// ToExponential(123456789000000, 3) -> "1.235e14"
|
|
||||||
// ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
|
|
||||||
// ToExponential(1000000000000000019884624838656.0, 32) ->
|
|
||||||
// "1.00000000000000001988462483865600e30"
|
|
||||||
// ToExponential(1234, 0) -> "1e3"
|
|
||||||
//
|
|
||||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
|
||||||
// except for the following cases:
|
|
||||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
|
||||||
// been provided to the constructor,
|
|
||||||
// - 'requested_digits' > kMaxExponentialDigits.
|
|
||||||
// The last condition implies that the result will never contain more than
|
|
||||||
// kMaxExponentialDigits + 8 characters (the sign, the digit before the
|
|
||||||
// decimal point, the decimal point, the exponent character, the
|
|
||||||
// exponent's sign, and at most 3 exponent digits).
|
|
||||||
bool ToExponential(double value,
|
|
||||||
int requested_digits,
|
|
||||||
StringBuilder* result_builder) const;
|
|
||||||
|
|
||||||
// Computes 'precision' leading digits of the given 'value' and returns them
|
|
||||||
// either in exponential or decimal format, depending on
|
|
||||||
// max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
|
|
||||||
// constructor).
|
|
||||||
// The last computed digit is rounded.
|
|
||||||
//
|
|
||||||
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
|
||||||
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
|
||||||
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
|
||||||
// Similarily the converter may add up to
|
|
||||||
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
|
||||||
// returning an exponential representation. A zero added by the
|
|
||||||
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
|
||||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
|
||||||
// ToPrecision(230.0, 2) -> "230"
|
|
||||||
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
|
||||||
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
|
||||||
// Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
|
|
||||||
// EMIT_TRAILING_ZERO_AFTER_POINT:
|
|
||||||
// ToPrecision(123450.0, 6) -> "123450"
|
|
||||||
// ToPrecision(123450.0, 5) -> "123450"
|
|
||||||
// ToPrecision(123450.0, 4) -> "123500"
|
|
||||||
// ToPrecision(123450.0, 3) -> "123000"
|
|
||||||
// ToPrecision(123450.0, 2) -> "1.2e5"
|
|
||||||
//
|
|
||||||
// Returns true if the conversion succeeds. The conversion always succeeds
|
|
||||||
// except for the following cases:
|
|
||||||
// - the input value is special and no infinity_symbol or nan_symbol has
|
|
||||||
// been provided to the constructor,
|
|
||||||
// - precision < kMinPericisionDigits
|
|
||||||
// - precision > kMaxPrecisionDigits
|
|
||||||
// The last condition implies that the result will never contain more than
|
|
||||||
// kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
|
|
||||||
// exponent character, the exponent's sign, and at most 3 exponent digits).
|
|
||||||
bool ToPrecision(double value,
|
|
||||||
int precision,
|
|
||||||
StringBuilder* result_builder) const;
|
|
||||||
|
|
||||||
enum DtoaMode {
|
|
||||||
// Produce the shortest correct representation.
|
|
||||||
// For example the output of 0.299999999999999988897 is (the less accurate
|
|
||||||
// but correct) 0.3.
|
|
||||||
SHORTEST,
|
|
||||||
// Same as SHORTEST, but for single-precision floats.
|
|
||||||
SHORTEST_SINGLE,
|
|
||||||
// Produce a fixed number of digits after the decimal point.
|
|
||||||
// For instance fixed(0.1, 4) becomes 0.1000
|
|
||||||
// If the input number is big, the output will be big.
|
|
||||||
FIXED,
|
|
||||||
// Fixed number of digits (independent of the decimal point).
|
|
||||||
PRECISION
|
|
||||||
};
|
|
||||||
|
|
||||||
// The maximal number of digits that are needed to emit a double in base 10.
|
|
||||||
// A higher precision can be achieved by using more digits, but the shortest
|
|
||||||
// accurate representation of any double will never use more digits than
|
|
||||||
// kBase10MaximalLength.
|
|
||||||
// Note that DoubleToAscii null-terminates its input. So the given buffer
|
|
||||||
// should be at least kBase10MaximalLength + 1 characters long.
|
|
||||||
static const int kBase10MaximalLength = 17;
|
|
||||||
|
|
||||||
// Converts the given double 'v' to digit characters. 'v' must not be NaN,
|
|
||||||
// +Infinity, or -Infinity. In SHORTEST_SINGLE-mode this restriction also
|
|
||||||
// applies to 'v' after it has been casted to a single-precision float. That
|
|
||||||
// is, in this mode static_cast<float>(v) must not be NaN, +Infinity or
|
|
||||||
// -Infinity.
|
|
||||||
//
|
|
||||||
// The result should be interpreted as buffer * 10^(point-length).
|
|
||||||
//
|
|
||||||
// The digits are written to the buffer in the platform's charset, which is
|
|
||||||
// often UTF-8 (with ASCII-range digits) but may be another charset, such
|
|
||||||
// as EBCDIC.
|
|
||||||
//
|
|
||||||
// The output depends on the given mode:
|
|
||||||
// - SHORTEST: produce the least amount of digits for which the internal
|
|
||||||
// identity requirement is still satisfied. If the digits are printed
|
|
||||||
// (together with the correct exponent) then reading this number will give
|
|
||||||
// 'v' again. The buffer will choose the representation that is closest to
|
|
||||||
// 'v'. If there are two at the same distance, than the one farther away
|
|
||||||
// from 0 is chosen (halfway cases - ending with 5 - are rounded up).
|
|
||||||
// In this mode the 'requested_digits' parameter is ignored.
|
|
||||||
// - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
|
|
||||||
// - FIXED: produces digits necessary to print a given number with
|
|
||||||
// 'requested_digits' digits after the decimal point. The produced digits
|
|
||||||
// might be too short in which case the caller has to fill the remainder
|
|
||||||
// with '0's.
|
|
||||||
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
|
||||||
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
|
||||||
// toFixed(0.15, 2) thus returns buffer="2", point=0.
|
|
||||||
// The returned buffer may contain digits that would be truncated from the
|
|
||||||
// shortest representation of the input.
|
|
||||||
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
|
||||||
// Even though the length of produced digits usually equals
|
|
||||||
// 'requested_digits', the function is allowed to return fewer digits, in
|
|
||||||
// which case the caller has to fill the missing digits with '0's.
|
|
||||||
// Halfway cases are again rounded away from 0.
|
|
||||||
// DoubleToAscii expects the given buffer to be big enough to hold all
|
|
||||||
// digits and a terminating null-character. In SHORTEST-mode it expects a
|
|
||||||
// buffer of at least kBase10MaximalLength + 1. In all other modes the
|
|
||||||
// requested_digits parameter and the padding-zeroes limit the size of the
|
|
||||||
// output. Don't forget the decimal point, the exponent character and the
|
|
||||||
// terminating null-character when computing the maximal output size.
|
|
||||||
// The given length is only used in debug mode to ensure the buffer is big
|
|
||||||
// enough.
|
|
||||||
static void DoubleToAscii(double v,
|
|
||||||
DtoaMode mode,
|
|
||||||
int requested_digits,
|
|
||||||
char* buffer,
|
|
||||||
int buffer_length,
|
|
||||||
bool* sign,
|
|
||||||
int* length,
|
|
||||||
int* point);
|
|
||||||
|
|
||||||
private:
|
|
||||||
// Implementation for ToShortest and ToShortestSingle.
|
|
||||||
bool ToShortestIeeeNumber(double value,
|
|
||||||
StringBuilder* result_builder,
|
|
||||||
DtoaMode mode) const;
|
|
||||||
|
|
||||||
// If the value is a special value (NaN or Infinity) constructs the
|
|
||||||
// corresponding string using the configured infinity/nan-symbol.
|
|
||||||
// If either of them is NULL or the value is not special then the
|
|
||||||
// function returns false.
|
|
||||||
bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
|
|
||||||
// Constructs an exponential representation (i.e. 1.234e56).
|
|
||||||
// The given exponent assumes a decimal point after the first decimal digit.
|
|
||||||
void CreateExponentialRepresentation(const char* decimal_digits,
|
|
||||||
int length,
|
|
||||||
int exponent,
|
|
||||||
StringBuilder* result_builder) const;
|
|
||||||
// Creates a decimal representation (i.e 1234.5678).
|
|
||||||
void CreateDecimalRepresentation(const char* decimal_digits,
|
|
||||||
int length,
|
|
||||||
int decimal_point,
|
|
||||||
int digits_after_point,
|
|
||||||
StringBuilder* result_builder) const;
|
|
||||||
|
|
||||||
const int flags_;
|
|
||||||
const char* const infinity_symbol_;
|
|
||||||
const char* const nan_symbol_;
|
|
||||||
const char exponent_character_;
|
|
||||||
const int decimal_in_shortest_low_;
|
|
||||||
const int decimal_in_shortest_high_;
|
|
||||||
const int max_leading_padding_zeroes_in_precision_mode_;
|
|
||||||
const int max_trailing_padding_zeroes_in_precision_mode_;
|
|
||||||
|
|
||||||
DC_DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
class StringToDoubleConverter {
|
|
||||||
public:
|
|
||||||
// Enumeration for allowing octals and ignoring junk when converting
|
|
||||||
// strings to numbers.
|
|
||||||
enum Flags {
|
|
||||||
NO_FLAGS = 0,
|
|
||||||
ALLOW_HEX = 1,
|
|
||||||
ALLOW_OCTALS = 2,
|
|
||||||
ALLOW_TRAILING_JUNK = 4,
|
|
||||||
ALLOW_LEADING_SPACES = 8,
|
|
||||||
ALLOW_TRAILING_SPACES = 16,
|
|
||||||
ALLOW_SPACES_AFTER_SIGN = 32,
|
|
||||||
ALLOW_CASE_INSENSIBILITY = 64,
|
|
||||||
ALLOW_HEX_FLOATS = 128,
|
|
||||||
};
|
|
||||||
|
|
||||||
static const uc16 kNoSeparator = '\0';
|
|
||||||
|
|
||||||
// Flags should be a bit-or combination of the possible Flags-enum.
|
|
||||||
// - NO_FLAGS: no special flags.
|
|
||||||
// - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
|
|
||||||
// Ex: StringToDouble("0x1234") -> 4660.0
|
|
||||||
// In StringToDouble("0x1234.56") the characters ".56" are trailing
|
|
||||||
// junk. The result of the call is hence dependent on
|
|
||||||
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
|
||||||
// With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
|
|
||||||
// the string will not be parsed as "0" followed by junk.
|
|
||||||
//
|
|
||||||
// - ALLOW_OCTALS: recognizes the prefix "0" for octals:
|
|
||||||
// If a sequence of octal digits starts with '0', then the number is
|
|
||||||
// read as octal integer. Octal numbers may only be integers.
|
|
||||||
// Ex: StringToDouble("01234") -> 668.0
|
|
||||||
// StringToDouble("012349") -> 12349.0 // Not a sequence of octal
|
|
||||||
// // digits.
|
|
||||||
// In StringToDouble("01234.56") the characters ".56" are trailing
|
|
||||||
// junk. The result of the call is hence dependent on
|
|
||||||
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
|
||||||
// In StringToDouble("01234e56") the characters "e56" are trailing
|
|
||||||
// junk, too.
|
|
||||||
// - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
|
|
||||||
// a double literal.
|
|
||||||
// - ALLOW_LEADING_SPACES: skip over leading whitespace, including spaces,
|
|
||||||
// new-lines, and tabs.
|
|
||||||
// - ALLOW_TRAILING_SPACES: ignore trailing whitespace.
|
|
||||||
// - ALLOW_SPACES_AFTER_SIGN: ignore whitespace after the sign.
|
|
||||||
// Ex: StringToDouble("- 123.2") -> -123.2.
|
|
||||||
// StringToDouble("+ 123.2") -> 123.2
|
|
||||||
// - ALLOW_CASE_INSENSIBILITY: ignore case of characters for special values:
|
|
||||||
// infinity and nan.
|
|
||||||
// - ALLOW_HEX_FLOATS: allows hexadecimal float literals.
|
|
||||||
// This *must* start with "0x" and separate the exponent with "p".
|
|
||||||
// Examples: 0x1.2p3 == 9.0
|
|
||||||
// 0x10.1p0 == 16.0625
|
|
||||||
// ALLOW_HEX and ALLOW_HEX_FLOATS are indendent.
|
|
||||||
//
|
|
||||||
// empty_string_value is returned when an empty string is given as input.
|
|
||||||
// If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
|
|
||||||
// containing only spaces is converted to the 'empty_string_value', too.
|
|
||||||
//
|
|
||||||
// junk_string_value is returned when
|
|
||||||
// a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
|
|
||||||
// part of a double-literal) is found.
|
|
||||||
// b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
|
|
||||||
// double literal.
|
|
||||||
//
|
|
||||||
// infinity_symbol and nan_symbol are strings that are used to detect
|
|
||||||
// inputs that represent infinity and NaN. They can be null, in which case
|
|
||||||
// they are ignored.
|
|
||||||
// The conversion routine first reads any possible signs. Then it compares the
|
|
||||||
// following character of the input-string with the first character of
|
|
||||||
// the infinity, and nan-symbol. If either matches, the function assumes, that
|
|
||||||
// a match has been found, and expects the following input characters to match
|
|
||||||
// the remaining characters of the special-value symbol.
|
|
||||||
// This means that the following restrictions apply to special-value symbols:
|
|
||||||
// - they must not start with signs ('+', or '-'),
|
|
||||||
// - they must not have the same first character.
|
|
||||||
// - they must not start with digits.
|
|
||||||
//
|
|
||||||
// If the separator character is not kNoSeparator, then that specific
|
|
||||||
// character is ignored when in between two valid digits of the significant.
|
|
||||||
// It is not allowed to appear in the exponent.
|
|
||||||
// It is not allowed to lead or trail the number.
|
|
||||||
// It is not allowed to appear twice next to each other.
|
|
||||||
//
|
|
||||||
// Examples:
|
|
||||||
// flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
|
|
||||||
// empty_string_value = 0.0,
|
|
||||||
// junk_string_value = NaN,
|
|
||||||
// infinity_symbol = "infinity",
|
|
||||||
// nan_symbol = "nan":
|
|
||||||
// StringToDouble("0x1234") -> 4660.0.
|
|
||||||
// StringToDouble("0x1234K") -> 4660.0.
|
|
||||||
// StringToDouble("") -> 0.0 // empty_string_value.
|
|
||||||
// StringToDouble(" ") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble(" 1") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("0x") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("-123.45") -> -123.45.
|
|
||||||
// StringToDouble("--123.45") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("123e45") -> 123e45.
|
|
||||||
// StringToDouble("123E45") -> 123e45.
|
|
||||||
// StringToDouble("123e+45") -> 123e45.
|
|
||||||
// StringToDouble("123E-45") -> 123e-45.
|
|
||||||
// StringToDouble("123e") -> 123.0 // trailing junk ignored.
|
|
||||||
// StringToDouble("123e-") -> 123.0 // trailing junk ignored.
|
|
||||||
// StringToDouble("+NaN") -> NaN // NaN string literal.
|
|
||||||
// StringToDouble("-infinity") -> -inf. // infinity literal.
|
|
||||||
// StringToDouble("Infinity") -> NaN // junk_string_value.
|
|
||||||
//
|
|
||||||
// flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
|
|
||||||
// empty_string_value = 0.0,
|
|
||||||
// junk_string_value = NaN,
|
|
||||||
// infinity_symbol = NULL,
|
|
||||||
// nan_symbol = NULL:
|
|
||||||
// StringToDouble("0x1234") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("01234") -> 668.0.
|
|
||||||
// StringToDouble("") -> 0.0 // empty_string_value.
|
|
||||||
// StringToDouble(" ") -> 0.0 // empty_string_value.
|
|
||||||
// StringToDouble(" 1") -> 1.0
|
|
||||||
// StringToDouble("0x") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("0123e45") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("01239E45") -> 1239e45.
|
|
||||||
// StringToDouble("-infinity") -> NaN // junk_string_value.
|
|
||||||
// StringToDouble("NaN") -> NaN // junk_string_value.
|
|
||||||
//
|
|
||||||
// flags = NO_FLAGS,
|
|
||||||
// separator = ' ':
|
|
||||||
// StringToDouble("1 2 3 4") -> 1234.0
|
|
||||||
// StringToDouble("1 2") -> NaN // junk_string_value
|
|
||||||
// StringToDouble("1 000 000.0") -> 1000000.0
|
|
||||||
// StringToDouble("1.000 000") -> 1.0
|
|
||||||
// StringToDouble("1.0e1 000") -> NaN // junk_string_value
|
|
||||||
StringToDoubleConverter(int flags,
|
|
||||||
double empty_string_value,
|
|
||||||
double junk_string_value,
|
|
||||||
const char* infinity_symbol,
|
|
||||||
const char* nan_symbol,
|
|
||||||
uc16 separator = kNoSeparator)
|
|
||||||
: flags_(flags),
|
|
||||||
empty_string_value_(empty_string_value),
|
|
||||||
junk_string_value_(junk_string_value),
|
|
||||||
infinity_symbol_(infinity_symbol),
|
|
||||||
nan_symbol_(nan_symbol),
|
|
||||||
separator_(separator) {
|
|
||||||
}
|
|
||||||
|
|
||||||
// Performs the conversion.
|
|
||||||
// The output parameter 'processed_characters_count' is set to the number
|
|
||||||
// of characters that have been processed to read the number.
|
|
||||||
// Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
|
|
||||||
// in the 'processed_characters_count'. Trailing junk is never included.
|
|
||||||
double StringToDouble(const char* buffer,
|
|
||||||
int length,
|
|
||||||
int* processed_characters_count) const;
|
|
||||||
|
|
||||||
// Same as StringToDouble above but for 16 bit characters.
|
|
||||||
double StringToDouble(const uc16* buffer,
|
|
||||||
int length,
|
|
||||||
int* processed_characters_count) const;
|
|
||||||
|
|
||||||
// Same as StringToDouble but reads a float.
|
|
||||||
// Note that this is not equivalent to static_cast<float>(StringToDouble(...))
|
|
||||||
// due to potential double-rounding.
|
|
||||||
float StringToFloat(const char* buffer,
|
|
||||||
int length,
|
|
||||||
int* processed_characters_count) const;
|
|
||||||
|
|
||||||
// Same as StringToFloat above but for 16 bit characters.
|
|
||||||
float StringToFloat(const uc16* buffer,
|
|
||||||
int length,
|
|
||||||
int* processed_characters_count) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
const int flags_;
|
|
||||||
const double empty_string_value_;
|
|
||||||
const double junk_string_value_;
|
|
||||||
const char* const infinity_symbol_;
|
|
||||||
const char* const nan_symbol_;
|
|
||||||
const uc16 separator_;
|
|
||||||
|
|
||||||
template <class Iterator>
|
|
||||||
double StringToIeee(Iterator start_pointer,
|
|
||||||
int length,
|
|
||||||
bool read_as_double,
|
|
||||||
int* processed_characters_count) const;
|
|
||||||
|
|
||||||
DC_DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace double_conversion
|
|
||||||
|
|
||||||
#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
||||||
|
440
Foundation/src/double-to-string.cc
Normal file
440
Foundation/src/double-to-string.cc
Normal file
@@ -0,0 +1,440 @@
|
|||||||
|
// Copyright 2010 the V8 project authors. All rights reserved.
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// * Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
// * Redistributions in binary form must reproduce the above
|
||||||
|
// copyright notice, this list of conditions and the following
|
||||||
|
// disclaimer in the documentation and/or other materials provided
|
||||||
|
// with the distribution.
|
||||||
|
// * Neither the name of Google Inc. nor the names of its
|
||||||
|
// contributors may be used to endorse or promote products derived
|
||||||
|
// from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <climits>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
#include "double-to-string.h"
|
||||||
|
|
||||||
|
#include "bignum-dtoa.h"
|
||||||
|
#include "fast-dtoa.h"
|
||||||
|
#include "fixed-dtoa.h"
|
||||||
|
#include "ieee.h"
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
|
namespace double_conversion {
|
||||||
|
|
||||||
|
const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
|
||||||
|
int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
|
||||||
|
static DoubleToStringConverter converter(flags,
|
||||||
|
"Infinity",
|
||||||
|
"NaN",
|
||||||
|
'e',
|
||||||
|
-6, 21,
|
||||||
|
6, 0);
|
||||||
|
return converter;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool DoubleToStringConverter::HandleSpecialValues(
|
||||||
|
double value,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
Double double_inspect(value);
|
||||||
|
if (double_inspect.IsInfinite()) {
|
||||||
|
if (infinity_symbol_ == NULL) return false;
|
||||||
|
if (value < 0) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
}
|
||||||
|
result_builder->AddString(infinity_symbol_);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (double_inspect.IsNan()) {
|
||||||
|
if (nan_symbol_ == NULL) return false;
|
||||||
|
result_builder->AddString(nan_symbol_);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void DoubleToStringConverter::CreateExponentialRepresentation(
|
||||||
|
const char* decimal_digits,
|
||||||
|
int length,
|
||||||
|
int exponent,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(length != 0);
|
||||||
|
result_builder->AddCharacter(decimal_digits[0]);
|
||||||
|
if (length != 1) {
|
||||||
|
result_builder->AddCharacter('.');
|
||||||
|
result_builder->AddSubstring(&decimal_digits[1], length-1);
|
||||||
|
}
|
||||||
|
result_builder->AddCharacter(exponent_character_);
|
||||||
|
if (exponent < 0) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
exponent = -exponent;
|
||||||
|
} else {
|
||||||
|
if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
|
||||||
|
result_builder->AddCharacter('+');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
DOUBLE_CONVERSION_ASSERT(exponent < 1e4);
|
||||||
|
// Changing this constant requires updating the comment of DoubleToStringConverter constructor
|
||||||
|
const int kMaxExponentLength = 5;
|
||||||
|
char buffer[kMaxExponentLength + 1];
|
||||||
|
buffer[kMaxExponentLength] = '\0';
|
||||||
|
int first_char_pos = kMaxExponentLength;
|
||||||
|
if (exponent == 0) {
|
||||||
|
buffer[--first_char_pos] = '0';
|
||||||
|
} else {
|
||||||
|
while (exponent > 0) {
|
||||||
|
buffer[--first_char_pos] = '0' + (exponent % 10);
|
||||||
|
exponent /= 10;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Add prefix '0' to make exponent width >= min(min_exponent_with_, kMaxExponentLength)
|
||||||
|
// For example: convert 1e+9 -> 1e+09, if min_exponent_with_ is set to 2
|
||||||
|
while(kMaxExponentLength - first_char_pos < std::min(min_exponent_width_, kMaxExponentLength)) {
|
||||||
|
buffer[--first_char_pos] = '0';
|
||||||
|
}
|
||||||
|
result_builder->AddSubstring(&buffer[first_char_pos],
|
||||||
|
kMaxExponentLength - first_char_pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void DoubleToStringConverter::CreateDecimalRepresentation(
|
||||||
|
const char* decimal_digits,
|
||||||
|
int length,
|
||||||
|
int decimal_point,
|
||||||
|
int digits_after_point,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
// Create a representation that is padded with zeros if needed.
|
||||||
|
if (decimal_point <= 0) {
|
||||||
|
// "0.00000decimal_rep" or "0.000decimal_rep00".
|
||||||
|
result_builder->AddCharacter('0');
|
||||||
|
if (digits_after_point > 0) {
|
||||||
|
result_builder->AddCharacter('.');
|
||||||
|
result_builder->AddPadding('0', -decimal_point);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(length <= digits_after_point - (-decimal_point));
|
||||||
|
result_builder->AddSubstring(decimal_digits, length);
|
||||||
|
int remaining_digits = digits_after_point - (-decimal_point) - length;
|
||||||
|
result_builder->AddPadding('0', remaining_digits);
|
||||||
|
}
|
||||||
|
} else if (decimal_point >= length) {
|
||||||
|
// "decimal_rep0000.00000" or "decimal_rep.0000".
|
||||||
|
result_builder->AddSubstring(decimal_digits, length);
|
||||||
|
result_builder->AddPadding('0', decimal_point - length);
|
||||||
|
if (digits_after_point > 0) {
|
||||||
|
result_builder->AddCharacter('.');
|
||||||
|
result_builder->AddPadding('0', digits_after_point);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// "decima.l_rep000".
|
||||||
|
DOUBLE_CONVERSION_ASSERT(digits_after_point > 0);
|
||||||
|
result_builder->AddSubstring(decimal_digits, decimal_point);
|
||||||
|
result_builder->AddCharacter('.');
|
||||||
|
DOUBLE_CONVERSION_ASSERT(length - decimal_point <= digits_after_point);
|
||||||
|
result_builder->AddSubstring(&decimal_digits[decimal_point],
|
||||||
|
length - decimal_point);
|
||||||
|
int remaining_digits = digits_after_point - (length - decimal_point);
|
||||||
|
result_builder->AddPadding('0', remaining_digits);
|
||||||
|
}
|
||||||
|
if (digits_after_point == 0) {
|
||||||
|
if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
|
||||||
|
result_builder->AddCharacter('.');
|
||||||
|
}
|
||||||
|
if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
|
||||||
|
result_builder->AddCharacter('0');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool DoubleToStringConverter::ToShortestIeeeNumber(
|
||||||
|
double value,
|
||||||
|
StringBuilder* result_builder,
|
||||||
|
DoubleToStringConverter::DtoaMode mode) const {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
|
||||||
|
if (Double(value).IsSpecial()) {
|
||||||
|
return HandleSpecialValues(value, result_builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
int decimal_point;
|
||||||
|
bool sign;
|
||||||
|
const int kDecimalRepCapacity = kBase10MaximalLength + 1;
|
||||||
|
char decimal_rep[kDecimalRepCapacity];
|
||||||
|
int decimal_rep_length;
|
||||||
|
|
||||||
|
DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
|
||||||
|
&sign, &decimal_rep_length, &decimal_point);
|
||||||
|
|
||||||
|
bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
|
||||||
|
if (sign && (value != 0.0 || !unique_zero)) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
int exponent = decimal_point - 1;
|
||||||
|
if ((decimal_in_shortest_low_ <= exponent) &&
|
||||||
|
(exponent < decimal_in_shortest_high_)) {
|
||||||
|
CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
|
||||||
|
decimal_point,
|
||||||
|
(std::max)(0, decimal_rep_length - decimal_point),
|
||||||
|
result_builder);
|
||||||
|
} else {
|
||||||
|
CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
|
||||||
|
result_builder);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool DoubleToStringConverter::ToFixed(double value,
|
||||||
|
int requested_digits,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(kMaxFixedDigitsBeforePoint == 60);
|
||||||
|
const double kFirstNonFixed = 1e60;
|
||||||
|
|
||||||
|
if (Double(value).IsSpecial()) {
|
||||||
|
return HandleSpecialValues(value, result_builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
|
||||||
|
if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
|
||||||
|
|
||||||
|
// Find a sufficiently precise decimal representation of n.
|
||||||
|
int decimal_point;
|
||||||
|
bool sign;
|
||||||
|
// Add space for the '\0' byte.
|
||||||
|
const int kDecimalRepCapacity =
|
||||||
|
kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
|
||||||
|
char decimal_rep[kDecimalRepCapacity];
|
||||||
|
int decimal_rep_length;
|
||||||
|
DoubleToAscii(value, FIXED, requested_digits,
|
||||||
|
decimal_rep, kDecimalRepCapacity,
|
||||||
|
&sign, &decimal_rep_length, &decimal_point);
|
||||||
|
|
||||||
|
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||||
|
if (sign && (value != 0.0 || !unique_zero)) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
||||||
|
requested_digits, result_builder);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool DoubleToStringConverter::ToExponential(
|
||||||
|
double value,
|
||||||
|
int requested_digits,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
if (Double(value).IsSpecial()) {
|
||||||
|
return HandleSpecialValues(value, result_builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requested_digits < -1) return false;
|
||||||
|
if (requested_digits > kMaxExponentialDigits) return false;
|
||||||
|
|
||||||
|
int decimal_point;
|
||||||
|
bool sign;
|
||||||
|
// Add space for digit before the decimal point and the '\0' character.
|
||||||
|
const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
|
||||||
|
DOUBLE_CONVERSION_ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
|
||||||
|
char decimal_rep[kDecimalRepCapacity];
|
||||||
|
#ifndef NDEBUG
|
||||||
|
// Problem: there is an assert in StringBuilder::AddSubstring() that
|
||||||
|
// will pass this buffer to strlen(), and this buffer is not generally
|
||||||
|
// null-terminated.
|
||||||
|
memset(decimal_rep, 0, sizeof(decimal_rep));
|
||||||
|
#endif
|
||||||
|
int decimal_rep_length;
|
||||||
|
|
||||||
|
if (requested_digits == -1) {
|
||||||
|
DoubleToAscii(value, SHORTEST, 0,
|
||||||
|
decimal_rep, kDecimalRepCapacity,
|
||||||
|
&sign, &decimal_rep_length, &decimal_point);
|
||||||
|
} else {
|
||||||
|
DoubleToAscii(value, PRECISION, requested_digits + 1,
|
||||||
|
decimal_rep, kDecimalRepCapacity,
|
||||||
|
&sign, &decimal_rep_length, &decimal_point);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(decimal_rep_length <= requested_digits + 1);
|
||||||
|
|
||||||
|
for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
|
||||||
|
decimal_rep[i] = '0';
|
||||||
|
}
|
||||||
|
decimal_rep_length = requested_digits + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||||
|
if (sign && (value != 0.0 || !unique_zero)) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
int exponent = decimal_point - 1;
|
||||||
|
CreateExponentialRepresentation(decimal_rep,
|
||||||
|
decimal_rep_length,
|
||||||
|
exponent,
|
||||||
|
result_builder);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool DoubleToStringConverter::ToPrecision(double value,
|
||||||
|
int precision,
|
||||||
|
StringBuilder* result_builder) const {
|
||||||
|
if (Double(value).IsSpecial()) {
|
||||||
|
return HandleSpecialValues(value, result_builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find a sufficiently precise decimal representation of n.
|
||||||
|
int decimal_point;
|
||||||
|
bool sign;
|
||||||
|
// Add one for the terminating null character.
|
||||||
|
const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
|
||||||
|
char decimal_rep[kDecimalRepCapacity];
|
||||||
|
int decimal_rep_length;
|
||||||
|
|
||||||
|
DoubleToAscii(value, PRECISION, precision,
|
||||||
|
decimal_rep, kDecimalRepCapacity,
|
||||||
|
&sign, &decimal_rep_length, &decimal_point);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(decimal_rep_length <= precision);
|
||||||
|
|
||||||
|
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
||||||
|
if (sign && (value != 0.0 || !unique_zero)) {
|
||||||
|
result_builder->AddCharacter('-');
|
||||||
|
}
|
||||||
|
|
||||||
|
// The exponent if we print the number as x.xxeyyy. That is with the
|
||||||
|
// decimal point after the first digit.
|
||||||
|
int exponent = decimal_point - 1;
|
||||||
|
|
||||||
|
int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
|
||||||
|
bool as_exponential =
|
||||||
|
(-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
|
||||||
|
(decimal_point - precision + extra_zero >
|
||||||
|
max_trailing_padding_zeroes_in_precision_mode_);
|
||||||
|
if ((flags_ & NO_TRAILING_ZERO) != 0) {
|
||||||
|
// Truncate trailing zeros that occur after the decimal point (if exponential,
|
||||||
|
// that is everything after the first digit).
|
||||||
|
int stop = as_exponential ? 1 : std::max(1, decimal_point);
|
||||||
|
while (decimal_rep_length > stop && decimal_rep[decimal_rep_length - 1] == '0') {
|
||||||
|
--decimal_rep_length;
|
||||||
|
}
|
||||||
|
// Clamp precision to avoid the code below re-adding the zeros.
|
||||||
|
precision = std::min(precision, decimal_rep_length);
|
||||||
|
}
|
||||||
|
if (as_exponential) {
|
||||||
|
// Fill buffer to contain 'precision' digits.
|
||||||
|
// Usually the buffer is already at the correct length, but 'DoubleToAscii'
|
||||||
|
// is allowed to return less characters.
|
||||||
|
for (int i = decimal_rep_length; i < precision; ++i) {
|
||||||
|
decimal_rep[i] = '0';
|
||||||
|
}
|
||||||
|
|
||||||
|
CreateExponentialRepresentation(decimal_rep,
|
||||||
|
precision,
|
||||||
|
exponent,
|
||||||
|
result_builder);
|
||||||
|
} else {
|
||||||
|
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
||||||
|
(std::max)(0, precision - decimal_point),
|
||||||
|
result_builder);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static BignumDtoaMode DtoaToBignumDtoaMode(
|
||||||
|
DoubleToStringConverter::DtoaMode dtoa_mode) {
|
||||||
|
switch (dtoa_mode) {
|
||||||
|
case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
|
||||||
|
case DoubleToStringConverter::SHORTEST_SINGLE:
|
||||||
|
return BIGNUM_DTOA_SHORTEST_SINGLE;
|
||||||
|
case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
|
||||||
|
case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
|
||||||
|
default:
|
||||||
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void DoubleToStringConverter::DoubleToAscii(double v,
|
||||||
|
DtoaMode mode,
|
||||||
|
int requested_digits,
|
||||||
|
char* buffer,
|
||||||
|
int buffer_length,
|
||||||
|
bool* sign,
|
||||||
|
int* length,
|
||||||
|
int* point) {
|
||||||
|
Vector<char> vector(buffer, buffer_length);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(!Double(v).IsSpecial());
|
||||||
|
DOUBLE_CONVERSION_ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
|
||||||
|
|
||||||
|
if (Double(v).Sign() < 0) {
|
||||||
|
*sign = true;
|
||||||
|
v = -v;
|
||||||
|
} else {
|
||||||
|
*sign = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mode == PRECISION && requested_digits == 0) {
|
||||||
|
vector[0] = '\0';
|
||||||
|
*length = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v == 0) {
|
||||||
|
vector[0] = '0';
|
||||||
|
vector[1] = '\0';
|
||||||
|
*length = 1;
|
||||||
|
*point = 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool fast_worked;
|
||||||
|
switch (mode) {
|
||||||
|
case SHORTEST:
|
||||||
|
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
|
||||||
|
break;
|
||||||
|
case SHORTEST_SINGLE:
|
||||||
|
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
|
||||||
|
vector, length, point);
|
||||||
|
break;
|
||||||
|
case FIXED:
|
||||||
|
fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
|
||||||
|
break;
|
||||||
|
case PRECISION:
|
||||||
|
fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
|
||||||
|
vector, length, point);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
fast_worked = false;
|
||||||
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
|
}
|
||||||
|
if (fast_worked) return;
|
||||||
|
|
||||||
|
// If the fast dtoa didn't succeed use the slower bignum version.
|
||||||
|
BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
|
||||||
|
BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
|
||||||
|
vector[*length] = '\0';
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace double_conversion
|
445
Foundation/src/double-to-string.h
Normal file
445
Foundation/src/double-to-string.h
Normal file
@@ -0,0 +1,445 @@
|
|||||||
|
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// * Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
// * Redistributions in binary form must reproduce the above
|
||||||
|
// copyright notice, this list of conditions and the following
|
||||||
|
// disclaimer in the documentation and/or other materials provided
|
||||||
|
// with the distribution.
|
||||||
|
// * Neither the name of Google Inc. nor the names of its
|
||||||
|
// contributors may be used to endorse or promote products derived
|
||||||
|
// from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
#ifndef DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
|
||||||
|
#define DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
|
||||||
|
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
|
namespace double_conversion {
|
||||||
|
|
||||||
|
class DoubleToStringConverter {
|
||||||
|
public:
|
||||||
|
// When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
|
||||||
|
// or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
|
||||||
|
// function returns false.
|
||||||
|
static const int kMaxFixedDigitsBeforePoint = 60;
|
||||||
|
static const int kMaxFixedDigitsAfterPoint = 100;
|
||||||
|
|
||||||
|
// When calling ToExponential with a requested_digits
|
||||||
|
// parameter > kMaxExponentialDigits then the function returns false.
|
||||||
|
static const int kMaxExponentialDigits = 120;
|
||||||
|
|
||||||
|
// When calling ToPrecision with a requested_digits
|
||||||
|
// parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
|
||||||
|
// then the function returns false.
|
||||||
|
static const int kMinPrecisionDigits = 1;
|
||||||
|
static const int kMaxPrecisionDigits = 120;
|
||||||
|
|
||||||
|
// The maximal number of digits that are needed to emit a double in base 10.
|
||||||
|
// A higher precision can be achieved by using more digits, but the shortest
|
||||||
|
// accurate representation of any double will never use more digits than
|
||||||
|
// kBase10MaximalLength.
|
||||||
|
// Note that DoubleToAscii null-terminates its input. So the given buffer
|
||||||
|
// should be at least kBase10MaximalLength + 1 characters long.
|
||||||
|
static const int kBase10MaximalLength = 17;
|
||||||
|
|
||||||
|
// The maximal number of digits that are needed to emit a single in base 10.
|
||||||
|
// A higher precision can be achieved by using more digits, but the shortest
|
||||||
|
// accurate representation of any single will never use more digits than
|
||||||
|
// kBase10MaximalLengthSingle.
|
||||||
|
static const int kBase10MaximalLengthSingle = 9;
|
||||||
|
|
||||||
|
// The length of the longest string that 'ToShortest' can produce when the
|
||||||
|
// converter is instantiated with EcmaScript defaults (see
|
||||||
|
// 'EcmaScriptConverter')
|
||||||
|
// This value does not include the trailing '\0' character.
|
||||||
|
// This amount of characters is needed for negative values that hit the
|
||||||
|
// 'decimal_in_shortest_low' limit. For example: "-0.0000033333333333333333"
|
||||||
|
static const int kMaxCharsEcmaScriptShortest = 25;
|
||||||
|
|
||||||
|
enum Flags {
|
||||||
|
NO_FLAGS = 0,
|
||||||
|
EMIT_POSITIVE_EXPONENT_SIGN = 1,
|
||||||
|
EMIT_TRAILING_DECIMAL_POINT = 2,
|
||||||
|
EMIT_TRAILING_ZERO_AFTER_POINT = 4,
|
||||||
|
UNIQUE_ZERO = 8,
|
||||||
|
NO_TRAILING_ZERO = 16
|
||||||
|
};
|
||||||
|
|
||||||
|
// Flags should be a bit-or combination of the possible Flags-enum.
|
||||||
|
// - NO_FLAGS: no special flags.
|
||||||
|
// - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
|
||||||
|
// form, emits a '+' for positive exponents. Example: 1.2e+2.
|
||||||
|
// - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
|
||||||
|
// converted into decimal format then a trailing decimal point is appended.
|
||||||
|
// Example: 2345.0 is converted to "2345.".
|
||||||
|
// - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
|
||||||
|
// emits a trailing '0'-character. This flag requires the
|
||||||
|
// EMIT_TRAILING_DECIMAL_POINT flag.
|
||||||
|
// Example: 2345.0 is converted to "2345.0".
|
||||||
|
// - UNIQUE_ZERO: "-0.0" is converted to "0.0".
|
||||||
|
// - NO_TRAILING_ZERO: Trailing zeros are removed from the fractional portion
|
||||||
|
// of the result in precision mode. Matches printf's %g.
|
||||||
|
// When EMIT_TRAILING_ZERO_AFTER_POINT is also given, one trailing zero is
|
||||||
|
// preserved.
|
||||||
|
//
|
||||||
|
// Infinity symbol and nan_symbol provide the string representation for these
|
||||||
|
// special values. If the string is NULL and the special value is encountered
|
||||||
|
// then the conversion functions return false.
|
||||||
|
//
|
||||||
|
// The exponent_character is used in exponential representations. It is
|
||||||
|
// usually 'e' or 'E'.
|
||||||
|
//
|
||||||
|
// When converting to the shortest representation the converter will
|
||||||
|
// represent input numbers in decimal format if they are in the interval
|
||||||
|
// [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
|
||||||
|
// (lower boundary included, greater boundary excluded).
|
||||||
|
// Example: with decimal_in_shortest_low = -6 and
|
||||||
|
// decimal_in_shortest_high = 21:
|
||||||
|
// ToShortest(0.000001) -> "0.000001"
|
||||||
|
// ToShortest(0.0000001) -> "1e-7"
|
||||||
|
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
||||||
|
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
||||||
|
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
||||||
|
//
|
||||||
|
// When converting to precision mode the converter may add
|
||||||
|
// max_leading_padding_zeroes before returning the number in exponential
|
||||||
|
// format.
|
||||||
|
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
||||||
|
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
||||||
|
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
||||||
|
// Similarly the converter may add up to
|
||||||
|
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
||||||
|
// returning an exponential representation. A zero added by the
|
||||||
|
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
||||||
|
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
||||||
|
// ToPrecision(230.0, 2) -> "230"
|
||||||
|
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
||||||
|
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||||
|
//
|
||||||
|
// The min_exponent_width is used for exponential representations.
|
||||||
|
// The converter adds leading '0's to the exponent until the exponent
|
||||||
|
// is at least min_exponent_width digits long.
|
||||||
|
// The min_exponent_width is clamped to 5.
|
||||||
|
// As such, the exponent may never have more than 5 digits in total.
|
||||||
|
DoubleToStringConverter(int flags,
|
||||||
|
const char* infinity_symbol,
|
||||||
|
const char* nan_symbol,
|
||||||
|
char exponent_character,
|
||||||
|
int decimal_in_shortest_low,
|
||||||
|
int decimal_in_shortest_high,
|
||||||
|
int max_leading_padding_zeroes_in_precision_mode,
|
||||||
|
int max_trailing_padding_zeroes_in_precision_mode,
|
||||||
|
int min_exponent_width = 0)
|
||||||
|
: flags_(flags),
|
||||||
|
infinity_symbol_(infinity_symbol),
|
||||||
|
nan_symbol_(nan_symbol),
|
||||||
|
exponent_character_(exponent_character),
|
||||||
|
decimal_in_shortest_low_(decimal_in_shortest_low),
|
||||||
|
decimal_in_shortest_high_(decimal_in_shortest_high),
|
||||||
|
max_leading_padding_zeroes_in_precision_mode_(
|
||||||
|
max_leading_padding_zeroes_in_precision_mode),
|
||||||
|
max_trailing_padding_zeroes_in_precision_mode_(
|
||||||
|
max_trailing_padding_zeroes_in_precision_mode),
|
||||||
|
min_exponent_width_(min_exponent_width) {
|
||||||
|
// When 'trailing zero after the point' is set, then 'trailing point'
|
||||||
|
// must be set too.
|
||||||
|
DOUBLE_CONVERSION_ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
|
||||||
|
!((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns a converter following the EcmaScript specification.
|
||||||
|
//
|
||||||
|
// Flags: UNIQUE_ZERO and EMIT_POSITIVE_EXPONENT_SIGN.
|
||||||
|
// Special values: "Infinity" and "NaN".
|
||||||
|
// Lower case 'e' for exponential values.
|
||||||
|
// decimal_in_shortest_low: -6
|
||||||
|
// decimal_in_shortest_high: 21
|
||||||
|
// max_leading_padding_zeroes_in_precision_mode: 6
|
||||||
|
// max_trailing_padding_zeroes_in_precision_mode: 0
|
||||||
|
static const DoubleToStringConverter& EcmaScriptConverter();
|
||||||
|
|
||||||
|
// Computes the shortest string of digits that correctly represent the input
|
||||||
|
// number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
|
||||||
|
// (see constructor) it then either returns a decimal representation, or an
|
||||||
|
// exponential representation.
|
||||||
|
// Example with decimal_in_shortest_low = -6,
|
||||||
|
// decimal_in_shortest_high = 21,
|
||||||
|
// EMIT_POSITIVE_EXPONENT_SIGN activated, and
|
||||||
|
// EMIT_TRAILING_DECIMAL_POINT deactivated:
|
||||||
|
// ToShortest(0.000001) -> "0.000001"
|
||||||
|
// ToShortest(0.0000001) -> "1e-7"
|
||||||
|
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
||||||
|
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
||||||
|
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
||||||
|
//
|
||||||
|
// Note: the conversion may round the output if the returned string
|
||||||
|
// is accurate enough to uniquely identify the input-number.
|
||||||
|
// For example the most precise representation of the double 9e59 equals
|
||||||
|
// "899999999999999918767229449717619953810131273674690656206848", but
|
||||||
|
// the converter will return the shorter (but still correct) "9e59".
|
||||||
|
//
|
||||||
|
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||||
|
// except when the input value is special and no infinity_symbol or
|
||||||
|
// nan_symbol has been given to the constructor.
|
||||||
|
//
|
||||||
|
// The length of the longest result is the maximum of the length of the
|
||||||
|
// following string representations (each with possible examples):
|
||||||
|
// - NaN and negative infinity: "NaN", "-Infinity", "-inf".
|
||||||
|
// - -10^(decimal_in_shortest_high - 1):
|
||||||
|
// "-100000000000000000000", "-1000000000000000.0"
|
||||||
|
// - the longest string in range [0; -10^decimal_in_shortest_low]. Generally,
|
||||||
|
// this string is 3 + kBase10MaximalLength - decimal_in_shortest_low.
|
||||||
|
// (Sign, '0', decimal point, padding zeroes for decimal_in_shortest_low,
|
||||||
|
// and the significant digits).
|
||||||
|
// "-0.0000033333333333333333", "-0.0012345678901234567"
|
||||||
|
// - the longest exponential representation. (A negative number with
|
||||||
|
// kBase10MaximalLength significant digits).
|
||||||
|
// "-1.7976931348623157e+308", "-1.7976931348623157E308"
|
||||||
|
// In addition, the buffer must be able to hold the trailing '\0' character.
|
||||||
|
bool ToShortest(double value, StringBuilder* result_builder) const {
|
||||||
|
return ToShortestIeeeNumber(value, result_builder, SHORTEST);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Same as ToShortest, but for single-precision floats.
|
||||||
|
bool ToShortestSingle(float value, StringBuilder* result_builder) const {
|
||||||
|
return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Computes a decimal representation with a fixed number of digits after the
|
||||||
|
// decimal point. The last emitted digit is rounded.
|
||||||
|
//
|
||||||
|
// Examples:
|
||||||
|
// ToFixed(3.12, 1) -> "3.1"
|
||||||
|
// ToFixed(3.1415, 3) -> "3.142"
|
||||||
|
// ToFixed(1234.56789, 4) -> "1234.5679"
|
||||||
|
// ToFixed(1.23, 5) -> "1.23000"
|
||||||
|
// ToFixed(0.1, 4) -> "0.1000"
|
||||||
|
// ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
|
||||||
|
// ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
|
||||||
|
// ToFixed(0.1, 17) -> "0.10000000000000001"
|
||||||
|
//
|
||||||
|
// If requested_digits equals 0, then the tail of the result depends on
|
||||||
|
// the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||||
|
// Examples, for requested_digits == 0,
|
||||||
|
// let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
|
||||||
|
// - false and false: then 123.45 -> 123
|
||||||
|
// 0.678 -> 1
|
||||||
|
// - true and false: then 123.45 -> 123.
|
||||||
|
// 0.678 -> 1.
|
||||||
|
// - true and true: then 123.45 -> 123.0
|
||||||
|
// 0.678 -> 1.0
|
||||||
|
//
|
||||||
|
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||||
|
// except for the following cases:
|
||||||
|
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||||
|
// been provided to the constructor,
|
||||||
|
// - 'value' > 10^kMaxFixedDigitsBeforePoint, or
|
||||||
|
// - 'requested_digits' > kMaxFixedDigitsAfterPoint.
|
||||||
|
// The last two conditions imply that the result for non-special values never
|
||||||
|
// contains more than
|
||||||
|
// 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
|
||||||
|
// (one additional character for the sign, and one for the decimal point).
|
||||||
|
// In addition, the buffer must be able to hold the trailing '\0' character.
|
||||||
|
bool ToFixed(double value,
|
||||||
|
int requested_digits,
|
||||||
|
StringBuilder* result_builder) const;
|
||||||
|
|
||||||
|
// Computes a representation in exponential format with requested_digits
|
||||||
|
// after the decimal point. The last emitted digit is rounded.
|
||||||
|
// If requested_digits equals -1, then the shortest exponential representation
|
||||||
|
// is computed.
|
||||||
|
//
|
||||||
|
// Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
|
||||||
|
// exponent_character set to 'e'.
|
||||||
|
// ToExponential(3.12, 1) -> "3.1e0"
|
||||||
|
// ToExponential(5.0, 3) -> "5.000e0"
|
||||||
|
// ToExponential(0.001, 2) -> "1.00e-3"
|
||||||
|
// ToExponential(3.1415, -1) -> "3.1415e0"
|
||||||
|
// ToExponential(3.1415, 4) -> "3.1415e0"
|
||||||
|
// ToExponential(3.1415, 3) -> "3.142e0"
|
||||||
|
// ToExponential(123456789000000, 3) -> "1.235e14"
|
||||||
|
// ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
|
||||||
|
// ToExponential(1000000000000000019884624838656.0, 32) ->
|
||||||
|
// "1.00000000000000001988462483865600e30"
|
||||||
|
// ToExponential(1234, 0) -> "1e3"
|
||||||
|
//
|
||||||
|
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||||
|
// except for the following cases:
|
||||||
|
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||||
|
// been provided to the constructor,
|
||||||
|
// - 'requested_digits' > kMaxExponentialDigits.
|
||||||
|
//
|
||||||
|
// The last condition implies that the result never contains more than
|
||||||
|
// kMaxExponentialDigits + 8 characters (the sign, the digit before the
|
||||||
|
// decimal point, the decimal point, the exponent character, the
|
||||||
|
// exponent's sign, and at most 3 exponent digits).
|
||||||
|
// In addition, the buffer must be able to hold the trailing '\0' character.
|
||||||
|
bool ToExponential(double value,
|
||||||
|
int requested_digits,
|
||||||
|
StringBuilder* result_builder) const;
|
||||||
|
|
||||||
|
|
||||||
|
// Computes 'precision' leading digits of the given 'value' and returns them
|
||||||
|
// either in exponential or decimal format, depending on
|
||||||
|
// max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
|
||||||
|
// constructor).
|
||||||
|
// The last computed digit is rounded.
|
||||||
|
//
|
||||||
|
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
||||||
|
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
||||||
|
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
||||||
|
// Similarly the converter may add up to
|
||||||
|
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
||||||
|
// returning an exponential representation. A zero added by the
|
||||||
|
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
||||||
|
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
||||||
|
// ToPrecision(230.0, 2) -> "230"
|
||||||
|
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
||||||
|
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
||||||
|
// Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
|
||||||
|
// EMIT_TRAILING_ZERO_AFTER_POINT:
|
||||||
|
// ToPrecision(123450.0, 6) -> "123450"
|
||||||
|
// ToPrecision(123450.0, 5) -> "123450"
|
||||||
|
// ToPrecision(123450.0, 4) -> "123500"
|
||||||
|
// ToPrecision(123450.0, 3) -> "123000"
|
||||||
|
// ToPrecision(123450.0, 2) -> "1.2e5"
|
||||||
|
//
|
||||||
|
// Returns true if the conversion succeeds. The conversion always succeeds
|
||||||
|
// except for the following cases:
|
||||||
|
// - the input value is special and no infinity_symbol or nan_symbol has
|
||||||
|
// been provided to the constructor,
|
||||||
|
// - precision < kMinPericisionDigits
|
||||||
|
// - precision > kMaxPrecisionDigits
|
||||||
|
//
|
||||||
|
// The last condition implies that the result never contains more than
|
||||||
|
// kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
|
||||||
|
// exponent character, the exponent's sign, and at most 3 exponent digits).
|
||||||
|
// In addition, the buffer must be able to hold the trailing '\0' character.
|
||||||
|
bool ToPrecision(double value,
|
||||||
|
int precision,
|
||||||
|
StringBuilder* result_builder) const;
|
||||||
|
|
||||||
|
enum DtoaMode {
|
||||||
|
// Produce the shortest correct representation.
|
||||||
|
// For example the output of 0.299999999999999988897 is (the less accurate
|
||||||
|
// but correct) 0.3.
|
||||||
|
SHORTEST,
|
||||||
|
// Same as SHORTEST, but for single-precision floats.
|
||||||
|
SHORTEST_SINGLE,
|
||||||
|
// Produce a fixed number of digits after the decimal point.
|
||||||
|
// For instance fixed(0.1, 4) becomes 0.1000
|
||||||
|
// If the input number is big, the output will be big.
|
||||||
|
FIXED,
|
||||||
|
// Fixed number of digits (independent of the decimal point).
|
||||||
|
PRECISION
|
||||||
|
};
|
||||||
|
|
||||||
|
// Converts the given double 'v' to digit characters. 'v' must not be NaN,
|
||||||
|
// +Infinity, or -Infinity. In SHORTEST_SINGLE-mode this restriction also
|
||||||
|
// applies to 'v' after it has been casted to a single-precision float. That
|
||||||
|
// is, in this mode static_cast<float>(v) must not be NaN, +Infinity or
|
||||||
|
// -Infinity.
|
||||||
|
//
|
||||||
|
// The result should be interpreted as buffer * 10^(point-length).
|
||||||
|
//
|
||||||
|
// The digits are written to the buffer in the platform's charset, which is
|
||||||
|
// often UTF-8 (with ASCII-range digits) but may be another charset, such
|
||||||
|
// as EBCDIC.
|
||||||
|
//
|
||||||
|
// The output depends on the given mode:
|
||||||
|
// - SHORTEST: produce the least amount of digits for which the internal
|
||||||
|
// identity requirement is still satisfied. If the digits are printed
|
||||||
|
// (together with the correct exponent) then reading this number will give
|
||||||
|
// 'v' again. The buffer will choose the representation that is closest to
|
||||||
|
// 'v'. If there are two at the same distance, than the one farther away
|
||||||
|
// from 0 is chosen (halfway cases - ending with 5 - are rounded up).
|
||||||
|
// In this mode the 'requested_digits' parameter is ignored.
|
||||||
|
// - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
|
||||||
|
// - FIXED: produces digits necessary to print a given number with
|
||||||
|
// 'requested_digits' digits after the decimal point. The produced digits
|
||||||
|
// might be too short in which case the caller has to fill the remainder
|
||||||
|
// with '0's.
|
||||||
|
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
||||||
|
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
||||||
|
// toFixed(0.15, 2) thus returns buffer="2", point=0.
|
||||||
|
// The returned buffer may contain digits that would be truncated from the
|
||||||
|
// shortest representation of the input.
|
||||||
|
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
||||||
|
// Even though the length of produced digits usually equals
|
||||||
|
// 'requested_digits', the function is allowed to return fewer digits, in
|
||||||
|
// which case the caller has to fill the missing digits with '0's.
|
||||||
|
// Halfway cases are again rounded away from 0.
|
||||||
|
// DoubleToAscii expects the given buffer to be big enough to hold all
|
||||||
|
// digits and a terminating null-character. In SHORTEST-mode it expects a
|
||||||
|
// buffer of at least kBase10MaximalLength + 1. In all other modes the
|
||||||
|
// requested_digits parameter and the padding-zeroes limit the size of the
|
||||||
|
// output. Don't forget the decimal point, the exponent character and the
|
||||||
|
// terminating null-character when computing the maximal output size.
|
||||||
|
// The given length is only used in debug mode to ensure the buffer is big
|
||||||
|
// enough.
|
||||||
|
static void DoubleToAscii(double v,
|
||||||
|
DtoaMode mode,
|
||||||
|
int requested_digits,
|
||||||
|
char* buffer,
|
||||||
|
int buffer_length,
|
||||||
|
bool* sign,
|
||||||
|
int* length,
|
||||||
|
int* point);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Implementation for ToShortest and ToShortestSingle.
|
||||||
|
bool ToShortestIeeeNumber(double value,
|
||||||
|
StringBuilder* result_builder,
|
||||||
|
DtoaMode mode) const;
|
||||||
|
|
||||||
|
// If the value is a special value (NaN or Infinity) constructs the
|
||||||
|
// corresponding string using the configured infinity/nan-symbol.
|
||||||
|
// If either of them is NULL or the value is not special then the
|
||||||
|
// function returns false.
|
||||||
|
bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
|
||||||
|
// Constructs an exponential representation (i.e. 1.234e56).
|
||||||
|
// The given exponent assumes a decimal point after the first decimal digit.
|
||||||
|
void CreateExponentialRepresentation(const char* decimal_digits,
|
||||||
|
int length,
|
||||||
|
int exponent,
|
||||||
|
StringBuilder* result_builder) const;
|
||||||
|
// Creates a decimal representation (i.e 1234.5678).
|
||||||
|
void CreateDecimalRepresentation(const char* decimal_digits,
|
||||||
|
int length,
|
||||||
|
int decimal_point,
|
||||||
|
int digits_after_point,
|
||||||
|
StringBuilder* result_builder) const;
|
||||||
|
|
||||||
|
const int flags_;
|
||||||
|
const char* const infinity_symbol_;
|
||||||
|
const char* const nan_symbol_;
|
||||||
|
const char exponent_character_;
|
||||||
|
const int decimal_in_shortest_low_;
|
||||||
|
const int decimal_in_shortest_high_;
|
||||||
|
const int max_leading_padding_zeroes_in_precision_mode_;
|
||||||
|
const int max_trailing_padding_zeroes_in_precision_mode_;
|
||||||
|
const int min_exponent_width_;
|
||||||
|
|
||||||
|
DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace double_conversion
|
||||||
|
|
||||||
|
#endif // DOUBLE_CONVERSION_DOUBLE_TO_STRING_H_
|
@@ -138,7 +138,7 @@ static bool RoundWeed(Vector<char> buffer,
|
|||||||
// Conceptually rest ~= too_high - buffer
|
// Conceptually rest ~= too_high - buffer
|
||||||
// We need to do the following tests in this order to avoid over- and
|
// We need to do the following tests in this order to avoid over- and
|
||||||
// underflows.
|
// underflows.
|
||||||
ASSERT(rest <= unsafe_interval);
|
DOUBLE_CONVERSION_ASSERT(rest <= unsafe_interval);
|
||||||
while (rest < small_distance && // Negated condition 1
|
while (rest < small_distance && // Negated condition 1
|
||||||
unsafe_interval - rest >= ten_kappa && // Negated condition 2
|
unsafe_interval - rest >= ten_kappa && // Negated condition 2
|
||||||
(rest + ten_kappa < small_distance || // buffer{-1} > w_high
|
(rest + ten_kappa < small_distance || // buffer{-1} > w_high
|
||||||
@@ -184,7 +184,7 @@ static bool RoundWeedCounted(Vector<char> buffer,
|
|||||||
uint64_t ten_kappa,
|
uint64_t ten_kappa,
|
||||||
uint64_t unit,
|
uint64_t unit,
|
||||||
int* kappa) {
|
int* kappa) {
|
||||||
ASSERT(rest < ten_kappa);
|
DOUBLE_CONVERSION_ASSERT(rest < ten_kappa);
|
||||||
// The following tests are done in a specific order to avoid overflows. They
|
// The following tests are done in a specific order to avoid overflows. They
|
||||||
// will work correctly with any uint64 values of rest < ten_kappa and unit.
|
// will work correctly with any uint64 values of rest < ten_kappa and unit.
|
||||||
//
|
//
|
||||||
@@ -241,7 +241,7 @@ static void BiggestPowerTen(uint32_t number,
|
|||||||
int number_bits,
|
int number_bits,
|
||||||
uint32_t* power,
|
uint32_t* power,
|
||||||
int* exponent_plus_one) {
|
int* exponent_plus_one) {
|
||||||
ASSERT(number < (1u << (number_bits + 1)));
|
DOUBLE_CONVERSION_ASSERT(number < (1u << (number_bits + 1)));
|
||||||
// 1233/4096 is approximately 1/lg(10).
|
// 1233/4096 is approximately 1/lg(10).
|
||||||
int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
|
int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
|
||||||
// We increment to skip over the first entry in the kPowersOf10 table.
|
// We increment to skip over the first entry in the kPowersOf10 table.
|
||||||
@@ -303,9 +303,9 @@ static bool DigitGen(DiyFp low,
|
|||||||
Vector<char> buffer,
|
Vector<char> buffer,
|
||||||
int* length,
|
int* length,
|
||||||
int* kappa) {
|
int* kappa) {
|
||||||
ASSERT(low.e() == w.e() && w.e() == high.e());
|
DOUBLE_CONVERSION_ASSERT(low.e() == w.e() && w.e() == high.e());
|
||||||
ASSERT(low.f() + 1 <= high.f() - 1);
|
DOUBLE_CONVERSION_ASSERT(low.f() + 1 <= high.f() - 1);
|
||||||
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
||||||
// low, w and high are imprecise, but by less than one ulp (unit in the last
|
// low, w and high are imprecise, but by less than one ulp (unit in the last
|
||||||
// place).
|
// place).
|
||||||
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
|
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
|
||||||
@@ -347,7 +347,7 @@ static bool DigitGen(DiyFp low,
|
|||||||
// that is smaller than integrals.
|
// that is smaller than integrals.
|
||||||
while (*kappa > 0) {
|
while (*kappa > 0) {
|
||||||
int digit = integrals / divisor;
|
int digit = integrals / divisor;
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
integrals %= divisor;
|
integrals %= divisor;
|
||||||
@@ -374,16 +374,16 @@ static bool DigitGen(DiyFp low,
|
|||||||
// data (like the interval or 'unit'), too.
|
// data (like the interval or 'unit'), too.
|
||||||
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
||||||
// and thus one.e >= -60.
|
// and thus one.e >= -60.
|
||||||
ASSERT(one.e() >= -60);
|
DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
|
||||||
ASSERT(fractionals < one.f());
|
DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
|
||||||
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
||||||
for (;;) {
|
for (;;) {
|
||||||
fractionals *= 10;
|
fractionals *= 10;
|
||||||
unit *= 10;
|
unit *= 10;
|
||||||
unsafe_interval.set_f(unsafe_interval.f() * 10);
|
unsafe_interval.set_f(unsafe_interval.f() * 10);
|
||||||
// Integer division by one.
|
// Integer division by one.
|
||||||
int digit = static_cast<int>(fractionals >> -one.e());
|
int digit = static_cast<int>(fractionals >> -one.e());
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
fractionals &= one.f() - 1; // Modulo by one.
|
fractionals &= one.f() - 1; // Modulo by one.
|
||||||
@@ -430,9 +430,9 @@ static bool DigitGenCounted(DiyFp w,
|
|||||||
Vector<char> buffer,
|
Vector<char> buffer,
|
||||||
int* length,
|
int* length,
|
||||||
int* kappa) {
|
int* kappa) {
|
||||||
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
||||||
ASSERT(kMinimalTargetExponent >= -60);
|
DOUBLE_CONVERSION_ASSERT(kMinimalTargetExponent >= -60);
|
||||||
ASSERT(kMaximalTargetExponent <= -32);
|
DOUBLE_CONVERSION_ASSERT(kMaximalTargetExponent <= -32);
|
||||||
// w is assumed to have an error less than 1 unit. Whenever w is scaled we
|
// w is assumed to have an error less than 1 unit. Whenever w is scaled we
|
||||||
// also scale its error.
|
// also scale its error.
|
||||||
uint64_t w_error = 1;
|
uint64_t w_error = 1;
|
||||||
@@ -458,7 +458,7 @@ static bool DigitGenCounted(DiyFp w,
|
|||||||
// that is smaller than 'integrals'.
|
// that is smaller than 'integrals'.
|
||||||
while (*kappa > 0) {
|
while (*kappa > 0) {
|
||||||
int digit = integrals / divisor;
|
int digit = integrals / divisor;
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
requested_digits--;
|
requested_digits--;
|
||||||
@@ -484,15 +484,15 @@ static bool DigitGenCounted(DiyFp w,
|
|||||||
// data (the 'unit'), too.
|
// data (the 'unit'), too.
|
||||||
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
||||||
// and thus one.e >= -60.
|
// and thus one.e >= -60.
|
||||||
ASSERT(one.e() >= -60);
|
DOUBLE_CONVERSION_ASSERT(one.e() >= -60);
|
||||||
ASSERT(fractionals < one.f());
|
DOUBLE_CONVERSION_ASSERT(fractionals < one.f());
|
||||||
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
DOUBLE_CONVERSION_ASSERT(DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
||||||
while (requested_digits > 0 && fractionals > w_error) {
|
while (requested_digits > 0 && fractionals > w_error) {
|
||||||
fractionals *= 10;
|
fractionals *= 10;
|
||||||
w_error *= 10;
|
w_error *= 10;
|
||||||
// Integer division by one.
|
// Integer division by one.
|
||||||
int digit = static_cast<int>(fractionals >> -one.e());
|
int digit = static_cast<int>(fractionals >> -one.e());
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
requested_digits--;
|
requested_digits--;
|
||||||
@@ -530,11 +530,11 @@ static bool Grisu3(double v,
|
|||||||
if (mode == FAST_DTOA_SHORTEST) {
|
if (mode == FAST_DTOA_SHORTEST) {
|
||||||
Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
||||||
} else {
|
} else {
|
||||||
ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
|
DOUBLE_CONVERSION_ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
|
||||||
float single_v = static_cast<float>(v);
|
float single_v = static_cast<float>(v);
|
||||||
Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
||||||
}
|
}
|
||||||
ASSERT(boundary_plus.e() == w.e());
|
DOUBLE_CONVERSION_ASSERT(boundary_plus.e() == w.e());
|
||||||
DiyFp ten_mk; // Cached power of ten: 10^-k
|
DiyFp ten_mk; // Cached power of ten: 10^-k
|
||||||
int mk; // -k
|
int mk; // -k
|
||||||
int ten_mk_minimal_binary_exponent =
|
int ten_mk_minimal_binary_exponent =
|
||||||
@@ -545,7 +545,7 @@ static bool Grisu3(double v,
|
|||||||
ten_mk_minimal_binary_exponent,
|
ten_mk_minimal_binary_exponent,
|
||||||
ten_mk_maximal_binary_exponent,
|
ten_mk_maximal_binary_exponent,
|
||||||
&ten_mk, &mk);
|
&ten_mk, &mk);
|
||||||
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
||||||
DiyFp::kSignificandSize) &&
|
DiyFp::kSignificandSize) &&
|
||||||
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
||||||
DiyFp::kSignificandSize));
|
DiyFp::kSignificandSize));
|
||||||
@@ -559,13 +559,13 @@ static bool Grisu3(double v,
|
|||||||
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
||||||
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
||||||
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
||||||
ASSERT(scaled_w.e() ==
|
DOUBLE_CONVERSION_ASSERT(scaled_w.e() ==
|
||||||
boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
|
boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
|
||||||
// In theory it would be possible to avoid some recomputations by computing
|
// In theory it would be possible to avoid some recomputations by computing
|
||||||
// the difference between w and boundary_minus/plus (a power of 2) and to
|
// the difference between w and boundary_minus/plus (a power of 2) and to
|
||||||
// compute scaled_boundary_minus/plus by subtracting/adding from
|
// compute scaled_boundary_minus/plus by subtracting/adding from
|
||||||
// scaled_w. However the code becomes much less readable and the speed
|
// scaled_w. However the code becomes much less readable and the speed
|
||||||
// enhancements are not terriffic.
|
// enhancements are not terrific.
|
||||||
DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
|
DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
|
||||||
DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
|
DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
|
||||||
|
|
||||||
@@ -573,7 +573,7 @@ static bool Grisu3(double v,
|
|||||||
// v == (double) (scaled_w * 10^-mk).
|
// v == (double) (scaled_w * 10^-mk).
|
||||||
// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
|
// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
|
||||||
// integer than it will be updated. For instance if scaled_w == 1.23 then
|
// integer than it will be updated. For instance if scaled_w == 1.23 then
|
||||||
// the buffer will be filled with "123" und the decimal_exponent will be
|
// the buffer will be filled with "123" and the decimal_exponent will be
|
||||||
// decreased by 2.
|
// decreased by 2.
|
||||||
int kappa;
|
int kappa;
|
||||||
bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
|
bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
|
||||||
@@ -604,7 +604,7 @@ static bool Grisu3Counted(double v,
|
|||||||
ten_mk_minimal_binary_exponent,
|
ten_mk_minimal_binary_exponent,
|
||||||
ten_mk_maximal_binary_exponent,
|
ten_mk_maximal_binary_exponent,
|
||||||
&ten_mk, &mk);
|
&ten_mk, &mk);
|
||||||
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
DOUBLE_CONVERSION_ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
||||||
DiyFp::kSignificandSize) &&
|
DiyFp::kSignificandSize) &&
|
||||||
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
||||||
DiyFp::kSignificandSize));
|
DiyFp::kSignificandSize));
|
||||||
@@ -638,8 +638,8 @@ bool FastDtoa(double v,
|
|||||||
Vector<char> buffer,
|
Vector<char> buffer,
|
||||||
int* length,
|
int* length,
|
||||||
int* decimal_point) {
|
int* decimal_point) {
|
||||||
ASSERT(v > 0);
|
DOUBLE_CONVERSION_ASSERT(v > 0);
|
||||||
ASSERT(!Double(v).IsSpecial());
|
DOUBLE_CONVERSION_ASSERT(!Double(v).IsSpecial());
|
||||||
|
|
||||||
bool result = false;
|
bool result = false;
|
||||||
int decimal_exponent = 0;
|
int decimal_exponent = 0;
|
||||||
@@ -653,7 +653,7 @@ bool FastDtoa(double v,
|
|||||||
buffer, length, &decimal_exponent);
|
buffer, length, &decimal_exponent);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
UNREACHABLE();
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
}
|
}
|
||||||
if (result) {
|
if (result) {
|
||||||
*decimal_point = *length + decimal_exponent;
|
*decimal_point = *length + decimal_exponent;
|
||||||
|
@@ -53,11 +53,11 @@ class UInt128 {
|
|||||||
accumulator >>= 32;
|
accumulator >>= 32;
|
||||||
accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
|
accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
|
||||||
high_bits_ = (accumulator << 32) + part;
|
high_bits_ = (accumulator << 32) + part;
|
||||||
ASSERT((accumulator >> 32) == 0);
|
DOUBLE_CONVERSION_ASSERT((accumulator >> 32) == 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void Shift(int shift_amount) {
|
void Shift(int shift_amount) {
|
||||||
ASSERT(-64 <= shift_amount && shift_amount <= 64);
|
DOUBLE_CONVERSION_ASSERT(-64 <= shift_amount && shift_amount <= 64);
|
||||||
if (shift_amount == 0) {
|
if (shift_amount == 0) {
|
||||||
return;
|
return;
|
||||||
} else if (shift_amount == -64) {
|
} else if (shift_amount == -64) {
|
||||||
@@ -230,13 +230,13 @@ static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
|
|||||||
static void FillFractionals(uint64_t fractionals, int exponent,
|
static void FillFractionals(uint64_t fractionals, int exponent,
|
||||||
int fractional_count, Vector<char> buffer,
|
int fractional_count, Vector<char> buffer,
|
||||||
int* length, int* decimal_point) {
|
int* length, int* decimal_point) {
|
||||||
ASSERT(-128 <= exponent && exponent <= 0);
|
DOUBLE_CONVERSION_ASSERT(-128 <= exponent && exponent <= 0);
|
||||||
// 'fractionals' is a fixed-point number, with binary point at bit
|
// 'fractionals' is a fixed-point number, with binary point at bit
|
||||||
// (-exponent). Inside the function the non-converted remainder of fractionals
|
// (-exponent). Inside the function the non-converted remainder of fractionals
|
||||||
// is a fixed-point number, with binary point at bit 'point'.
|
// is a fixed-point number, with binary point at bit 'point'.
|
||||||
if (-exponent <= 64) {
|
if (-exponent <= 64) {
|
||||||
// One 64 bit number is sufficient.
|
// One 64 bit number is sufficient.
|
||||||
ASSERT(fractionals >> 56 == 0);
|
DOUBLE_CONVERSION_ASSERT(fractionals >> 56 == 0);
|
||||||
int point = -exponent;
|
int point = -exponent;
|
||||||
for (int i = 0; i < fractional_count; ++i) {
|
for (int i = 0; i < fractional_count; ++i) {
|
||||||
if (fractionals == 0) break;
|
if (fractionals == 0) break;
|
||||||
@@ -253,18 +253,18 @@ static void FillFractionals(uint64_t fractionals, int exponent,
|
|||||||
fractionals *= 5;
|
fractionals *= 5;
|
||||||
point--;
|
point--;
|
||||||
int digit = static_cast<int>(fractionals >> point);
|
int digit = static_cast<int>(fractionals >> point);
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
fractionals -= static_cast<uint64_t>(digit) << point;
|
fractionals -= static_cast<uint64_t>(digit) << point;
|
||||||
}
|
}
|
||||||
// If the first bit after the point is set we have to round up.
|
// If the first bit after the point is set we have to round up.
|
||||||
ASSERT(fractionals == 0 || point - 1 >= 0);
|
DOUBLE_CONVERSION_ASSERT(fractionals == 0 || point - 1 >= 0);
|
||||||
if ((fractionals != 0) && ((fractionals >> (point - 1)) & 1) == 1) {
|
if ((fractionals != 0) && ((fractionals >> (point - 1)) & 1) == 1) {
|
||||||
RoundUp(buffer, length, decimal_point);
|
RoundUp(buffer, length, decimal_point);
|
||||||
}
|
}
|
||||||
} else { // We need 128 bits.
|
} else { // We need 128 bits.
|
||||||
ASSERT(64 < -exponent && -exponent <= 128);
|
DOUBLE_CONVERSION_ASSERT(64 < -exponent && -exponent <= 128);
|
||||||
UInt128 fractionals128 = UInt128(fractionals, 0);
|
UInt128 fractionals128 = UInt128(fractionals, 0);
|
||||||
fractionals128.Shift(-exponent - 64);
|
fractionals128.Shift(-exponent - 64);
|
||||||
int point = 128;
|
int point = 128;
|
||||||
@@ -276,7 +276,7 @@ static void FillFractionals(uint64_t fractionals, int exponent,
|
|||||||
fractionals128.Multiply(5);
|
fractionals128.Multiply(5);
|
||||||
point--;
|
point--;
|
||||||
int digit = fractionals128.DivModPowerOf2(point);
|
int digit = fractionals128.DivModPowerOf2(point);
|
||||||
ASSERT(digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(digit <= 9);
|
||||||
buffer[*length] = static_cast<char>('0' + digit);
|
buffer[*length] = static_cast<char>('0' + digit);
|
||||||
(*length)++;
|
(*length)++;
|
||||||
}
|
}
|
||||||
@@ -335,7 +335,7 @@ bool FastFixedDtoa(double v,
|
|||||||
// The quotient delivers the first digits, and the remainder fits into a 64
|
// The quotient delivers the first digits, and the remainder fits into a 64
|
||||||
// bit number.
|
// bit number.
|
||||||
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
|
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
|
||||||
const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
|
const uint64_t kFive17 = DOUBLE_CONVERSION_UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
|
||||||
uint64_t divisor = kFive17;
|
uint64_t divisor = kFive17;
|
||||||
int divisor_power = 17;
|
int divisor_power = 17;
|
||||||
uint64_t dividend = significand;
|
uint64_t dividend = significand;
|
||||||
@@ -383,7 +383,7 @@ bool FastFixedDtoa(double v,
|
|||||||
} else if (exponent < -128) {
|
} else if (exponent < -128) {
|
||||||
// This configuration (with at most 20 digits) means that all digits must be
|
// This configuration (with at most 20 digits) means that all digits must be
|
||||||
// 0.
|
// 0.
|
||||||
ASSERT(fractional_count <= 20);
|
DOUBLE_CONVERSION_ASSERT(fractional_count <= 20);
|
||||||
buffer[0] = '\0';
|
buffer[0] = '\0';
|
||||||
*length = 0;
|
*length = 0;
|
||||||
*decimal_point = -fractional_count;
|
*decimal_point = -fractional_count;
|
||||||
@@ -395,8 +395,8 @@ bool FastFixedDtoa(double v,
|
|||||||
TrimZeros(buffer, length, decimal_point);
|
TrimZeros(buffer, length, decimal_point);
|
||||||
buffer[*length] = '\0';
|
buffer[*length] = '\0';
|
||||||
if ((*length) == 0) {
|
if ((*length) == 0) {
|
||||||
// The string is empty and the decimal_point thus has no importance. Mimick
|
// The string is empty and the decimal_point thus has no importance. Mimic
|
||||||
// Gay's dtoa and and set it to -fractional_count.
|
// Gay's dtoa and set it to -fractional_count.
|
||||||
*decimal_point = -fractional_count;
|
*decimal_point = -fractional_count;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
@@ -41,10 +41,11 @@ static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); }
|
|||||||
// Helper functions for doubles.
|
// Helper functions for doubles.
|
||||||
class Double {
|
class Double {
|
||||||
public:
|
public:
|
||||||
static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
|
static const uint64_t kSignMask = DOUBLE_CONVERSION_UINT64_2PART_C(0x80000000, 00000000);
|
||||||
static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
|
static const uint64_t kExponentMask = DOUBLE_CONVERSION_UINT64_2PART_C(0x7FF00000, 00000000);
|
||||||
static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
|
static const uint64_t kSignificandMask = DOUBLE_CONVERSION_UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
|
||||||
static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
|
static const uint64_t kHiddenBit = DOUBLE_CONVERSION_UINT64_2PART_C(0x00100000, 00000000);
|
||||||
|
static const uint64_t kQuietNanBit = DOUBLE_CONVERSION_UINT64_2PART_C(0x00080000, 00000000);
|
||||||
static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
|
static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
|
||||||
static const int kSignificandSize = 53;
|
static const int kSignificandSize = 53;
|
||||||
static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
|
static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
|
||||||
@@ -59,14 +60,14 @@ class Double {
|
|||||||
// The value encoded by this Double must be greater or equal to +0.0.
|
// The value encoded by this Double must be greater or equal to +0.0.
|
||||||
// It must not be special (infinity, or NaN).
|
// It must not be special (infinity, or NaN).
|
||||||
DiyFp AsDiyFp() const {
|
DiyFp AsDiyFp() const {
|
||||||
ASSERT(Sign() > 0);
|
DOUBLE_CONVERSION_ASSERT(Sign() > 0);
|
||||||
ASSERT(!IsSpecial());
|
DOUBLE_CONVERSION_ASSERT(!IsSpecial());
|
||||||
return DiyFp(Significand(), Exponent());
|
return DiyFp(Significand(), Exponent());
|
||||||
}
|
}
|
||||||
|
|
||||||
// The value encoded by this Double must be strictly greater than 0.
|
// The value encoded by this Double must be strictly greater than 0.
|
||||||
DiyFp AsNormalizedDiyFp() const {
|
DiyFp AsNormalizedDiyFp() const {
|
||||||
ASSERT(value() > 0.0);
|
DOUBLE_CONVERSION_ASSERT(value() > 0.0);
|
||||||
uint64_t f = Significand();
|
uint64_t f = Significand();
|
||||||
int e = Exponent();
|
int e = Exponent();
|
||||||
|
|
||||||
@@ -148,6 +149,23 @@ class Double {
|
|||||||
((d64 & kSignificandMask) != 0);
|
((d64 & kSignificandMask) != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool IsQuietNan() const {
|
||||||
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
return IsNan() && ((AsUint64() & kQuietNanBit) == 0);
|
||||||
|
#else
|
||||||
|
return IsNan() && ((AsUint64() & kQuietNanBit) != 0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsSignalingNan() const {
|
||||||
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
return IsNan() && ((AsUint64() & kQuietNanBit) != 0);
|
||||||
|
#else
|
||||||
|
return IsNan() && ((AsUint64() & kQuietNanBit) == 0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
bool IsInfinite() const {
|
bool IsInfinite() const {
|
||||||
uint64_t d64 = AsUint64();
|
uint64_t d64 = AsUint64();
|
||||||
return ((d64 & kExponentMask) == kExponentMask) &&
|
return ((d64 & kExponentMask) == kExponentMask) &&
|
||||||
@@ -162,7 +180,7 @@ class Double {
|
|||||||
// Precondition: the value encoded by this Double must be greater or equal
|
// Precondition: the value encoded by this Double must be greater or equal
|
||||||
// than +0.0.
|
// than +0.0.
|
||||||
DiyFp UpperBoundary() const {
|
DiyFp UpperBoundary() const {
|
||||||
ASSERT(Sign() > 0);
|
DOUBLE_CONVERSION_ASSERT(Sign() > 0);
|
||||||
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,7 +189,7 @@ class Double {
|
|||||||
// exponent as m_plus.
|
// exponent as m_plus.
|
||||||
// Precondition: the value encoded by this Double must be greater than 0.
|
// Precondition: the value encoded by this Double must be greater than 0.
|
||||||
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
||||||
ASSERT(value() > 0.0);
|
DOUBLE_CONVERSION_ASSERT(value() > 0.0);
|
||||||
DiyFp v = this->AsDiyFp();
|
DiyFp v = this->AsDiyFp();
|
||||||
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
||||||
DiyFp m_minus;
|
DiyFp m_minus;
|
||||||
@@ -225,8 +243,13 @@ class Double {
|
|||||||
|
|
||||||
private:
|
private:
|
||||||
static const int kDenormalExponent = -kExponentBias + 1;
|
static const int kDenormalExponent = -kExponentBias + 1;
|
||||||
static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
|
static const uint64_t kInfinity = DOUBLE_CONVERSION_UINT64_2PART_C(0x7FF00000, 00000000);
|
||||||
static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
static const uint64_t kNaN = DOUBLE_CONVERSION_UINT64_2PART_C(0x7FF7FFFF, FFFFFFFF);
|
||||||
|
#else
|
||||||
|
static const uint64_t kNaN = DOUBLE_CONVERSION_UINT64_2PART_C(0x7FF80000, 00000000);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
const uint64_t d64_;
|
const uint64_t d64_;
|
||||||
|
|
||||||
@@ -257,7 +280,7 @@ class Double {
|
|||||||
(biased_exponent << kPhysicalSignificandSize);
|
(biased_exponent << kPhysicalSignificandSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
DC_DISALLOW_COPY_AND_ASSIGN(Double);
|
DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(Double);
|
||||||
};
|
};
|
||||||
|
|
||||||
class Single {
|
class Single {
|
||||||
@@ -266,6 +289,7 @@ class Single {
|
|||||||
static const uint32_t kExponentMask = 0x7F800000;
|
static const uint32_t kExponentMask = 0x7F800000;
|
||||||
static const uint32_t kSignificandMask = 0x007FFFFF;
|
static const uint32_t kSignificandMask = 0x007FFFFF;
|
||||||
static const uint32_t kHiddenBit = 0x00800000;
|
static const uint32_t kHiddenBit = 0x00800000;
|
||||||
|
static const uint32_t kQuietNanBit = 0x00400000;
|
||||||
static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
|
static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
|
||||||
static const int kSignificandSize = 24;
|
static const int kSignificandSize = 24;
|
||||||
|
|
||||||
@@ -276,8 +300,8 @@ class Single {
|
|||||||
// The value encoded by this Single must be greater or equal to +0.0.
|
// The value encoded by this Single must be greater or equal to +0.0.
|
||||||
// It must not be special (infinity, or NaN).
|
// It must not be special (infinity, or NaN).
|
||||||
DiyFp AsDiyFp() const {
|
DiyFp AsDiyFp() const {
|
||||||
ASSERT(Sign() > 0);
|
DOUBLE_CONVERSION_ASSERT(Sign() > 0);
|
||||||
ASSERT(!IsSpecial());
|
DOUBLE_CONVERSION_ASSERT(!IsSpecial());
|
||||||
return DiyFp(Significand(), Exponent());
|
return DiyFp(Significand(), Exponent());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -324,6 +348,23 @@ class Single {
|
|||||||
((d32 & kSignificandMask) != 0);
|
((d32 & kSignificandMask) != 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool IsQuietNan() const {
|
||||||
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
return IsNan() && ((AsUint32() & kQuietNanBit) == 0);
|
||||||
|
#else
|
||||||
|
return IsNan() && ((AsUint32() & kQuietNanBit) != 0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
bool IsSignalingNan() const {
|
||||||
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
return IsNan() && ((AsUint32() & kQuietNanBit) != 0);
|
||||||
|
#else
|
||||||
|
return IsNan() && ((AsUint32() & kQuietNanBit) == 0);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
bool IsInfinite() const {
|
bool IsInfinite() const {
|
||||||
uint32_t d32 = AsUint32();
|
uint32_t d32 = AsUint32();
|
||||||
return ((d32 & kExponentMask) == kExponentMask) &&
|
return ((d32 & kExponentMask) == kExponentMask) &&
|
||||||
@@ -340,7 +381,7 @@ class Single {
|
|||||||
// exponent as m_plus.
|
// exponent as m_plus.
|
||||||
// Precondition: the value encoded by this Single must be greater than 0.
|
// Precondition: the value encoded by this Single must be greater than 0.
|
||||||
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
||||||
ASSERT(value() > 0.0);
|
DOUBLE_CONVERSION_ASSERT(value() > 0.0);
|
||||||
DiyFp v = this->AsDiyFp();
|
DiyFp v = this->AsDiyFp();
|
||||||
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
||||||
DiyFp m_minus;
|
DiyFp m_minus;
|
||||||
@@ -358,7 +399,7 @@ class Single {
|
|||||||
// Precondition: the value encoded by this Single must be greater or equal
|
// Precondition: the value encoded by this Single must be greater or equal
|
||||||
// than +0.0.
|
// than +0.0.
|
||||||
DiyFp UpperBoundary() const {
|
DiyFp UpperBoundary() const {
|
||||||
ASSERT(Sign() > 0);
|
DOUBLE_CONVERSION_ASSERT(Sign() > 0);
|
||||||
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -390,11 +431,15 @@ class Single {
|
|||||||
static const int kDenormalExponent = -kExponentBias + 1;
|
static const int kDenormalExponent = -kExponentBias + 1;
|
||||||
static const int kMaxExponent = 0xFF - kExponentBias;
|
static const int kMaxExponent = 0xFF - kExponentBias;
|
||||||
static const uint32_t kInfinity = 0x7F800000;
|
static const uint32_t kInfinity = 0x7F800000;
|
||||||
|
#if (defined(__mips__) && !defined(__mips_nan2008)) || defined(__hppa__)
|
||||||
|
static const uint32_t kNaN = 0x7FBFFFFF;
|
||||||
|
#else
|
||||||
static const uint32_t kNaN = 0x7FC00000;
|
static const uint32_t kNaN = 0x7FC00000;
|
||||||
|
#endif
|
||||||
|
|
||||||
const uint32_t d32_;
|
const uint32_t d32_;
|
||||||
|
|
||||||
DC_DISALLOW_COPY_AND_ASSIGN(Single);
|
DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(Single);
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
@@ -29,397 +29,25 @@
|
|||||||
#include <locale>
|
#include <locale>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
|
||||||
#include "double-conversion.h"
|
#include "string-to-double.h"
|
||||||
|
|
||||||
#include "bignum-dtoa.h"
|
|
||||||
#include "fast-dtoa.h"
|
|
||||||
#include "fixed-dtoa.h"
|
|
||||||
#include "ieee.h"
|
#include "ieee.h"
|
||||||
#include "strtod.h"
|
#include "strtod.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
namespace double_conversion {
|
#ifdef _MSC_VER
|
||||||
|
# if _MSC_VER >= 1900
|
||||||
const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
|
// Fix MSVC >= 2015 (_MSC_VER == 1900) warning
|
||||||
int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
|
// C4244: 'argument': conversion from 'const uc16' to 'char', possible loss of data
|
||||||
static DoubleToStringConverter converter(flags,
|
// against Advance and friends, when instantiated with **it as char, not uc16.
|
||||||
"Infinity",
|
__pragma(warning(disable: 4244))
|
||||||
"NaN",
|
# endif
|
||||||
'e',
|
# if _MSC_VER <= 1700 // VS2012, see IsDecimalDigitForRadix warning fix, below
|
||||||
-6, 21,
|
# define VS2012_RADIXWARN
|
||||||
6, 0);
|
# endif
|
||||||
return converter;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool DoubleToStringConverter::HandleSpecialValues(
|
|
||||||
double value,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
Double double_inspect(value);
|
|
||||||
if (double_inspect.IsInfinite()) {
|
|
||||||
if (infinity_symbol_ == NULL) return false;
|
|
||||||
if (value < 0) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
}
|
|
||||||
result_builder->AddString(infinity_symbol_);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (double_inspect.IsNan()) {
|
|
||||||
if (nan_symbol_ == NULL) return false;
|
|
||||||
result_builder->AddString(nan_symbol_);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void DoubleToStringConverter::CreateExponentialRepresentation(
|
|
||||||
const char* decimal_digits,
|
|
||||||
int length,
|
|
||||||
int exponent,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
ASSERT(length != 0);
|
|
||||||
result_builder->AddCharacter(decimal_digits[0]);
|
|
||||||
if (length != 1) {
|
|
||||||
result_builder->AddCharacter('.');
|
|
||||||
result_builder->AddSubstring(&decimal_digits[1], length-1);
|
|
||||||
}
|
|
||||||
result_builder->AddCharacter(exponent_character_);
|
|
||||||
if (exponent < 0) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
exponent = -exponent;
|
|
||||||
} else {
|
|
||||||
if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
|
|
||||||
result_builder->AddCharacter('+');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (exponent == 0) {
|
|
||||||
result_builder->AddCharacter('0');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
ASSERT(exponent < 1e4);
|
|
||||||
const int kMaxExponentLength = 5;
|
|
||||||
char buffer[kMaxExponentLength + 1];
|
|
||||||
buffer[kMaxExponentLength] = '\0';
|
|
||||||
int first_char_pos = kMaxExponentLength;
|
|
||||||
while (exponent > 0) {
|
|
||||||
buffer[--first_char_pos] = '0' + (exponent % 10);
|
|
||||||
exponent /= 10;
|
|
||||||
}
|
|
||||||
result_builder->AddSubstring(&buffer[first_char_pos],
|
|
||||||
kMaxExponentLength - first_char_pos);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void DoubleToStringConverter::CreateDecimalRepresentation(
|
|
||||||
const char* decimal_digits,
|
|
||||||
int length,
|
|
||||||
int decimal_point,
|
|
||||||
int digits_after_point,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
// Create a representation that is padded with zeros if needed.
|
|
||||||
if (decimal_point <= 0) {
|
|
||||||
// "0.00000decimal_rep" or "0.000decimal_rep00".
|
|
||||||
result_builder->AddCharacter('0');
|
|
||||||
if (digits_after_point > 0) {
|
|
||||||
result_builder->AddCharacter('.');
|
|
||||||
result_builder->AddPadding('0', -decimal_point);
|
|
||||||
ASSERT(length <= digits_after_point - (-decimal_point));
|
|
||||||
result_builder->AddSubstring(decimal_digits, length);
|
|
||||||
int remaining_digits = digits_after_point - (-decimal_point) - length;
|
|
||||||
result_builder->AddPadding('0', remaining_digits);
|
|
||||||
}
|
|
||||||
} else if (decimal_point >= length) {
|
|
||||||
// "decimal_rep0000.00000" or "decimal_rep.0000".
|
|
||||||
result_builder->AddSubstring(decimal_digits, length);
|
|
||||||
result_builder->AddPadding('0', decimal_point - length);
|
|
||||||
if (digits_after_point > 0) {
|
|
||||||
result_builder->AddCharacter('.');
|
|
||||||
result_builder->AddPadding('0', digits_after_point);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// "decima.l_rep000".
|
|
||||||
ASSERT(digits_after_point > 0);
|
|
||||||
result_builder->AddSubstring(decimal_digits, decimal_point);
|
|
||||||
result_builder->AddCharacter('.');
|
|
||||||
ASSERT(length - decimal_point <= digits_after_point);
|
|
||||||
result_builder->AddSubstring(&decimal_digits[decimal_point],
|
|
||||||
length - decimal_point);
|
|
||||||
int remaining_digits = digits_after_point - (length - decimal_point);
|
|
||||||
result_builder->AddPadding('0', remaining_digits);
|
|
||||||
}
|
|
||||||
if (digits_after_point == 0) {
|
|
||||||
if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
|
|
||||||
result_builder->AddCharacter('.');
|
|
||||||
}
|
|
||||||
if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
|
|
||||||
result_builder->AddCharacter('0');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool DoubleToStringConverter::ToShortestIeeeNumber(
|
|
||||||
double value,
|
|
||||||
StringBuilder* result_builder,
|
|
||||||
DoubleToStringConverter::DtoaMode mode) const {
|
|
||||||
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
|
|
||||||
if (Double(value).IsSpecial()) {
|
|
||||||
return HandleSpecialValues(value, result_builder);
|
|
||||||
}
|
|
||||||
|
|
||||||
int decimal_point;
|
|
||||||
bool sign;
|
|
||||||
const int kDecimalRepCapacity = kBase10MaximalLength + 1;
|
|
||||||
char decimal_rep[kDecimalRepCapacity];
|
|
||||||
int decimal_rep_length;
|
|
||||||
|
|
||||||
DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
|
|
||||||
&sign, &decimal_rep_length, &decimal_point);
|
|
||||||
|
|
||||||
bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
|
|
||||||
if (sign && (value != 0.0 || !unique_zero)) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
}
|
|
||||||
|
|
||||||
int exponent = decimal_point - 1;
|
|
||||||
if ((decimal_in_shortest_low_ <= exponent) &&
|
|
||||||
(exponent < decimal_in_shortest_high_)) {
|
|
||||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
|
|
||||||
decimal_point,
|
|
||||||
Max(0, decimal_rep_length - decimal_point),
|
|
||||||
result_builder);
|
|
||||||
} else {
|
|
||||||
CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
|
|
||||||
result_builder);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool DoubleToStringConverter::ToFixed(double value,
|
|
||||||
int requested_digits,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
ASSERT(kMaxFixedDigitsBeforePoint == 60);
|
|
||||||
const double kFirstNonFixed = 1e60;
|
|
||||||
|
|
||||||
if (Double(value).IsSpecial()) {
|
|
||||||
return HandleSpecialValues(value, result_builder);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
|
|
||||||
if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
|
|
||||||
|
|
||||||
// Find a sufficiently precise decimal representation of n.
|
|
||||||
int decimal_point;
|
|
||||||
bool sign;
|
|
||||||
// Add space for the '\0' byte.
|
|
||||||
const int kDecimalRepCapacity =
|
|
||||||
kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
|
|
||||||
char decimal_rep[kDecimalRepCapacity];
|
|
||||||
int decimal_rep_length;
|
|
||||||
DoubleToAscii(value, FIXED, requested_digits,
|
|
||||||
decimal_rep, kDecimalRepCapacity,
|
|
||||||
&sign, &decimal_rep_length, &decimal_point);
|
|
||||||
|
|
||||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
|
||||||
if (sign && (value != 0.0 || !unique_zero)) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
}
|
|
||||||
|
|
||||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
|
||||||
requested_digits, result_builder);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool DoubleToStringConverter::ToExponential(
|
|
||||||
double value,
|
|
||||||
int requested_digits,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
if (Double(value).IsSpecial()) {
|
|
||||||
return HandleSpecialValues(value, result_builder);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (requested_digits < -1) return false;
|
|
||||||
if (requested_digits > kMaxExponentialDigits) return false;
|
|
||||||
|
|
||||||
int decimal_point;
|
|
||||||
bool sign;
|
|
||||||
// Add space for digit before the decimal point and the '\0' character.
|
|
||||||
const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
|
|
||||||
ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
|
|
||||||
char decimal_rep[kDecimalRepCapacity];
|
|
||||||
#ifndef NDEBUG
|
|
||||||
// Problem: there is an assert in StringBuilder::AddSubstring() that
|
|
||||||
// will pass this buffer to strlen(), and this buffer is not generally
|
|
||||||
// null-terminated.
|
|
||||||
memset(decimal_rep, 0, sizeof(decimal_rep));
|
|
||||||
#endif
|
#endif
|
||||||
int decimal_rep_length;
|
|
||||||
|
|
||||||
if (requested_digits == -1) {
|
|
||||||
DoubleToAscii(value, SHORTEST, 0,
|
|
||||||
decimal_rep, kDecimalRepCapacity,
|
|
||||||
&sign, &decimal_rep_length, &decimal_point);
|
|
||||||
} else {
|
|
||||||
DoubleToAscii(value, PRECISION, requested_digits + 1,
|
|
||||||
decimal_rep, kDecimalRepCapacity,
|
|
||||||
&sign, &decimal_rep_length, &decimal_point);
|
|
||||||
ASSERT(decimal_rep_length <= requested_digits + 1);
|
|
||||||
|
|
||||||
for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
|
|
||||||
decimal_rep[i] = '0';
|
|
||||||
}
|
|
||||||
decimal_rep_length = requested_digits + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
|
||||||
if (sign && (value != 0.0 || !unique_zero)) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
}
|
|
||||||
|
|
||||||
int exponent = decimal_point - 1;
|
|
||||||
CreateExponentialRepresentation(decimal_rep,
|
|
||||||
decimal_rep_length,
|
|
||||||
exponent,
|
|
||||||
result_builder);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
bool DoubleToStringConverter::ToPrecision(double value,
|
|
||||||
int precision,
|
|
||||||
StringBuilder* result_builder) const {
|
|
||||||
if (Double(value).IsSpecial()) {
|
|
||||||
return HandleSpecialValues(value, result_builder);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find a sufficiently precise decimal representation of n.
|
|
||||||
int decimal_point;
|
|
||||||
bool sign;
|
|
||||||
// Add one for the terminating null character.
|
|
||||||
const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
|
|
||||||
char decimal_rep[kDecimalRepCapacity];
|
|
||||||
int decimal_rep_length;
|
|
||||||
|
|
||||||
DoubleToAscii(value, PRECISION, precision,
|
|
||||||
decimal_rep, kDecimalRepCapacity,
|
|
||||||
&sign, &decimal_rep_length, &decimal_point);
|
|
||||||
ASSERT(decimal_rep_length <= precision);
|
|
||||||
|
|
||||||
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
|
||||||
if (sign && (value != 0.0 || !unique_zero)) {
|
|
||||||
result_builder->AddCharacter('-');
|
|
||||||
}
|
|
||||||
|
|
||||||
// The exponent if we print the number as x.xxeyyy. That is with the
|
|
||||||
// decimal point after the first digit.
|
|
||||||
int exponent = decimal_point - 1;
|
|
||||||
|
|
||||||
int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
|
|
||||||
if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
|
|
||||||
(decimal_point - precision + extra_zero >
|
|
||||||
max_trailing_padding_zeroes_in_precision_mode_)) {
|
|
||||||
// Fill buffer to contain 'precision' digits.
|
|
||||||
// Usually the buffer is already at the correct length, but 'DoubleToAscii'
|
|
||||||
// is allowed to return less characters.
|
|
||||||
for (int i = decimal_rep_length; i < precision; ++i) {
|
|
||||||
decimal_rep[i] = '0';
|
|
||||||
}
|
|
||||||
|
|
||||||
CreateExponentialRepresentation(decimal_rep,
|
|
||||||
precision,
|
|
||||||
exponent,
|
|
||||||
result_builder);
|
|
||||||
} else {
|
|
||||||
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
|
||||||
Max(0, precision - decimal_point),
|
|
||||||
result_builder);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static BignumDtoaMode DtoaToBignumDtoaMode(
|
|
||||||
DoubleToStringConverter::DtoaMode dtoa_mode) {
|
|
||||||
switch (dtoa_mode) {
|
|
||||||
case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
|
|
||||||
case DoubleToStringConverter::SHORTEST_SINGLE:
|
|
||||||
return BIGNUM_DTOA_SHORTEST_SINGLE;
|
|
||||||
case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
|
|
||||||
case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
|
|
||||||
default:
|
|
||||||
UNREACHABLE();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void DoubleToStringConverter::DoubleToAscii(double v,
|
|
||||||
DtoaMode mode,
|
|
||||||
int requested_digits,
|
|
||||||
char* buffer,
|
|
||||||
int buffer_length,
|
|
||||||
bool* sign,
|
|
||||||
int* length,
|
|
||||||
int* point) {
|
|
||||||
Vector<char> vector(buffer, buffer_length);
|
|
||||||
ASSERT(!Double(v).IsSpecial());
|
|
||||||
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
|
|
||||||
|
|
||||||
if (Double(v).Sign() < 0) {
|
|
||||||
*sign = true;
|
|
||||||
v = -v;
|
|
||||||
} else {
|
|
||||||
*sign = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (mode == PRECISION && requested_digits == 0) {
|
|
||||||
vector[0] = '\0';
|
|
||||||
*length = 0;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (v == 0) {
|
|
||||||
vector[0] = '0';
|
|
||||||
vector[1] = '\0';
|
|
||||||
*length = 1;
|
|
||||||
*point = 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool fast_worked;
|
|
||||||
switch (mode) {
|
|
||||||
case SHORTEST:
|
|
||||||
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
|
|
||||||
break;
|
|
||||||
case SHORTEST_SINGLE:
|
|
||||||
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
|
|
||||||
vector, length, point);
|
|
||||||
break;
|
|
||||||
case FIXED:
|
|
||||||
fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
|
|
||||||
break;
|
|
||||||
case PRECISION:
|
|
||||||
fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
|
|
||||||
vector, length, point);
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
fast_worked = false;
|
|
||||||
UNREACHABLE();
|
|
||||||
}
|
|
||||||
if (fast_worked) return;
|
|
||||||
|
|
||||||
// If the fast dtoa didn't succeed use the slower bignum version.
|
|
||||||
BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
|
|
||||||
BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
|
|
||||||
vector[*length] = '\0';
|
|
||||||
}
|
|
||||||
|
|
||||||
|
namespace double_conversion {
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
@@ -438,7 +66,7 @@ static inline bool ConsumeSubStringImpl(Iterator* current,
|
|||||||
Iterator end,
|
Iterator end,
|
||||||
const char* substring,
|
const char* substring,
|
||||||
Converter converter) {
|
Converter converter) {
|
||||||
ASSERT(converter(**current) == *substring);
|
DOUBLE_CONVERSION_ASSERT(converter(**current) == *substring);
|
||||||
for (substring++; *substring != '\0'; substring++) {
|
for (substring++; *substring != '\0'; substring++) {
|
||||||
++*current;
|
++*current;
|
||||||
if (*current == end || converter(**current) != *substring) {
|
if (*current == end || converter(**current) != *substring) {
|
||||||
@@ -455,8 +83,8 @@ template <class Iterator>
|
|||||||
static bool ConsumeSubString(Iterator* current,
|
static bool ConsumeSubString(Iterator* current,
|
||||||
Iterator end,
|
Iterator end,
|
||||||
const char* substring,
|
const char* substring,
|
||||||
bool allow_case_insensibility) {
|
bool allow_case_insensitivity) {
|
||||||
if (allow_case_insensibility) {
|
if (allow_case_insensitivity) {
|
||||||
return ConsumeSubStringImpl(current, end, substring, ToLower);
|
return ConsumeSubStringImpl(current, end, substring, ToLower);
|
||||||
} else {
|
} else {
|
||||||
return ConsumeSubStringImpl(current, end, substring, Pass);
|
return ConsumeSubStringImpl(current, end, substring, Pass);
|
||||||
@@ -466,8 +94,8 @@ static bool ConsumeSubString(Iterator* current,
|
|||||||
// Consumes first character of the str is equal to ch
|
// Consumes first character of the str is equal to ch
|
||||||
inline bool ConsumeFirstCharacter(char ch,
|
inline bool ConsumeFirstCharacter(char ch,
|
||||||
const char* str,
|
const char* str,
|
||||||
bool case_insensibility) {
|
bool case_insensitivity) {
|
||||||
return case_insensibility ? ToLower(ch) == str[0] : ch == str[0];
|
return case_insensitivity ? ToLower(ch) == str[0] : ch == str[0];
|
||||||
}
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
@@ -482,14 +110,14 @@ const int kMaxSignificantDigits = 772;
|
|||||||
|
|
||||||
|
|
||||||
static const char kWhitespaceTable7[] = { 32, 13, 10, 9, 11, 12 };
|
static const char kWhitespaceTable7[] = { 32, 13, 10, 9, 11, 12 };
|
||||||
static const int kWhitespaceTable7Length = ARRAY_SIZE(kWhitespaceTable7);
|
static const int kWhitespaceTable7Length = DOUBLE_CONVERSION_ARRAY_SIZE(kWhitespaceTable7);
|
||||||
|
|
||||||
|
|
||||||
static const uc16 kWhitespaceTable16[] = {
|
static const uc16 kWhitespaceTable16[] = {
|
||||||
160, 8232, 8233, 5760, 6158, 8192, 8193, 8194, 8195,
|
160, 8232, 8233, 5760, 6158, 8192, 8193, 8194, 8195,
|
||||||
8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279
|
8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279
|
||||||
};
|
};
|
||||||
static const int kWhitespaceTable16Length = ARRAY_SIZE(kWhitespaceTable16);
|
static const int kWhitespaceTable16Length = DOUBLE_CONVERSION_ARRAY_SIZE(kWhitespaceTable16);
|
||||||
|
|
||||||
|
|
||||||
static bool isWhitespace(int x) {
|
static bool isWhitespace(int x) {
|
||||||
@@ -533,9 +161,9 @@ static double SignedZero(bool sign) {
|
|||||||
//
|
//
|
||||||
// The function is small and could be inlined, but VS2012 emitted a warning
|
// The function is small and could be inlined, but VS2012 emitted a warning
|
||||||
// because it constant-propagated the radix and concluded that the last
|
// because it constant-propagated the radix and concluded that the last
|
||||||
// condition was always true. By moving it into a separate function the
|
// condition was always true. Moving it into a separate function and
|
||||||
// compiler wouldn't warn anymore.
|
// suppressing optimisation keeps the compiler from warning.
|
||||||
#ifdef _MSC_VER
|
#ifdef VS2012_RADIXWARN
|
||||||
#pragma optimize("",off)
|
#pragma optimize("",off)
|
||||||
static bool IsDecimalDigitForRadix(int c, int radix) {
|
static bool IsDecimalDigitForRadix(int c, int radix) {
|
||||||
return '0' <= c && c <= '9' && (c - '0') < radix;
|
return '0' <= c && c <= '9' && (c - '0') < radix;
|
||||||
@@ -589,7 +217,7 @@ static bool IsHexFloatString(Iterator start,
|
|||||||
Iterator end,
|
Iterator end,
|
||||||
uc16 separator,
|
uc16 separator,
|
||||||
bool allow_trailing_junk) {
|
bool allow_trailing_junk) {
|
||||||
ASSERT(start != end);
|
DOUBLE_CONVERSION_ASSERT(start != end);
|
||||||
|
|
||||||
Iterator current = start;
|
Iterator current = start;
|
||||||
|
|
||||||
@@ -634,8 +262,8 @@ static double RadixStringToIeee(Iterator* current,
|
|||||||
double junk_string_value,
|
double junk_string_value,
|
||||||
bool read_as_double,
|
bool read_as_double,
|
||||||
bool* result_is_junk) {
|
bool* result_is_junk) {
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
ASSERT(!parse_as_hex_float ||
|
DOUBLE_CONVERSION_ASSERT(!parse_as_hex_float ||
|
||||||
IsHexFloatString(*current, end, separator, allow_trailing_junk));
|
IsHexFloatString(*current, end, separator, allow_trailing_junk));
|
||||||
|
|
||||||
const int kDoubleSize = Double::kSignificandSize;
|
const int kDoubleSize = Double::kSignificandSize;
|
||||||
@@ -673,7 +301,7 @@ static double RadixStringToIeee(Iterator* current,
|
|||||||
} else if (parse_as_hex_float && **current == '.') {
|
} else if (parse_as_hex_float && **current == '.') {
|
||||||
post_decimal = true;
|
post_decimal = true;
|
||||||
Advance(current, separator, radix, end);
|
Advance(current, separator, radix, end);
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
continue;
|
continue;
|
||||||
} else if (parse_as_hex_float && (**current == 'p' || **current == 'P')) {
|
} else if (parse_as_hex_float && (**current == 'p' || **current == 'P')) {
|
||||||
break;
|
break;
|
||||||
@@ -708,7 +336,7 @@ static double RadixStringToIeee(Iterator* current,
|
|||||||
// Just run over the '.'. We are just trying to see whether there is
|
// Just run over the '.'. We are just trying to see whether there is
|
||||||
// a non-zero digit somewhere.
|
// a non-zero digit somewhere.
|
||||||
Advance(current, separator, radix, end);
|
Advance(current, separator, radix, end);
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
post_decimal = true;
|
post_decimal = true;
|
||||||
}
|
}
|
||||||
if (!isDigit(**current, radix)) break;
|
if (!isDigit(**current, radix)) break;
|
||||||
@@ -743,23 +371,23 @@ static double RadixStringToIeee(Iterator* current,
|
|||||||
if (Advance(current, separator, radix, end)) break;
|
if (Advance(current, separator, radix, end)) break;
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(number < ((int64_t)1 << kSignificandSize));
|
DOUBLE_CONVERSION_ASSERT(number < ((int64_t)1 << kSignificandSize));
|
||||||
ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
|
DOUBLE_CONVERSION_ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
|
||||||
|
|
||||||
*result_is_junk = false;
|
*result_is_junk = false;
|
||||||
|
|
||||||
if (parse_as_hex_float) {
|
if (parse_as_hex_float) {
|
||||||
ASSERT(**current == 'p' || **current == 'P');
|
DOUBLE_CONVERSION_ASSERT(**current == 'p' || **current == 'P');
|
||||||
Advance(current, separator, radix, end);
|
Advance(current, separator, radix, end);
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
bool is_negative = false;
|
bool is_negative = false;
|
||||||
if (**current == '+') {
|
if (**current == '+') {
|
||||||
Advance(current, separator, radix, end);
|
Advance(current, separator, radix, end);
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
} else if (**current == '-') {
|
} else if (**current == '-') {
|
||||||
is_negative = true;
|
is_negative = true;
|
||||||
Advance(current, separator, radix, end);
|
Advance(current, separator, radix, end);
|
||||||
ASSERT(*current != end);
|
DOUBLE_CONVERSION_ASSERT(*current != end);
|
||||||
}
|
}
|
||||||
int written_exponent = 0;
|
int written_exponent = 0;
|
||||||
while (IsDecimalDigitForRadix(**current, 10)) {
|
while (IsDecimalDigitForRadix(**current, 10)) {
|
||||||
@@ -782,7 +410,7 @@ static double RadixStringToIeee(Iterator* current,
|
|||||||
return static_cast<double>(number);
|
return static_cast<double>(number);
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(number != 0);
|
DOUBLE_CONVERSION_ASSERT(number != 0);
|
||||||
double result = Double(DiyFp(number, exponent)).value();
|
double result = Double(DiyFp(number, exponent)).value();
|
||||||
return sign ? -result : result;
|
return sign ? -result : result;
|
||||||
}
|
}
|
||||||
@@ -802,7 +430,7 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
|
const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
|
||||||
const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
|
const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
|
||||||
const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
|
const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
|
||||||
const bool allow_case_insensibility = (flags_ & ALLOW_CASE_INSENSIBILITY) != 0;
|
const bool allow_case_insensitivity = (flags_ & ALLOW_CASE_INSENSITIVITY) != 0;
|
||||||
|
|
||||||
// To make sure that iterator dereferencing is valid the following
|
// To make sure that iterator dereferencing is valid the following
|
||||||
// convention is used:
|
// convention is used:
|
||||||
@@ -825,11 +453,6 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
|
|
||||||
const int kBufferSize = kMaxSignificantDigits + 10;
|
|
||||||
char buffer[kBufferSize]; // NOLINT: size is known at compile time.
|
|
||||||
int buffer_pos = 0;
|
|
||||||
|
|
||||||
// Exponent will be adjusted if insignificant digits of the integer part
|
// Exponent will be adjusted if insignificant digits of the integer part
|
||||||
// or insignificant leading zeros of the fractional part are dropped.
|
// or insignificant leading zeros of the fractional part are dropped.
|
||||||
int exponent = 0;
|
int exponent = 0;
|
||||||
@@ -852,8 +475,8 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (infinity_symbol_ != NULL) {
|
if (infinity_symbol_ != NULL) {
|
||||||
if (ConsumeFirstCharacter(*current, infinity_symbol_, allow_case_insensibility)) {
|
if (ConsumeFirstCharacter(*current, infinity_symbol_, allow_case_insensitivity)) {
|
||||||
if (!ConsumeSubString(¤t, end, infinity_symbol_, allow_case_insensibility)) {
|
if (!ConsumeSubString(¤t, end, infinity_symbol_, allow_case_insensitivity)) {
|
||||||
return junk_string_value_;
|
return junk_string_value_;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -864,15 +487,14 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
return junk_string_value_;
|
return junk_string_value_;
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(buffer_pos == 0);
|
|
||||||
*processed_characters_count = static_cast<int>(current - input);
|
*processed_characters_count = static_cast<int>(current - input);
|
||||||
return sign ? -Double::Infinity() : Double::Infinity();
|
return sign ? -Double::Infinity() : Double::Infinity();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (nan_symbol_ != NULL) {
|
if (nan_symbol_ != NULL) {
|
||||||
if (ConsumeFirstCharacter(*current, nan_symbol_, allow_case_insensibility)) {
|
if (ConsumeFirstCharacter(*current, nan_symbol_, allow_case_insensitivity)) {
|
||||||
if (!ConsumeSubString(¤t, end, nan_symbol_, allow_case_insensibility)) {
|
if (!ConsumeSubString(¤t, end, nan_symbol_, allow_case_insensitivity)) {
|
||||||
return junk_string_value_;
|
return junk_string_value_;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -883,7 +505,6 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
return junk_string_value_;
|
return junk_string_value_;
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(buffer_pos == 0);
|
|
||||||
*processed_characters_count = static_cast<int>(current - input);
|
*processed_characters_count = static_cast<int>(current - input);
|
||||||
return sign ? -Double::NaN() : Double::NaN();
|
return sign ? -Double::NaN() : Double::NaN();
|
||||||
}
|
}
|
||||||
@@ -940,10 +561,16 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
|
|
||||||
bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
|
bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
|
||||||
|
|
||||||
|
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
|
||||||
|
const int kBufferSize = kMaxSignificantDigits + 10;
|
||||||
|
DOUBLE_CONVERSION_STACK_UNINITIALIZED char
|
||||||
|
buffer[kBufferSize]; // NOLINT: size is known at compile time.
|
||||||
|
int buffer_pos = 0;
|
||||||
|
|
||||||
// Copy significant digits of the integer part (if any) to the buffer.
|
// Copy significant digits of the integer part (if any) to the buffer.
|
||||||
while (*current >= '0' && *current <= '9') {
|
while (*current >= '0' && *current <= '9') {
|
||||||
if (significant_digits < kMaxSignificantDigits) {
|
if (significant_digits < kMaxSignificantDigits) {
|
||||||
ASSERT(buffer_pos < kBufferSize);
|
DOUBLE_CONVERSION_ASSERT(buffer_pos < kBufferSize);
|
||||||
buffer[buffer_pos++] = static_cast<char>(*current);
|
buffer[buffer_pos++] = static_cast<char>(*current);
|
||||||
significant_digits++;
|
significant_digits++;
|
||||||
// Will later check if it's an octal in the buffer.
|
// Will later check if it's an octal in the buffer.
|
||||||
@@ -988,7 +615,7 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
// We don't emit a '.', but adjust the exponent instead.
|
// We don't emit a '.', but adjust the exponent instead.
|
||||||
while (*current >= '0' && *current <= '9') {
|
while (*current >= '0' && *current <= '9') {
|
||||||
if (significant_digits < kMaxSignificantDigits) {
|
if (significant_digits < kMaxSignificantDigits) {
|
||||||
ASSERT(buffer_pos < kBufferSize);
|
DOUBLE_CONVERSION_ASSERT(buffer_pos < kBufferSize);
|
||||||
buffer[buffer_pos++] = static_cast<char>(*current);
|
buffer[buffer_pos++] = static_cast<char>(*current);
|
||||||
significant_digits++;
|
significant_digits++;
|
||||||
exponent--;
|
exponent--;
|
||||||
@@ -1046,7 +673,7 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const int max_exponent = INT_MAX / 2;
|
const int max_exponent = INT_MAX / 2;
|
||||||
ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
|
DOUBLE_CONVERSION_ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
|
||||||
int num = 0;
|
int num = 0;
|
||||||
do {
|
do {
|
||||||
// Check overflow.
|
// Check overflow.
|
||||||
@@ -1089,7 +716,7 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
junk_string_value_,
|
junk_string_value_,
|
||||||
read_as_double,
|
read_as_double,
|
||||||
&result_is_junk);
|
&result_is_junk);
|
||||||
ASSERT(!result_is_junk);
|
DOUBLE_CONVERSION_ASSERT(!result_is_junk);
|
||||||
*processed_characters_count = static_cast<int>(current - input);
|
*processed_characters_count = static_cast<int>(current - input);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -1099,14 +726,20 @@ double StringToDoubleConverter::StringToIeee(
|
|||||||
exponent--;
|
exponent--;
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT(buffer_pos < kBufferSize);
|
DOUBLE_CONVERSION_ASSERT(buffer_pos < kBufferSize);
|
||||||
buffer[buffer_pos] = '\0';
|
buffer[buffer_pos] = '\0';
|
||||||
|
|
||||||
|
// Code above ensures there are no leading zeros and the buffer has fewer than
|
||||||
|
// kMaxSignificantDecimalDigits characters. Trim trailing zeros.
|
||||||
|
Vector<const char> chars(buffer, buffer_pos);
|
||||||
|
chars = TrimTrailingZeros(chars);
|
||||||
|
exponent += buffer_pos - chars.length();
|
||||||
|
|
||||||
double converted;
|
double converted;
|
||||||
if (read_as_double) {
|
if (read_as_double) {
|
||||||
converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
|
converted = StrtodTrimmed(chars, exponent);
|
||||||
} else {
|
} else {
|
||||||
converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
|
converted = StrtofTrimmed(chars, exponent);
|
||||||
}
|
}
|
||||||
*processed_characters_count = static_cast<int>(current - input);
|
*processed_characters_count = static_cast<int>(current - input);
|
||||||
return sign? -converted: converted;
|
return sign? -converted: converted;
|
||||||
@@ -1146,4 +779,40 @@ float StringToDoubleConverter::StringToFloat(
|
|||||||
processed_characters_count));
|
processed_characters_count));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template<>
|
||||||
|
double StringToDoubleConverter::StringTo<double>(
|
||||||
|
const char* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const {
|
||||||
|
return StringToDouble(buffer, length, processed_characters_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template<>
|
||||||
|
float StringToDoubleConverter::StringTo<float>(
|
||||||
|
const char* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const {
|
||||||
|
return StringToFloat(buffer, length, processed_characters_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template<>
|
||||||
|
double StringToDoubleConverter::StringTo<double>(
|
||||||
|
const uc16* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const {
|
||||||
|
return StringToDouble(buffer, length, processed_characters_count);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template<>
|
||||||
|
float StringToDoubleConverter::StringTo<float>(
|
||||||
|
const uc16* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const {
|
||||||
|
return StringToFloat(buffer, length, processed_characters_count);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
238
Foundation/src/string-to-double.h
Normal file
238
Foundation/src/string-to-double.h
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
// Copyright 2012 the V8 project authors. All rights reserved.
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// * Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
// * Redistributions in binary form must reproduce the above
|
||||||
|
// copyright notice, this list of conditions and the following
|
||||||
|
// disclaimer in the documentation and/or other materials provided
|
||||||
|
// with the distribution.
|
||||||
|
// * Neither the name of Google Inc. nor the names of its
|
||||||
|
// contributors may be used to endorse or promote products derived
|
||||||
|
// from this software without specific prior written permission.
|
||||||
|
//
|
||||||
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||||
|
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||||
|
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||||
|
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||||
|
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||||
|
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||||
|
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
#ifndef DOUBLE_CONVERSION_STRING_TO_DOUBLE_H_
|
||||||
|
#define DOUBLE_CONVERSION_STRING_TO_DOUBLE_H_
|
||||||
|
|
||||||
|
#include "utils.h"
|
||||||
|
|
||||||
|
namespace double_conversion {
|
||||||
|
|
||||||
|
class StringToDoubleConverter {
|
||||||
|
public:
|
||||||
|
// Enumeration for allowing octals and ignoring junk when converting
|
||||||
|
// strings to numbers.
|
||||||
|
enum Flags {
|
||||||
|
NO_FLAGS = 0,
|
||||||
|
ALLOW_HEX = 1,
|
||||||
|
ALLOW_OCTALS = 2,
|
||||||
|
ALLOW_TRAILING_JUNK = 4,
|
||||||
|
ALLOW_LEADING_SPACES = 8,
|
||||||
|
ALLOW_TRAILING_SPACES = 16,
|
||||||
|
ALLOW_SPACES_AFTER_SIGN = 32,
|
||||||
|
ALLOW_CASE_INSENSITIVITY = 64,
|
||||||
|
ALLOW_CASE_INSENSIBILITY = 64, // Deprecated
|
||||||
|
ALLOW_HEX_FLOATS = 128,
|
||||||
|
};
|
||||||
|
|
||||||
|
static const uc16 kNoSeparator = '\0';
|
||||||
|
|
||||||
|
// Flags should be a bit-or combination of the possible Flags-enum.
|
||||||
|
// - NO_FLAGS: no special flags.
|
||||||
|
// - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
|
||||||
|
// Ex: StringToDouble("0x1234") -> 4660.0
|
||||||
|
// In StringToDouble("0x1234.56") the characters ".56" are trailing
|
||||||
|
// junk. The result of the call is hence dependent on
|
||||||
|
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
||||||
|
// With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
|
||||||
|
// the string will not be parsed as "0" followed by junk.
|
||||||
|
//
|
||||||
|
// - ALLOW_OCTALS: recognizes the prefix "0" for octals:
|
||||||
|
// If a sequence of octal digits starts with '0', then the number is
|
||||||
|
// read as octal integer. Octal numbers may only be integers.
|
||||||
|
// Ex: StringToDouble("01234") -> 668.0
|
||||||
|
// StringToDouble("012349") -> 12349.0 // Not a sequence of octal
|
||||||
|
// // digits.
|
||||||
|
// In StringToDouble("01234.56") the characters ".56" are trailing
|
||||||
|
// junk. The result of the call is hence dependent on
|
||||||
|
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
||||||
|
// In StringToDouble("01234e56") the characters "e56" are trailing
|
||||||
|
// junk, too.
|
||||||
|
// - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
|
||||||
|
// a double literal.
|
||||||
|
// - ALLOW_LEADING_SPACES: skip over leading whitespace, including spaces,
|
||||||
|
// new-lines, and tabs.
|
||||||
|
// - ALLOW_TRAILING_SPACES: ignore trailing whitespace.
|
||||||
|
// - ALLOW_SPACES_AFTER_SIGN: ignore whitespace after the sign.
|
||||||
|
// Ex: StringToDouble("- 123.2") -> -123.2.
|
||||||
|
// StringToDouble("+ 123.2") -> 123.2
|
||||||
|
// - ALLOW_CASE_INSENSITIVITY: ignore case of characters for special values:
|
||||||
|
// infinity and nan.
|
||||||
|
// - ALLOW_HEX_FLOATS: allows hexadecimal float literals.
|
||||||
|
// This *must* start with "0x" and separate the exponent with "p".
|
||||||
|
// Examples: 0x1.2p3 == 9.0
|
||||||
|
// 0x10.1p0 == 16.0625
|
||||||
|
// ALLOW_HEX and ALLOW_HEX_FLOATS are indented.
|
||||||
|
//
|
||||||
|
// empty_string_value is returned when an empty string is given as input.
|
||||||
|
// If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
|
||||||
|
// containing only spaces is converted to the 'empty_string_value', too.
|
||||||
|
//
|
||||||
|
// junk_string_value is returned when
|
||||||
|
// a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
|
||||||
|
// part of a double-literal) is found.
|
||||||
|
// b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
|
||||||
|
// double literal.
|
||||||
|
//
|
||||||
|
// infinity_symbol and nan_symbol are strings that are used to detect
|
||||||
|
// inputs that represent infinity and NaN. They can be null, in which case
|
||||||
|
// they are ignored.
|
||||||
|
// The conversion routine first reads any possible signs. Then it compares the
|
||||||
|
// following character of the input-string with the first character of
|
||||||
|
// the infinity, and nan-symbol. If either matches, the function assumes, that
|
||||||
|
// a match has been found, and expects the following input characters to match
|
||||||
|
// the remaining characters of the special-value symbol.
|
||||||
|
// This means that the following restrictions apply to special-value symbols:
|
||||||
|
// - they must not start with signs ('+', or '-'),
|
||||||
|
// - they must not have the same first character.
|
||||||
|
// - they must not start with digits.
|
||||||
|
//
|
||||||
|
// If the separator character is not kNoSeparator, then that specific
|
||||||
|
// character is ignored when in between two valid digits of the significant.
|
||||||
|
// It is not allowed to appear in the exponent.
|
||||||
|
// It is not allowed to lead or trail the number.
|
||||||
|
// It is not allowed to appear twice next to each other.
|
||||||
|
//
|
||||||
|
// Examples:
|
||||||
|
// flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
|
||||||
|
// empty_string_value = 0.0,
|
||||||
|
// junk_string_value = NaN,
|
||||||
|
// infinity_symbol = "infinity",
|
||||||
|
// nan_symbol = "nan":
|
||||||
|
// StringToDouble("0x1234") -> 4660.0.
|
||||||
|
// StringToDouble("0x1234K") -> 4660.0.
|
||||||
|
// StringToDouble("") -> 0.0 // empty_string_value.
|
||||||
|
// StringToDouble(" ") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble(" 1") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("0x") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("-123.45") -> -123.45.
|
||||||
|
// StringToDouble("--123.45") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("123e45") -> 123e45.
|
||||||
|
// StringToDouble("123E45") -> 123e45.
|
||||||
|
// StringToDouble("123e+45") -> 123e45.
|
||||||
|
// StringToDouble("123E-45") -> 123e-45.
|
||||||
|
// StringToDouble("123e") -> 123.0 // trailing junk ignored.
|
||||||
|
// StringToDouble("123e-") -> 123.0 // trailing junk ignored.
|
||||||
|
// StringToDouble("+NaN") -> NaN // NaN string literal.
|
||||||
|
// StringToDouble("-infinity") -> -inf. // infinity literal.
|
||||||
|
// StringToDouble("Infinity") -> NaN // junk_string_value.
|
||||||
|
//
|
||||||
|
// flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
|
||||||
|
// empty_string_value = 0.0,
|
||||||
|
// junk_string_value = NaN,
|
||||||
|
// infinity_symbol = NULL,
|
||||||
|
// nan_symbol = NULL:
|
||||||
|
// StringToDouble("0x1234") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("01234") -> 668.0.
|
||||||
|
// StringToDouble("") -> 0.0 // empty_string_value.
|
||||||
|
// StringToDouble(" ") -> 0.0 // empty_string_value.
|
||||||
|
// StringToDouble(" 1") -> 1.0
|
||||||
|
// StringToDouble("0x") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("0123e45") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("01239E45") -> 1239e45.
|
||||||
|
// StringToDouble("-infinity") -> NaN // junk_string_value.
|
||||||
|
// StringToDouble("NaN") -> NaN // junk_string_value.
|
||||||
|
//
|
||||||
|
// flags = NO_FLAGS,
|
||||||
|
// separator = ' ':
|
||||||
|
// StringToDouble("1 2 3 4") -> 1234.0
|
||||||
|
// StringToDouble("1 2") -> NaN // junk_string_value
|
||||||
|
// StringToDouble("1 000 000.0") -> 1000000.0
|
||||||
|
// StringToDouble("1.000 000") -> 1.0
|
||||||
|
// StringToDouble("1.0e1 000") -> NaN // junk_string_value
|
||||||
|
StringToDoubleConverter(int flags,
|
||||||
|
double empty_string_value,
|
||||||
|
double junk_string_value,
|
||||||
|
const char* infinity_symbol,
|
||||||
|
const char* nan_symbol,
|
||||||
|
uc16 separator = kNoSeparator)
|
||||||
|
: flags_(flags),
|
||||||
|
empty_string_value_(empty_string_value),
|
||||||
|
junk_string_value_(junk_string_value),
|
||||||
|
infinity_symbol_(infinity_symbol),
|
||||||
|
nan_symbol_(nan_symbol),
|
||||||
|
separator_(separator) {
|
||||||
|
}
|
||||||
|
|
||||||
|
// Performs the conversion.
|
||||||
|
// The output parameter 'processed_characters_count' is set to the number
|
||||||
|
// of characters that have been processed to read the number.
|
||||||
|
// Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
|
||||||
|
// in the 'processed_characters_count'. Trailing junk is never included.
|
||||||
|
double StringToDouble(const char* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
// Same as StringToDouble above but for 16 bit characters.
|
||||||
|
double StringToDouble(const uc16* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
// Same as StringToDouble but reads a float.
|
||||||
|
// Note that this is not equivalent to static_cast<float>(StringToDouble(...))
|
||||||
|
// due to potential double-rounding.
|
||||||
|
float StringToFloat(const char* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
// Same as StringToFloat above but for 16 bit characters.
|
||||||
|
float StringToFloat(const uc16* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
// Same as StringToDouble for T = double, and StringToFloat for T = float.
|
||||||
|
template <typename T>
|
||||||
|
T StringTo(const char* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
// Same as StringTo above but for 16 bit characters.
|
||||||
|
template <typename T>
|
||||||
|
T StringTo(const uc16* buffer,
|
||||||
|
int length,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
const int flags_;
|
||||||
|
const double empty_string_value_;
|
||||||
|
const double junk_string_value_;
|
||||||
|
const char* const infinity_symbol_;
|
||||||
|
const char* const nan_symbol_;
|
||||||
|
const uc16 separator_;
|
||||||
|
|
||||||
|
template <class Iterator>
|
||||||
|
double StringToIeee(Iterator start_pointer,
|
||||||
|
int length,
|
||||||
|
bool read_as_double,
|
||||||
|
int* processed_characters_count) const;
|
||||||
|
|
||||||
|
DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace double_conversion
|
||||||
|
|
||||||
|
#endif // DOUBLE_CONVERSION_STRING_TO_DOUBLE_H_
|
@@ -35,10 +35,12 @@
|
|||||||
|
|
||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
|
#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||||
// 2^53 = 9007199254740992.
|
// 2^53 = 9007199254740992.
|
||||||
// Any integer with at most 15 decimal digits will hence fit into a double
|
// Any integer with at most 15 decimal digits will hence fit into a double
|
||||||
// (which has a 53bit significand) without loss of precision.
|
// (which has a 53bit significand) without loss of precision.
|
||||||
static const int kMaxExactDoubleIntegerDecimalDigits = 15;
|
static const int kMaxExactDoubleIntegerDecimalDigits = 15;
|
||||||
|
#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||||
// 2^64 = 18446744073709551616 > 10^19
|
// 2^64 = 18446744073709551616 > 10^19
|
||||||
static const int kMaxUint64DecimalDigits = 19;
|
static const int kMaxUint64DecimalDigits = 19;
|
||||||
|
|
||||||
@@ -52,9 +54,10 @@ static const int kMaxDecimalPower = 309;
|
|||||||
static const int kMinDecimalPower = -324;
|
static const int kMinDecimalPower = -324;
|
||||||
|
|
||||||
// 2^64 = 18446744073709551616
|
// 2^64 = 18446744073709551616
|
||||||
static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
|
static const uint64_t kMaxUint64 = DOUBLE_CONVERSION_UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||||
static const double exact_powers_of_ten[] = {
|
static const double exact_powers_of_ten[] = {
|
||||||
1.0, // 10^0
|
1.0, // 10^0
|
||||||
10.0,
|
10.0,
|
||||||
@@ -81,7 +84,8 @@ static const double exact_powers_of_ten[] = {
|
|||||||
// 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
|
// 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
|
||||||
10000000000000000000000.0
|
10000000000000000000000.0
|
||||||
};
|
};
|
||||||
static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
|
static const int kExactPowersOfTenSize = DOUBLE_CONVERSION_ARRAY_SIZE(exact_powers_of_ten);
|
||||||
|
#endif // #if defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||||
|
|
||||||
// Maximum number of significant digits in the decimal representation.
|
// Maximum number of significant digits in the decimal representation.
|
||||||
// In fact the value is 772 (see conversions.cc), but to give us some margin
|
// In fact the value is 772 (see conversions.cc), but to give us some margin
|
||||||
@@ -97,17 +101,6 @@ static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
|
|||||||
return Vector<const char>(buffer.start(), 0);
|
return Vector<const char>(buffer.start(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
|
|
||||||
for (int i = buffer.length() - 1; i >= 0; --i) {
|
|
||||||
if (buffer[i] != '0') {
|
|
||||||
return buffer.SubVector(0, i + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Vector<const char>(buffer.start(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
static void CutToMaxSignificantDigits(Vector<const char> buffer,
|
static void CutToMaxSignificantDigits(Vector<const char> buffer,
|
||||||
int exponent,
|
int exponent,
|
||||||
char* significant_buffer,
|
char* significant_buffer,
|
||||||
@@ -117,7 +110,7 @@ static void CutToMaxSignificantDigits(Vector<const char> buffer,
|
|||||||
}
|
}
|
||||||
// The input buffer has been trimmed. Therefore the last digit must be
|
// The input buffer has been trimmed. Therefore the last digit must be
|
||||||
// different from '0'.
|
// different from '0'.
|
||||||
ASSERT(buffer[buffer.length() - 1] != '0');
|
DOUBLE_CONVERSION_ASSERT(buffer[buffer.length() - 1] != '0');
|
||||||
// Set the last digit to be non-zero. This is sufficient to guarantee
|
// Set the last digit to be non-zero. This is sufficient to guarantee
|
||||||
// correct rounding.
|
// correct rounding.
|
||||||
significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
|
significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
|
||||||
@@ -138,7 +131,7 @@ static void TrimAndCut(Vector<const char> buffer, int exponent,
|
|||||||
exponent += left_trimmed.length() - right_trimmed.length();
|
exponent += left_trimmed.length() - right_trimmed.length();
|
||||||
if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
|
if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
|
||||||
(void) space_size; // Mark variable as used.
|
(void) space_size; // Mark variable as used.
|
||||||
ASSERT(space_size >= kMaxSignificantDecimalDigits);
|
DOUBLE_CONVERSION_ASSERT(space_size >= kMaxSignificantDecimalDigits);
|
||||||
CutToMaxSignificantDigits(right_trimmed, exponent,
|
CutToMaxSignificantDigits(right_trimmed, exponent,
|
||||||
buffer_copy_space, updated_exponent);
|
buffer_copy_space, updated_exponent);
|
||||||
*trimmed = Vector<const char>(buffer_copy_space,
|
*trimmed = Vector<const char>(buffer_copy_space,
|
||||||
@@ -161,7 +154,7 @@ static uint64_t ReadUint64(Vector<const char> buffer,
|
|||||||
int i = 0;
|
int i = 0;
|
||||||
while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
|
while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
|
||||||
int digit = buffer[i++] - '0';
|
int digit = buffer[i++] - '0';
|
||||||
ASSERT(0 <= digit && digit <= 9);
|
DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9);
|
||||||
result = 10 * result + digit;
|
result = 10 * result + digit;
|
||||||
}
|
}
|
||||||
*number_of_read_digits = i;
|
*number_of_read_digits = i;
|
||||||
@@ -198,12 +191,14 @@ static bool DoubleStrtod(Vector<const char> trimmed,
|
|||||||
int exponent,
|
int exponent,
|
||||||
double* result) {
|
double* result) {
|
||||||
#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
||||||
|
// Avoid "unused parameter" warnings
|
||||||
|
(void) trimmed;
|
||||||
|
(void) exponent;
|
||||||
|
(void) result;
|
||||||
// On x86 the floating-point stack can be 64 or 80 bits wide. If it is
|
// On x86 the floating-point stack can be 64 or 80 bits wide. If it is
|
||||||
// 80 bits wide (as is the case on Linux) then double-rounding occurs and the
|
// 80 bits wide (as is the case on Linux) then double-rounding occurs and the
|
||||||
// result is not accurate.
|
// result is not accurate.
|
||||||
// We know that Windows32 uses 64 bits and is therefore accurate.
|
// We know that Windows32 uses 64 bits and is therefore accurate.
|
||||||
// Note that the ARM simulator is compiled for 32bits. It therefore exhibits
|
|
||||||
// the same problem.
|
|
||||||
return false;
|
return false;
|
||||||
#else
|
#else
|
||||||
if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
|
if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
|
||||||
@@ -217,14 +212,14 @@ static bool DoubleStrtod(Vector<const char> trimmed,
|
|||||||
if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
|
if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
|
||||||
// 10^-exponent fits into a double.
|
// 10^-exponent fits into a double.
|
||||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||||
ASSERT(read_digits == trimmed.length());
|
DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
|
||||||
*result /= exact_powers_of_ten[-exponent];
|
*result /= exact_powers_of_ten[-exponent];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (0 <= exponent && exponent < kExactPowersOfTenSize) {
|
if (0 <= exponent && exponent < kExactPowersOfTenSize) {
|
||||||
// 10^exponent fits into a double.
|
// 10^exponent fits into a double.
|
||||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||||
ASSERT(read_digits == trimmed.length());
|
DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
|
||||||
*result *= exact_powers_of_ten[exponent];
|
*result *= exact_powers_of_ten[exponent];
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -236,7 +231,7 @@ static bool DoubleStrtod(Vector<const char> trimmed,
|
|||||||
// 10^remaining_digits. As a result the remaining exponent now fits
|
// 10^remaining_digits. As a result the remaining exponent now fits
|
||||||
// into a double too.
|
// into a double too.
|
||||||
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
||||||
ASSERT(read_digits == trimmed.length());
|
DOUBLE_CONVERSION_ASSERT(read_digits == trimmed.length());
|
||||||
*result *= exact_powers_of_ten[remaining_digits];
|
*result *= exact_powers_of_ten[remaining_digits];
|
||||||
*result *= exact_powers_of_ten[exponent - remaining_digits];
|
*result *= exact_powers_of_ten[exponent - remaining_digits];
|
||||||
return true;
|
return true;
|
||||||
@@ -250,21 +245,21 @@ static bool DoubleStrtod(Vector<const char> trimmed,
|
|||||||
// Returns 10^exponent as an exact DiyFp.
|
// Returns 10^exponent as an exact DiyFp.
|
||||||
// The given exponent must be in the range [1; kDecimalExponentDistance[.
|
// The given exponent must be in the range [1; kDecimalExponentDistance[.
|
||||||
static DiyFp AdjustmentPowerOfTen(int exponent) {
|
static DiyFp AdjustmentPowerOfTen(int exponent) {
|
||||||
ASSERT(0 < exponent);
|
DOUBLE_CONVERSION_ASSERT(0 < exponent);
|
||||||
ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
|
DOUBLE_CONVERSION_ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
|
||||||
// Simply hardcode the remaining powers for the given decimal exponent
|
// Simply hardcode the remaining powers for the given decimal exponent
|
||||||
// distance.
|
// distance.
|
||||||
ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
|
DOUBLE_CONVERSION_ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
|
||||||
switch (exponent) {
|
switch (exponent) {
|
||||||
case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
|
case 1: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xa0000000, 00000000), -60);
|
||||||
case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
|
case 2: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc8000000, 00000000), -57);
|
||||||
case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
|
case 3: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xfa000000, 00000000), -54);
|
||||||
case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
|
case 4: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x9c400000, 00000000), -50);
|
||||||
case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
|
case 5: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xc3500000, 00000000), -47);
|
||||||
case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
|
case 6: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0xf4240000, 00000000), -44);
|
||||||
case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
|
case 7: return DiyFp(DOUBLE_CONVERSION_UINT64_2PART_C(0x98968000, 00000000), -40);
|
||||||
default:
|
default:
|
||||||
UNREACHABLE();
|
DOUBLE_CONVERSION_UNREACHABLE();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,7 +288,7 @@ static bool DiyFpStrtod(Vector<const char> buffer,
|
|||||||
input.Normalize();
|
input.Normalize();
|
||||||
error <<= old_e - input.e();
|
error <<= old_e - input.e();
|
||||||
|
|
||||||
ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
|
DOUBLE_CONVERSION_ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
|
||||||
if (exponent < PowersOfTenCache::kMinDecimalExponent) {
|
if (exponent < PowersOfTenCache::kMinDecimalExponent) {
|
||||||
*result = 0.0;
|
*result = 0.0;
|
||||||
return true;
|
return true;
|
||||||
@@ -311,7 +306,7 @@ static bool DiyFpStrtod(Vector<const char> buffer,
|
|||||||
if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
|
if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
|
||||||
// The product of input with the adjustment power fits into a 64 bit
|
// The product of input with the adjustment power fits into a 64 bit
|
||||||
// integer.
|
// integer.
|
||||||
ASSERT(DiyFp::kSignificandSize == 64);
|
DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64);
|
||||||
} else {
|
} else {
|
||||||
// The adjustment power is exact. There is hence only an error of 0.5.
|
// The adjustment power is exact. There is hence only an error of 0.5.
|
||||||
error += kDenominator / 2;
|
error += kDenominator / 2;
|
||||||
@@ -353,8 +348,8 @@ static bool DiyFpStrtod(Vector<const char> buffer,
|
|||||||
precision_digits_count -= shift_amount;
|
precision_digits_count -= shift_amount;
|
||||||
}
|
}
|
||||||
// We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
|
// We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
|
||||||
ASSERT(DiyFp::kSignificandSize == 64);
|
DOUBLE_CONVERSION_ASSERT(DiyFp::kSignificandSize == 64);
|
||||||
ASSERT(precision_digits_count < 64);
|
DOUBLE_CONVERSION_ASSERT(precision_digits_count < 64);
|
||||||
uint64_t one64 = 1;
|
uint64_t one64 = 1;
|
||||||
uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
|
uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
|
||||||
uint64_t precision_bits = input.f() & precision_bits_mask;
|
uint64_t precision_bits = input.f() & precision_bits_mask;
|
||||||
@@ -393,14 +388,14 @@ static bool DiyFpStrtod(Vector<const char> buffer,
|
|||||||
static int CompareBufferWithDiyFp(Vector<const char> buffer,
|
static int CompareBufferWithDiyFp(Vector<const char> buffer,
|
||||||
int exponent,
|
int exponent,
|
||||||
DiyFp diy_fp) {
|
DiyFp diy_fp) {
|
||||||
ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
|
DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
|
||||||
ASSERT(buffer.length() + exponent > kMinDecimalPower);
|
DOUBLE_CONVERSION_ASSERT(buffer.length() + exponent > kMinDecimalPower);
|
||||||
ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
|
DOUBLE_CONVERSION_ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
|
||||||
// Make sure that the Bignum will be able to hold all our numbers.
|
// Make sure that the Bignum will be able to hold all our numbers.
|
||||||
// Our Bignum implementation has a separate field for exponents. Shifts will
|
// Our Bignum implementation has a separate field for exponents. Shifts will
|
||||||
// consume at most one bigit (< 64 bits).
|
// consume at most one bigit (< 64 bits).
|
||||||
// ln(10) == 3.3219...
|
// ln(10) == 3.3219...
|
||||||
ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
|
DOUBLE_CONVERSION_ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
|
||||||
Bignum buffer_bignum;
|
Bignum buffer_bignum;
|
||||||
Bignum diy_fp_bignum;
|
Bignum diy_fp_bignum;
|
||||||
buffer_bignum.AssignDecimalString(buffer);
|
buffer_bignum.AssignDecimalString(buffer);
|
||||||
@@ -446,18 +441,36 @@ static bool ComputeGuess(Vector<const char> trimmed, int exponent,
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
double Strtod(Vector<const char> buffer, int exponent) {
|
static bool IsDigit(const char d) {
|
||||||
char copy_buffer[kMaxSignificantDecimalDigits];
|
return ('0' <= d) && (d <= '9');
|
||||||
Vector<const char> trimmed;
|
}
|
||||||
int updated_exponent;
|
|
||||||
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
|
||||||
&trimmed, &updated_exponent);
|
|
||||||
exponent = updated_exponent;
|
|
||||||
|
|
||||||
|
static bool IsNonZeroDigit(const char d) {
|
||||||
|
return ('1' <= d) && (d <= '9');
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef __has_cpp_attribute
|
||||||
|
#if __has_cpp_attribute(maybe_unused)
|
||||||
|
[[maybe_unused]]
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
static bool AssertTrimmedDigits(const Vector<const char>& buffer) {
|
||||||
|
for(int i = 0; i < buffer.length(); ++i) {
|
||||||
|
if(!IsDigit(buffer[i])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (buffer.length() == 0) || (IsNonZeroDigit(buffer[0]) && IsNonZeroDigit(buffer[buffer.length()-1]));
|
||||||
|
}
|
||||||
|
|
||||||
|
double StrtodTrimmed(Vector<const char> trimmed, int exponent) {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(trimmed.length() <= kMaxSignificantDecimalDigits);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(AssertTrimmedDigits(trimmed));
|
||||||
double guess;
|
double guess;
|
||||||
bool is_correct = ComputeGuess(trimmed, exponent, &guess);
|
const bool is_correct = ComputeGuess(trimmed, exponent, &guess);
|
||||||
if (is_correct) return guess;
|
if (is_correct) {
|
||||||
|
return guess;
|
||||||
|
}
|
||||||
DiyFp upper_boundary = Double(guess).UpperBoundary();
|
DiyFp upper_boundary = Double(guess).UpperBoundary();
|
||||||
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
||||||
if (comparison < 0) {
|
if (comparison < 0) {
|
||||||
@@ -472,8 +485,17 @@ double Strtod(Vector<const char> buffer, int exponent) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
double Strtod(Vector<const char> buffer, int exponent) {
|
||||||
|
char copy_buffer[kMaxSignificantDecimalDigits];
|
||||||
|
Vector<const char> trimmed;
|
||||||
|
int updated_exponent;
|
||||||
|
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
||||||
|
&trimmed, &updated_exponent);
|
||||||
|
return StrtodTrimmed(trimmed, updated_exponent);
|
||||||
|
}
|
||||||
|
|
||||||
static float SanitizedDoubletof(double d) {
|
static float SanitizedDoubletof(double d) {
|
||||||
ASSERT(d >= 0.0);
|
DOUBLE_CONVERSION_ASSERT(d >= 0.0);
|
||||||
// ASAN has a sanitize check that disallows casting doubles to floats if
|
// ASAN has a sanitize check that disallows casting doubles to floats if
|
||||||
// they are too big.
|
// they are too big.
|
||||||
// https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks
|
// https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#available-checks
|
||||||
@@ -503,6 +525,12 @@ float Strtof(Vector<const char> buffer, int exponent) {
|
|||||||
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
||||||
&trimmed, &updated_exponent);
|
&trimmed, &updated_exponent);
|
||||||
exponent = updated_exponent;
|
exponent = updated_exponent;
|
||||||
|
return StrtofTrimmed(trimmed, exponent);
|
||||||
|
}
|
||||||
|
|
||||||
|
float StrtofTrimmed(Vector<const char> trimmed, int exponent) {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(trimmed.length() <= kMaxSignificantDecimalDigits);
|
||||||
|
DOUBLE_CONVERSION_ASSERT(AssertTrimmedDigits(trimmed));
|
||||||
|
|
||||||
double double_guess;
|
double double_guess;
|
||||||
bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
|
bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
|
||||||
@@ -522,7 +550,7 @@ float Strtof(Vector<const char> buffer, int exponent) {
|
|||||||
// low-precision (3 digits):
|
// low-precision (3 digits):
|
||||||
// when read from input: 123
|
// when read from input: 123
|
||||||
// when rounded from high precision: 124.
|
// when rounded from high precision: 124.
|
||||||
// To do this we simply look at the neigbors of the correct result and see
|
// To do this we simply look at the neighbors of the correct result and see
|
||||||
// if they would round to the same float. If the guess is not correct we have
|
// if they would round to the same float. If the guess is not correct we have
|
||||||
// to look at four values (since two different doubles could be the correct
|
// to look at four values (since two different doubles could be the correct
|
||||||
// double).
|
// double).
|
||||||
@@ -541,7 +569,7 @@ float Strtof(Vector<const char> buffer, int exponent) {
|
|||||||
f4 = SanitizedDoubletof(double_next2);
|
f4 = SanitizedDoubletof(double_next2);
|
||||||
}
|
}
|
||||||
(void) f2; // Mark variable as used.
|
(void) f2; // Mark variable as used.
|
||||||
ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
|
DOUBLE_CONVERSION_ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
|
||||||
|
|
||||||
// If the guess doesn't lie near a single-precision boundary we can simply
|
// If the guess doesn't lie near a single-precision boundary we can simply
|
||||||
// return its float-value.
|
// return its float-value.
|
||||||
@@ -549,7 +577,7 @@ float Strtof(Vector<const char> buffer, int exponent) {
|
|||||||
return float_guess;
|
return float_guess;
|
||||||
}
|
}
|
||||||
|
|
||||||
ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
|
DOUBLE_CONVERSION_ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
|
||||||
(f1 == f2 && f2 != f3 && f3 == f4) ||
|
(f1 == f2 && f2 != f3 && f3 == f4) ||
|
||||||
(f1 == f2 && f2 == f3 && f3 != f4));
|
(f1 == f2 && f2 == f3 && f3 != f4));
|
||||||
|
|
||||||
|
@@ -40,6 +40,25 @@ double Strtod(Vector<const char> buffer, int exponent);
|
|||||||
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
||||||
float Strtof(Vector<const char> buffer, int exponent);
|
float Strtof(Vector<const char> buffer, int exponent);
|
||||||
|
|
||||||
|
// Same as Strtod, but assumes that 'trimmed' is already trimmed, as if run
|
||||||
|
// through TrimAndCut. That is, 'trimmed' must have no leading or trailing
|
||||||
|
// zeros, must not be a lone zero, and must not have 'too many' digits.
|
||||||
|
double StrtodTrimmed(Vector<const char> trimmed, int exponent);
|
||||||
|
|
||||||
|
// Same as Strtof, but assumes that 'trimmed' is already trimmed, as if run
|
||||||
|
// through TrimAndCut. That is, 'trimmed' must have no leading or trailing
|
||||||
|
// zeros, must not be a lone zero, and must not have 'too many' digits.
|
||||||
|
float StrtofTrimmed(Vector<const char> trimmed, int exponent);
|
||||||
|
|
||||||
|
inline Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
|
||||||
|
for (int i = buffer.length() - 1; i >= 0; --i) {
|
||||||
|
if (buffer[i] != '0') {
|
||||||
|
return buffer.SubVector(0, i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Vector<const char>(buffer.start(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace double_conversion
|
} // namespace double_conversion
|
||||||
|
|
||||||
#endif // DOUBLE_CONVERSION_STRTOD_H_
|
#endif // DOUBLE_CONVERSION_STRTOD_H_
|
||||||
|
@@ -28,17 +28,28 @@
|
|||||||
#ifndef DOUBLE_CONVERSION_UTILS_H_
|
#ifndef DOUBLE_CONVERSION_UTILS_H_
|
||||||
#define DOUBLE_CONVERSION_UTILS_H_
|
#define DOUBLE_CONVERSION_UTILS_H_
|
||||||
|
|
||||||
|
// Use DOUBLE_CONVERSION_NON_PREFIXED_MACROS to get unprefixed macros as was
|
||||||
|
// the case in double-conversion releases prior to 3.1.6
|
||||||
|
|
||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#ifndef ASSERT
|
#ifndef DOUBLE_CONVERSION_ASSERT
|
||||||
#define ASSERT(condition) \
|
#define DOUBLE_CONVERSION_ASSERT(condition) \
|
||||||
assert(condition);
|
assert(condition)
|
||||||
#endif
|
#endif
|
||||||
#ifndef UNIMPLEMENTED
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(ASSERT)
|
||||||
#define UNIMPLEMENTED() (abort())
|
#define ASSERT DOUBLE_CONVERSION_ASSERT
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
#ifndef DOUBLE_CONVERSION_UNIMPLEMENTED
|
||||||
|
#define DOUBLE_CONVERSION_UNIMPLEMENTED() (abort())
|
||||||
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNIMPLEMENTED)
|
||||||
|
#define UNIMPLEMENTED DOUBLE_CONVERSION_UNIMPLEMENTED
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifndef DOUBLE_CONVERSION_NO_RETURN
|
#ifndef DOUBLE_CONVERSION_NO_RETURN
|
||||||
#ifdef _MSC_VER
|
#ifdef _MSC_VER
|
||||||
#define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
|
#define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
|
||||||
@@ -46,23 +57,50 @@
|
|||||||
#define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
|
#define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
#ifndef UNREACHABLE
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(NO_RETURN)
|
||||||
|
#define NO_RETURN DOUBLE_CONVERSION_NO_RETURN
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef DOUBLE_CONVERSION_UNREACHABLE
|
||||||
#ifdef _MSC_VER
|
#ifdef _MSC_VER
|
||||||
void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
|
void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
|
||||||
inline void abort_noreturn() { abort(); }
|
inline void abort_noreturn() { abort(); }
|
||||||
#define UNREACHABLE() (abort_noreturn())
|
#define DOUBLE_CONVERSION_UNREACHABLE() (abort_noreturn())
|
||||||
#else
|
#else
|
||||||
#define UNREACHABLE() (abort())
|
#define DOUBLE_CONVERSION_UNREACHABLE() (abort())
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNREACHABLE)
|
||||||
|
#define UNREACHABLE DOUBLE_CONVERSION_UNREACHABLE
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Not all compilers support __has_attribute and combining a check for both
|
||||||
|
// ifdef and __has_attribute on the same preprocessor line isn't portable.
|
||||||
|
#ifdef __has_attribute
|
||||||
|
# define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) __has_attribute(x)
|
||||||
|
#else
|
||||||
|
# define DOUBLE_CONVERSION_HAS_ATTRIBUTE(x) 0
|
||||||
|
#endif
|
||||||
|
|
||||||
#ifndef DOUBLE_CONVERSION_UNUSED
|
#ifndef DOUBLE_CONVERSION_UNUSED
|
||||||
#ifdef __GNUC__
|
#if DOUBLE_CONVERSION_HAS_ATTRIBUTE(unused)
|
||||||
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
|
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
|
||||||
#else
|
#else
|
||||||
#define DOUBLE_CONVERSION_UNUSED
|
#define DOUBLE_CONVERSION_UNUSED
|
||||||
#endif
|
#endif
|
||||||
#endif
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UNUSED)
|
||||||
|
#define UNUSED DOUBLE_CONVERSION_UNUSED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if DOUBLE_CONVERSION_HAS_ATTRIBUTE(uninitialized)
|
||||||
|
#define DOUBLE_CONVERSION_STACK_UNINITIALIZED __attribute__((uninitialized))
|
||||||
|
#else
|
||||||
|
#define DOUBLE_CONVERSION_STACK_UNINITIALIZED
|
||||||
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(STACK_UNINITIALIZED)
|
||||||
|
#define STACK_UNINITIALIZED DOUBLE_CONVERSION_STACK_UNINITIALIZED
|
||||||
|
#endif
|
||||||
|
|
||||||
// Double operations detection based on target architecture.
|
// Double operations detection based on target architecture.
|
||||||
// Linux uses a 80bit wide floating point stack on x86. This induces double
|
// Linux uses a 80bit wide floating point stack on x86. This induces double
|
||||||
@@ -94,17 +132,19 @@ int main(int argc, char** argv) {
|
|||||||
defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \
|
defined(__ARMEL__) || defined(__avr32__) || defined(_M_ARM) || defined(_M_ARM64) || \
|
||||||
defined(__hppa__) || defined(__ia64__) || \
|
defined(__hppa__) || defined(__ia64__) || \
|
||||||
defined(__mips__) || \
|
defined(__mips__) || \
|
||||||
|
defined(__loongarch__) || \
|
||||||
|
defined(__nios2__) || defined(__ghs) || \
|
||||||
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
|
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
|
||||||
defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
|
defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
|
||||||
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
|
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
|
||||||
defined(__SH4__) || defined(__alpha__) || \
|
defined(__SH4__) || defined(__alpha__) || \
|
||||||
defined(_MIPS_ARCH_MIPS32R2) || defined(__ARMEB__) ||\
|
defined(_MIPS_ARCH_MIPS32R2) || defined(__ARMEB__) ||\
|
||||||
defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \
|
defined(__AARCH64EL__) || defined(__aarch64__) || defined(__AARCH64EB__) || \
|
||||||
defined(__riscv) || \
|
defined(__riscv) || defined(__e2k__) || \
|
||||||
defined(__loongarch64) || \
|
defined(__loongarch64) || \
|
||||||
defined(__or1k__) || defined(__arc__) || \
|
defined(__or1k__) || defined(__arc__) || defined(__ARC64__) || \
|
||||||
defined(__EMSCRIPTEN__) || \
|
defined(__microblaze__) || defined(__XTENSA__) || \
|
||||||
defined(nios2) || defined(__nios2) || defined(__nios2__)
|
defined(__EMSCRIPTEN__) || defined(__wasm32__)
|
||||||
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
||||||
#elif defined(__mc68000__) || \
|
#elif defined(__mc68000__) || \
|
||||||
defined(__pnacl__) || defined(__native_client__)
|
defined(__pnacl__) || defined(__native_client__)
|
||||||
@@ -119,6 +159,9 @@ int main(int argc, char** argv) {
|
|||||||
#else
|
#else
|
||||||
#error Target architecture was not detected as supported by Double-Conversion.
|
#error Target architecture was not detected as supported by Double-Conversion.
|
||||||
#endif
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(CORRECT_DOUBLE_OPERATIONS)
|
||||||
|
#define CORRECT_DOUBLE_OPERATIONS DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
|
||||||
|
#endif
|
||||||
|
|
||||||
#if defined(_WIN32) && !defined(__MINGW32__)
|
#if defined(_WIN32) && !defined(__MINGW32__)
|
||||||
|
|
||||||
@@ -142,27 +185,35 @@ typedef uint16_t uc16;
|
|||||||
|
|
||||||
// The following macro works on both 32 and 64-bit platforms.
|
// The following macro works on both 32 and 64-bit platforms.
|
||||||
// Usage: instead of writing 0x1234567890123456
|
// Usage: instead of writing 0x1234567890123456
|
||||||
// write UINT64_2PART_C(0x12345678,90123456);
|
// write DOUBLE_CONVERSION_UINT64_2PART_C(0x12345678,90123456);
|
||||||
#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
|
#define DOUBLE_CONVERSION_UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(UINT64_2PART_C)
|
||||||
|
#define UINT64_2PART_C DOUBLE_CONVERSION_UINT64_2PART_C
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// The expression DOUBLE_CONVERSION_ARRAY_SIZE(a) is a compile-time constant of type
|
||||||
// The expression ARRAY_SIZE(a) is a compile-time constant of type
|
|
||||||
// size_t which represents the number of elements of the given
|
// size_t which represents the number of elements of the given
|
||||||
// array. You should only use ARRAY_SIZE on statically allocated
|
// array. You should only use DOUBLE_CONVERSION_ARRAY_SIZE on statically allocated
|
||||||
// arrays.
|
// arrays.
|
||||||
#ifndef ARRAY_SIZE
|
#ifndef DOUBLE_CONVERSION_ARRAY_SIZE
|
||||||
#define ARRAY_SIZE(a) \
|
#define DOUBLE_CONVERSION_ARRAY_SIZE(a) \
|
||||||
((sizeof(a) / sizeof(*(a))) / \
|
((sizeof(a) / sizeof(*(a))) / \
|
||||||
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
|
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
|
||||||
#endif
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(ARRAY_SIZE)
|
||||||
|
#define ARRAY_SIZE DOUBLE_CONVERSION_ARRAY_SIZE
|
||||||
|
#endif
|
||||||
|
|
||||||
// A macro to disallow the evil copy constructor and operator= functions
|
// A macro to disallow the evil copy constructor and operator= functions
|
||||||
// This should be used in the private: declarations for a class
|
// This should be used in the private: declarations for a class
|
||||||
#ifndef DC_DISALLOW_COPY_AND_ASSIGN
|
#ifndef DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN
|
||||||
#define DC_DISALLOW_COPY_AND_ASSIGN(TypeName) \
|
#define DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName) \
|
||||||
TypeName(const TypeName&); \
|
TypeName(const TypeName&); \
|
||||||
void operator=(const TypeName&)
|
void operator=(const TypeName&)
|
||||||
#endif
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(DC_DISALLOW_COPY_AND_ASSIGN)
|
||||||
|
#define DC_DISALLOW_COPY_AND_ASSIGN DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN
|
||||||
|
#endif
|
||||||
|
|
||||||
// A macro to disallow all the implicit constructors, namely the
|
// A macro to disallow all the implicit constructors, namely the
|
||||||
// default constructor, copy constructor and operator= functions.
|
// default constructor, copy constructor and operator= functions.
|
||||||
@@ -170,33 +221,20 @@ typedef uint16_t uc16;
|
|||||||
// This should be used in the private: declarations for a class
|
// This should be used in the private: declarations for a class
|
||||||
// that wants to prevent anyone from instantiating it. This is
|
// that wants to prevent anyone from instantiating it. This is
|
||||||
// especially useful for classes containing only static methods.
|
// especially useful for classes containing only static methods.
|
||||||
#ifndef DC_DISALLOW_IMPLICIT_CONSTRUCTORS
|
#ifndef DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS
|
||||||
#define DC_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
|
#define DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
|
||||||
TypeName(); \
|
TypeName(); \
|
||||||
DC_DISALLOW_COPY_AND_ASSIGN(TypeName)
|
DOUBLE_CONVERSION_DISALLOW_COPY_AND_ASSIGN(TypeName)
|
||||||
|
#endif
|
||||||
|
#if defined(DOUBLE_CONVERSION_NON_PREFIXED_MACROS) && !defined(DC_DISALLOW_IMPLICIT_CONSTRUCTORS)
|
||||||
|
#define DC_DISALLOW_IMPLICIT_CONSTRUCTORS DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace double_conversion {
|
namespace double_conversion {
|
||||||
|
|
||||||
static const int kCharSize = sizeof(char);
|
|
||||||
|
|
||||||
// Returns the maximum of the two parameters.
|
|
||||||
template <typename T>
|
|
||||||
static T Max(T a, T b) {
|
|
||||||
return a < b ? b : a;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Returns the minimum of the two parameters.
|
|
||||||
template <typename T>
|
|
||||||
static T Min(T a, T b) {
|
|
||||||
return a < b ? a : b;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
inline int StrLength(const char* string) {
|
inline int StrLength(const char* string) {
|
||||||
size_t length = strlen(string);
|
size_t length = strlen(string);
|
||||||
ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
|
DOUBLE_CONVERSION_ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
|
||||||
return static_cast<int>(length);
|
return static_cast<int>(length);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,15 +244,15 @@ class Vector {
|
|||||||
public:
|
public:
|
||||||
Vector() : start_(NULL), length_(0) {}
|
Vector() : start_(NULL), length_(0) {}
|
||||||
Vector(T* data, int len) : start_(data), length_(len) {
|
Vector(T* data, int len) : start_(data), length_(len) {
|
||||||
ASSERT(len == 0 || (len > 0 && data != NULL));
|
DOUBLE_CONVERSION_ASSERT(len == 0 || (len > 0 && data != NULL));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns a vector using the same backing storage as this one,
|
// Returns a vector using the same backing storage as this one,
|
||||||
// spanning from and including 'from', to but not including 'to'.
|
// spanning from and including 'from', to but not including 'to'.
|
||||||
Vector<T> SubVector(int from, int to) {
|
Vector<T> SubVector(int from, int to) {
|
||||||
ASSERT(to <= length_);
|
DOUBLE_CONVERSION_ASSERT(to <= length_);
|
||||||
ASSERT(from < to);
|
DOUBLE_CONVERSION_ASSERT(from < to);
|
||||||
ASSERT(0 <= from);
|
DOUBLE_CONVERSION_ASSERT(0 <= from);
|
||||||
return Vector<T>(start() + from, to - from);
|
return Vector<T>(start() + from, to - from);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,7 +267,7 @@ class Vector {
|
|||||||
|
|
||||||
// Access individual vector elements - checks bounds in debug mode.
|
// Access individual vector elements - checks bounds in debug mode.
|
||||||
T& operator[](int index) const {
|
T& operator[](int index) const {
|
||||||
ASSERT(0 <= index && index < length_);
|
DOUBLE_CONVERSION_ASSERT(0 <= index && index < length_);
|
||||||
return start_[index];
|
return start_[index];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,6 +275,11 @@ class Vector {
|
|||||||
|
|
||||||
T& last() { return start_[length_ - 1]; }
|
T& last() { return start_[length_ - 1]; }
|
||||||
|
|
||||||
|
void pop_back() {
|
||||||
|
DOUBLE_CONVERSION_ASSERT(!is_empty());
|
||||||
|
--length_;
|
||||||
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
T* start_;
|
T* start_;
|
||||||
int length_;
|
int length_;
|
||||||
@@ -257,7 +300,7 @@ class StringBuilder {
|
|||||||
|
|
||||||
// Get the current position in the builder.
|
// Get the current position in the builder.
|
||||||
int position() const {
|
int position() const {
|
||||||
ASSERT(!is_finalized());
|
DOUBLE_CONVERSION_ASSERT(!is_finalized());
|
||||||
return position_;
|
return position_;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,8 +311,8 @@ class StringBuilder {
|
|||||||
// 0-characters; use the Finalize() method to terminate the string
|
// 0-characters; use the Finalize() method to terminate the string
|
||||||
// instead.
|
// instead.
|
||||||
void AddCharacter(char c) {
|
void AddCharacter(char c) {
|
||||||
ASSERT(c != '\0');
|
DOUBLE_CONVERSION_ASSERT(c != '\0');
|
||||||
ASSERT(!is_finalized() && position_ < buffer_.length());
|
DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length());
|
||||||
buffer_[position_++] = c;
|
buffer_[position_++] = c;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,9 +325,9 @@ class StringBuilder {
|
|||||||
// Add the first 'n' characters of the given string 's' to the
|
// Add the first 'n' characters of the given string 's' to the
|
||||||
// builder. The input string must have enough characters.
|
// builder. The input string must have enough characters.
|
||||||
void AddSubstring(const char* s, int n) {
|
void AddSubstring(const char* s, int n) {
|
||||||
ASSERT(!is_finalized() && position_ + n < buffer_.length());
|
DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ + n < buffer_.length());
|
||||||
ASSERT(static_cast<size_t>(n) <= strlen(s));
|
DOUBLE_CONVERSION_ASSERT(static_cast<size_t>(n) <= strlen(s));
|
||||||
memmove(&buffer_[position_], s, n * kCharSize);
|
memmove(&buffer_[position_], s, n);
|
||||||
position_ += n;
|
position_ += n;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,13 +342,13 @@ class StringBuilder {
|
|||||||
|
|
||||||
// Finalize the string by 0-terminating it and returning the buffer.
|
// Finalize the string by 0-terminating it and returning the buffer.
|
||||||
char* Finalize() {
|
char* Finalize() {
|
||||||
ASSERT(!is_finalized() && position_ < buffer_.length());
|
DOUBLE_CONVERSION_ASSERT(!is_finalized() && position_ < buffer_.length());
|
||||||
buffer_[position_] = '\0';
|
buffer_[position_] = '\0';
|
||||||
// Make sure nobody managed to add a 0-character to the
|
// Make sure nobody managed to add a 0-character to the
|
||||||
// buffer while building the string.
|
// buffer while building the string.
|
||||||
ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
|
DOUBLE_CONVERSION_ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
|
||||||
position_ = -1;
|
position_ = -1;
|
||||||
ASSERT(is_finalized());
|
DOUBLE_CONVERSION_ASSERT(is_finalized());
|
||||||
return buffer_.start();
|
return buffer_.start();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -315,7 +358,7 @@ class StringBuilder {
|
|||||||
|
|
||||||
bool is_finalized() const { return position_ < 0; }
|
bool is_finalized() const { return position_ < 0; }
|
||||||
|
|
||||||
DC_DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
|
DOUBLE_CONVERSION_DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
|
||||||
};
|
};
|
||||||
|
|
||||||
// The type-based aliasing rule allows the compiler to assume that pointers of
|
// The type-based aliasing rule allows the compiler to assume that pointers of
|
||||||
@@ -343,7 +386,7 @@ class StringBuilder {
|
|||||||
// enough that it can no longer see that you have cast one pointer type to
|
// enough that it can no longer see that you have cast one pointer type to
|
||||||
// another thus avoiding the warning.
|
// another thus avoiding the warning.
|
||||||
template <class Dest, class Source>
|
template <class Dest, class Source>
|
||||||
inline Dest BitCast(const Source& source) {
|
Dest BitCast(const Source& source) {
|
||||||
// Compile time assertion: sizeof(Dest) == sizeof(Source)
|
// Compile time assertion: sizeof(Dest) == sizeof(Source)
|
||||||
// A compile error here means your Dest and Source have different sizes.
|
// A compile error here means your Dest and Source have different sizes.
|
||||||
#if __cplusplus >= 201103L
|
#if __cplusplus >= 201103L
|
||||||
@@ -360,7 +403,7 @@ inline Dest BitCast(const Source& source) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
template <class Dest, class Source>
|
template <class Dest, class Source>
|
||||||
inline Dest BitCast(Source* source) {
|
Dest BitCast(Source* source) {
|
||||||
return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
|
return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -16,6 +16,8 @@
|
|||||||
#include "Poco/Thread.h"
|
#include "Poco/Thread.h"
|
||||||
#include "Poco/Event.h"
|
#include "Poco/Event.h"
|
||||||
#include "Poco/Exception.h"
|
#include "Poco/Exception.h"
|
||||||
|
#include "Poco/Environment.h"
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
|
||||||
using Poco::ActiveDispatcher;
|
using Poco::ActiveDispatcher;
|
||||||
@@ -25,6 +27,7 @@ using Poco::ActiveStarter;
|
|||||||
using Poco::Thread;
|
using Poco::Thread;
|
||||||
using Poco::Event;
|
using Poco::Event;
|
||||||
using Poco::Exception;
|
using Poco::Exception;
|
||||||
|
using Poco::Environment;
|
||||||
|
|
||||||
|
|
||||||
namespace
|
namespace
|
||||||
@@ -195,6 +198,12 @@ void ActiveDispatcherTest::testVoidIn()
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void ActiveDispatcherTest::testActiveDispatcher()
|
||||||
|
{
|
||||||
|
std::cout << "(disabled on TSAN runs)";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
void ActiveDispatcherTest::setUp()
|
void ActiveDispatcherTest::setUp()
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
@@ -209,13 +218,19 @@ CppUnit::Test* ActiveDispatcherTest::suite()
|
|||||||
{
|
{
|
||||||
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveDispatcherTest");
|
CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ActiveDispatcherTest");
|
||||||
|
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWait);
|
// see https://github.com/pocoproject/poco/pull/3617
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWaitInterval);
|
if (!Environment::has("TSAN_OPTIONS"))
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testTryWait);
|
{
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testFailure);
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWait);
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoid);
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testWaitInterval);
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidIn);
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testTryWait);
|
||||||
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidInOut);
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testFailure);
|
||||||
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoid);
|
||||||
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidIn);
|
||||||
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testVoidInOut);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
CppUnit_addTest(pSuite, ActiveDispatcherTest, testActiveDispatcher);
|
||||||
|
|
||||||
return pSuite;
|
return pSuite;
|
||||||
}
|
}
|
||||||
|
@@ -28,6 +28,7 @@ public:
|
|||||||
void testVoid();
|
void testVoid();
|
||||||
void testVoidIn();
|
void testVoidIn();
|
||||||
void testVoidInOut();
|
void testVoidInOut();
|
||||||
|
void testActiveDispatcher();
|
||||||
|
|
||||||
void setUp();
|
void setUp();
|
||||||
void tearDown();
|
void tearDown();
|
||||||
|
@@ -71,7 +71,7 @@ protected:
|
|||||||
|
|
||||||
int getCount() const;
|
int getCount() const;
|
||||||
private:
|
private:
|
||||||
int _count;
|
std::atomic<int> _count;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -56,6 +56,7 @@ void DirectoryWatcherTest::testAdded()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() >= 1);
|
assertTrue (_events.size() >= 1);
|
||||||
assertTrue (_events[0].callback == "onItemAdded");
|
assertTrue (_events[0].callback == "onItemAdded");
|
||||||
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
||||||
@@ -87,6 +88,7 @@ void DirectoryWatcherTest::testRemoved()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() >= 1);
|
assertTrue (_events.size() >= 1);
|
||||||
assertTrue (_events[0].callback == "onItemRemoved");
|
assertTrue (_events[0].callback == "onItemRemoved");
|
||||||
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
||||||
@@ -119,6 +121,7 @@ void DirectoryWatcherTest::testModified()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() >= 1);
|
assertTrue (_events.size() >= 1);
|
||||||
assertTrue (_events[0].callback == "onItemModified");
|
assertTrue (_events[0].callback == "onItemModified");
|
||||||
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
||||||
@@ -152,6 +155,7 @@ void DirectoryWatcherTest::testMoved()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
if (dw.supportsMoveEvents())
|
if (dw.supportsMoveEvents())
|
||||||
{
|
{
|
||||||
assertTrue (_events.size() >= 2);
|
assertTrue (_events.size() >= 2);
|
||||||
@@ -214,6 +218,7 @@ void DirectoryWatcherTest::testSuspend()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() == 0);
|
assertTrue (_events.size() == 0);
|
||||||
assertTrue (!_error);
|
assertTrue (!_error);
|
||||||
}
|
}
|
||||||
@@ -243,8 +248,11 @@ void DirectoryWatcherTest::testResume()
|
|||||||
fos2 << "Again!";
|
fos2 << "Again!";
|
||||||
fos2.close();
|
fos2.close();
|
||||||
|
|
||||||
assertTrue (_events.size() == 0);
|
{
|
||||||
assertTrue (!_error);
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
|
assertTrue (_events.size() == 0);
|
||||||
|
assertTrue (!_error);
|
||||||
|
}
|
||||||
|
|
||||||
dw.resumeEvents();
|
dw.resumeEvents();
|
||||||
|
|
||||||
@@ -254,6 +262,7 @@ void DirectoryWatcherTest::testResume()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() >= 1);
|
assertTrue (_events.size() >= 1);
|
||||||
assertTrue (_events[0].callback == "onItemModified");
|
assertTrue (_events[0].callback == "onItemModified");
|
||||||
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
||||||
@@ -301,8 +310,11 @@ void DirectoryWatcherTest::testSuspendMultipleTimes()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
assertTrue (_events.size() == 0);
|
{
|
||||||
assertTrue (!_error);
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
|
assertTrue (_events.size() == 0);
|
||||||
|
assertTrue (!_error);
|
||||||
|
}
|
||||||
|
|
||||||
dw.resumeEvents();
|
dw.resumeEvents();
|
||||||
dw.resumeEvents();
|
dw.resumeEvents();
|
||||||
@@ -313,6 +325,7 @@ void DirectoryWatcherTest::testSuspendMultipleTimes()
|
|||||||
|
|
||||||
Poco::Thread::sleep(2000*dw.scanInterval());
|
Poco::Thread::sleep(2000*dw.scanInterval());
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
assertTrue (_events.size() >= 1);
|
assertTrue (_events.size() >= 1);
|
||||||
assertTrue (_events[0].callback == "onItemModified");
|
assertTrue (_events[0].callback == "onItemModified");
|
||||||
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
assertTrue (Poco::Path(_events[0].path).getFileName() == "test.txt");
|
||||||
@@ -359,6 +372,8 @@ void DirectoryWatcherTest::onItemAdded(const Poco::DirectoryWatcher::DirectoryEv
|
|||||||
de.callback = "onItemAdded";
|
de.callback = "onItemAdded";
|
||||||
de.path = ev.item.path();
|
de.path = ev.item.path();
|
||||||
de.type = ev.event;
|
de.type = ev.event;
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
_events.push_back(de);
|
_events.push_back(de);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -369,6 +384,8 @@ void DirectoryWatcherTest::onItemRemoved(const Poco::DirectoryWatcher::Directory
|
|||||||
de.callback = "onItemRemoved";
|
de.callback = "onItemRemoved";
|
||||||
de.path = ev.item.path();
|
de.path = ev.item.path();
|
||||||
de.type = ev.event;
|
de.type = ev.event;
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
_events.push_back(de);
|
_events.push_back(de);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -379,6 +396,8 @@ void DirectoryWatcherTest::onItemModified(const Poco::DirectoryWatcher::Director
|
|||||||
de.callback = "onItemModified";
|
de.callback = "onItemModified";
|
||||||
de.path = ev.item.path();
|
de.path = ev.item.path();
|
||||||
de.type = ev.event;
|
de.type = ev.event;
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
_events.push_back(de);
|
_events.push_back(de);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -389,6 +408,8 @@ void DirectoryWatcherTest::onItemMovedFrom(const Poco::DirectoryWatcher::Directo
|
|||||||
de.callback = "onItemMovedFrom";
|
de.callback = "onItemMovedFrom";
|
||||||
de.path = ev.item.path();
|
de.path = ev.item.path();
|
||||||
de.type = ev.event;
|
de.type = ev.event;
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
_events.push_back(de);
|
_events.push_back(de);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -399,12 +420,15 @@ void DirectoryWatcherTest::onItemMovedTo(const Poco::DirectoryWatcher::Directory
|
|||||||
de.callback = "onItemMovedTo";
|
de.callback = "onItemMovedTo";
|
||||||
de.path = ev.item.path();
|
de.path = ev.item.path();
|
||||||
de.type = ev.event;
|
de.type = ev.event;
|
||||||
|
|
||||||
|
Poco::Mutex::ScopedLock l(_mutex);
|
||||||
_events.push_back(de);
|
_events.push_back(de);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
void DirectoryWatcherTest::onError(const Poco::Exception& exc)
|
void DirectoryWatcherTest::onError(const Poco::Exception& exc)
|
||||||
{
|
{
|
||||||
|
|
||||||
_error = true;
|
_error = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -22,6 +22,7 @@
|
|||||||
|
|
||||||
#include "Poco/DirectoryWatcher.h"
|
#include "Poco/DirectoryWatcher.h"
|
||||||
#include "Poco/Path.h"
|
#include "Poco/Path.h"
|
||||||
|
#include "Poco/Mutex.h"
|
||||||
#include "CppUnit/TestCase.h"
|
#include "CppUnit/TestCase.h"
|
||||||
|
|
||||||
|
|
||||||
@@ -63,6 +64,7 @@ private:
|
|||||||
};
|
};
|
||||||
std::vector<DirEvent> _events;
|
std::vector<DirEvent> _events;
|
||||||
bool _error;
|
bool _error;
|
||||||
|
Poco::Mutex _mutex;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -63,7 +63,7 @@ protected:
|
|||||||
|
|
||||||
int getCount() const;
|
int getCount() const;
|
||||||
private:
|
private:
|
||||||
int _count;
|
std::atomic<int> _count;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -71,7 +71,7 @@ protected:
|
|||||||
|
|
||||||
int getCount() const;
|
int getCount() const;
|
||||||
private:
|
private:
|
||||||
int _count;
|
std::atomic<int> _count;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -169,11 +169,11 @@ namespace
|
|||||||
}
|
}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
bool _started;
|
std::atomic<bool> _started;
|
||||||
bool _cancelled;
|
std::atomic<bool> _cancelled;
|
||||||
bool _finished;
|
std::atomic<bool> _finished;
|
||||||
Exception* _pException;
|
Exception* _pException;
|
||||||
float _progress;
|
float _progress;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
@@ -85,7 +85,7 @@ void pocoInitializeLibrary()
|
|||||||
|
|
||||||
void pocoUninitializeLibrary()
|
void pocoUninitializeLibrary()
|
||||||
{
|
{
|
||||||
std::cout << "TestLibrary uninitialzing" << std::endl;
|
std::cout << "TestLibrary uninitializing" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@@ -555,7 +555,7 @@ read_number(json_stream *json, int c)
|
|||||||
json_error(json, "unexpected byte '%c' in number", c);
|
json_error(json, "unexpected byte '%c' in number", c);
|
||||||
return JSON_ERROR;
|
return JSON_ERROR;
|
||||||
}
|
}
|
||||||
} else if (strchr("123456789", c) != NULL) {
|
} else if (c >= '1' && c <= '9') {
|
||||||
c = json->source.peek(&json->source);
|
c = json->source.peek(&json->source);
|
||||||
if (is_digit(c)) {
|
if (is_digit(c)) {
|
||||||
if (read_digits(json) != 0)
|
if (read_digits(json) != 0)
|
||||||
|
@@ -9,12 +9,12 @@
|
|||||||
extern "C" {
|
extern "C" {
|
||||||
#else
|
#else
|
||||||
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
|
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#else
|
#else
|
||||||
#ifndef bool
|
#ifndef bool
|
||||||
#define bool int
|
#define bool int
|
||||||
#define true 1
|
#define true 1
|
||||||
#define false 0
|
#define false 0
|
||||||
#endif /* bool */
|
#endif /* bool */
|
||||||
#endif /* __STDC_VERSION__ */
|
#endif /* __STDC_VERSION__ */
|
||||||
#endif /* __cplusplus */
|
#endif /* __cplusplus */
|
||||||
@@ -33,7 +33,7 @@ struct json_allocator {
|
|||||||
void (*free)(void *);
|
void (*free)(void *);
|
||||||
};
|
};
|
||||||
|
|
||||||
typedef int (*json_user_io) (void *user);
|
typedef int (*json_user_io)(void *user);
|
||||||
|
|
||||||
typedef struct json_stream json_stream;
|
typedef struct json_stream json_stream;
|
||||||
typedef struct json_allocator json_allocator;
|
typedef struct json_allocator json_allocator;
|
||||||
@@ -69,8 +69,8 @@ PDJSON_SYMEXPORT bool json_isspace(int c);
|
|||||||
/* internal */
|
/* internal */
|
||||||
|
|
||||||
struct json_source {
|
struct json_source {
|
||||||
int (*get) (struct json_source *);
|
int (*get)(struct json_source *);
|
||||||
int (*peek) (struct json_source *);
|
int (*peek)(struct json_source *);
|
||||||
size_t position;
|
size_t position;
|
||||||
union {
|
union {
|
||||||
struct {
|
struct {
|
||||||
|
@@ -74,7 +74,7 @@ private:
|
|||||||
Poco::Thread _thread;
|
Poco::Thread _thread;
|
||||||
Poco::Event _ready;
|
Poco::Event _ready;
|
||||||
mutable Poco::FastMutex _mutex;
|
mutable Poco::FastMutex _mutex;
|
||||||
bool _stop;
|
std::atomic<bool> _stop;
|
||||||
std::vector<std::string> _nextResponses;
|
std::vector<std::string> _nextResponses;
|
||||||
std::vector<std::string> _lastCommands;
|
std::vector<std::string> _lastCommands;
|
||||||
bool _acceptCommands;
|
bool _acceptCommands;
|
||||||
|
@@ -54,7 +54,7 @@ private:
|
|||||||
Poco::Net::SecureServerSocket _socket;
|
Poco::Net::SecureServerSocket _socket;
|
||||||
Poco::Thread _thread;
|
Poco::Thread _thread;
|
||||||
Poco::Event _ready;
|
Poco::Event _ready;
|
||||||
bool _stop;
|
std::atomic<bool> _stop;
|
||||||
std::string _lastRequest;
|
std::string _lastRequest;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@@ -23,6 +23,7 @@
|
|||||||
#include "Poco/RefCountedObject.h"
|
#include "Poco/RefCountedObject.h"
|
||||||
#include "Poco/AutoPtr.h"
|
#include "Poco/AutoPtr.h"
|
||||||
#include "Poco/Timestamp.h"
|
#include "Poco/Timestamp.h"
|
||||||
|
#include "Poco/Mutex.h"
|
||||||
|
|
||||||
|
|
||||||
namespace Poco {
|
namespace Poco {
|
||||||
@@ -62,6 +63,9 @@ public:
|
|||||||
///
|
///
|
||||||
/// Returns 0 if the timer has never been executed.
|
/// Returns 0 if the timer has never been executed.
|
||||||
|
|
||||||
|
void updateLastExecution();
|
||||||
|
/// Updates the last execution of the timer task.
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
~TimerTask();
|
~TimerTask();
|
||||||
/// Destroys the TimerTask.
|
/// Destroys the TimerTask.
|
||||||
@@ -71,9 +75,8 @@ private:
|
|||||||
TimerTask& operator = (const TimerTask&);
|
TimerTask& operator = (const TimerTask&);
|
||||||
|
|
||||||
Poco::Timestamp _lastExecution;
|
Poco::Timestamp _lastExecution;
|
||||||
bool _isCancelled;
|
std::atomic<bool> _isCancelled;
|
||||||
|
mutable FastMutex _mutex;
|
||||||
friend class TaskNotification;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
@@ -114,10 +117,18 @@ inline bool TimerTask::isCancelled() const
|
|||||||
|
|
||||||
inline Poco::Timestamp TimerTask::lastExecution() const
|
inline Poco::Timestamp TimerTask::lastExecution() const
|
||||||
{
|
{
|
||||||
|
FastMutex::ScopedLock l(_mutex);
|
||||||
return _lastExecution;
|
return _lastExecution;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline void TimerTask::updateLastExecution()
|
||||||
|
{
|
||||||
|
FastMutex::ScopedLock l(_mutex);
|
||||||
|
_lastExecution.update();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
} } // namespace Poco::Util
|
} } // namespace Poco::Util
|
||||||
|
|
||||||
|
|
||||||
|
@@ -135,7 +135,7 @@ public:
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
_pTask->_lastExecution.update();
|
_pTask->updateLastExecution();
|
||||||
_pTask->run();
|
_pTask->run();
|
||||||
}
|
}
|
||||||
catch (Exception& exc)
|
catch (Exception& exc)
|
||||||
|
@@ -264,7 +264,7 @@ void TimerTest::testFunc()
|
|||||||
{
|
{
|
||||||
Timer timer;
|
Timer timer;
|
||||||
|
|
||||||
int count = 0;
|
std::atomic<int> count(0);
|
||||||
timer.schedule(Timer::func([&count]()
|
timer.schedule(Timer::func([&count]()
|
||||||
{
|
{
|
||||||
count++;
|
count++;
|
||||||
|
@@ -5,4 +5,8 @@ export POCO_BASE=`pwd`
|
|||||||
export PATH=$PATH:.
|
export PATH=$PATH:.
|
||||||
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.:$POCO_BASE/lib/$osname/$osarch
|
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.:$POCO_BASE/lib/$osname/$osarch
|
||||||
export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:.:$POCO_BASE/lib/$osname/$osarch
|
export DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH:.:$POCO_BASE/lib/$osname/$osarch
|
||||||
|
if [ "TSAN" = "$1" ]
|
||||||
|
then
|
||||||
|
export TSAN_OPTIONS="suppressions=$POCO_BASE/tsan.suppress,second_deadlock_stack=1"
|
||||||
|
fi
|
||||||
build/script/runtests.sh
|
build/script/runtests.sh
|
||||||
|
25
tsan.suppress
Normal file
25
tsan.suppress
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
# Suppressed thread sanitizer tests
|
||||||
|
#
|
||||||
|
# https://github.com/google/sanitizers/wiki/ThreadSanitizerSuppressions
|
||||||
|
#
|
||||||
|
# To apply:
|
||||||
|
# export TSAN_OPTIONS="suppressions=$POCO_BASE/tsan.supress,second_deadlock_stack=1"
|
||||||
|
|
||||||
|
##############
|
||||||
|
# Suppressions:
|
||||||
|
##############
|
||||||
|
|
||||||
|
#
|
||||||
|
# Foundation
|
||||||
|
#
|
||||||
|
|
||||||
|
# ActiveDispatcher false positives
|
||||||
|
# strictly speaking, yes - ActiveDispatcher::run() is started
|
||||||
|
# in a thread before the inheriting object is fully constructed;
|
||||||
|
# however, nothing can happen there before some events are
|
||||||
|
# enqueued, which can't happen until after the inheriting object
|
||||||
|
# is fully constructed
|
||||||
|
race:ActiveDispatcherTest
|
||||||
|
race:ArchiveStrategy::moveFile
|
||||||
|
|
||||||
|
race:ThreadTest::testNotJoin
|
Reference in New Issue
Block a user