Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/ersatz_progress.hh +58 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/file.hh +133 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/fixed_array.hh +153 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/getopt.hh +33 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/joint_sort.hh +146 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/mmap.hh +192 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/multi_intersection.hh +80 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/murmur_hash.hh +18 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/read_compressed.hh +85 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/string_piece.hh +270 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/string_piece_hash.hh +43 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/thread_pool.hh +95 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/tokenize_piece.hh +151 -0
- cc-multilingual-main/cc_net/third_party/kenlm/include/util/unistd.hh +22 -0
- cc-multilingual-main/cc_net/third_party/kenlm/python/CMakeLists.txt +28 -0
- cc-multilingual-main/cc_net/third_party/kenlm/python/kenlm.pyx +288 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/CMakeLists.txt +130 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/CMakeLists.txt +27 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/LICENSE +26 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum-dtoa.cc +641 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum-dtoa.h +84 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum.cc +766 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum.h +144 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/cached-powers.cc +175 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/cached-powers.h +64 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/diy-fp.cc +57 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/diy-fp.h +118 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/double-conversion.cc +982 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/double-conversion.h +543 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fast-dtoa.cc +665 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fast-dtoa.h +88 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fixed-dtoa.cc +405 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fixed-dtoa.h +56 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/ieee.h +402 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/strtod.cc +555 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/strtod.h +45 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/utils.h +342 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/ersatz_progress.hh +64 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece.hh +223 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece_test.cc +172 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/float_to_string.cc +23 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/getopt.c +78 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/have.hh +13 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string.cc +667 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/murmur_hash.hh +18 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/parallel_read.hh +16 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/probing_hash_table_benchmark_main.cc +316 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/read_compressed_test.cc +130 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/spaces.cc +8 -0
- cc-multilingual-main/cc_net/third_party/kenlm/util/spaces.hh +12 -0
cc-multilingual-main/cc_net/third_party/kenlm/include/util/ersatz_progress.hh
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_ERSATZ_PROGRESS_H
|
2 |
+
#define UTIL_ERSATZ_PROGRESS_H
|
3 |
+
|
4 |
+
#include <iostream>
|
5 |
+
#include <string>
|
6 |
+
|
7 |
+
#include <stdint.h>
|
8 |
+
|
9 |
+
// Ersatz version of boost::progress so core language model doesn't depend on
|
10 |
+
// boost. Also adds option to print nothing.
|
11 |
+
|
12 |
+
namespace util {
|
13 |
+
|
14 |
+
extern const char kProgressBanner[];
|
15 |
+
|
16 |
+
class ErsatzProgress {
|
17 |
+
public:
|
18 |
+
// No output.
|
19 |
+
ErsatzProgress();
|
20 |
+
|
21 |
+
// Null means no output. The null value is useful for passing along the ostream pointer from another caller.
|
22 |
+
explicit ErsatzProgress(uint64_t complete, std::ostream *to = &std::cerr, const std::string &message = "");
|
23 |
+
|
24 |
+
~ErsatzProgress();
|
25 |
+
|
26 |
+
ErsatzProgress &operator++() {
|
27 |
+
if (++current_ >= next_) Milestone();
|
28 |
+
return *this;
|
29 |
+
}
|
30 |
+
|
31 |
+
ErsatzProgress &operator+=(uint64_t amount) {
|
32 |
+
if ((current_ += amount) >= next_) Milestone();
|
33 |
+
return *this;
|
34 |
+
}
|
35 |
+
|
36 |
+
void Set(uint64_t to) {
|
37 |
+
if ((current_ = to) >= next_) Milestone();
|
38 |
+
}
|
39 |
+
|
40 |
+
void Finished() {
|
41 |
+
Set(complete_);
|
42 |
+
}
|
43 |
+
|
44 |
+
private:
|
45 |
+
void Milestone();
|
46 |
+
|
47 |
+
uint64_t current_, next_, complete_;
|
48 |
+
unsigned char stones_written_;
|
49 |
+
std::ostream *out_;
|
50 |
+
|
51 |
+
// noncopyable
|
52 |
+
ErsatzProgress(const ErsatzProgress &other);
|
53 |
+
ErsatzProgress &operator=(const ErsatzProgress &other);
|
54 |
+
};
|
55 |
+
|
56 |
+
} // namespace util
|
57 |
+
|
58 |
+
#endif // UTIL_ERSATZ_PROGRESS_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/file.hh
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_FILE_H
|
2 |
+
#define UTIL_FILE_H
|
3 |
+
|
4 |
+
#include "util/exception.hh"
|
5 |
+
#include "util/scoped.hh"
|
6 |
+
#include "util/string_piece.hh"
|
7 |
+
|
8 |
+
#include <cstddef>
|
9 |
+
#include <cstdio>
|
10 |
+
#include <string>
|
11 |
+
|
12 |
+
#include <stdint.h>
|
13 |
+
|
14 |
+
namespace util {
|
15 |
+
|
16 |
+
class scoped_fd {
|
17 |
+
public:
|
18 |
+
scoped_fd() : fd_(-1) {}
|
19 |
+
|
20 |
+
explicit scoped_fd(int fd) : fd_(fd) {}
|
21 |
+
|
22 |
+
~scoped_fd();
|
23 |
+
|
24 |
+
void reset(int to = -1) {
|
25 |
+
scoped_fd other(fd_);
|
26 |
+
fd_ = to;
|
27 |
+
}
|
28 |
+
|
29 |
+
int get() const { return fd_; }
|
30 |
+
|
31 |
+
int operator*() const { return fd_; }
|
32 |
+
|
33 |
+
int release() {
|
34 |
+
int ret = fd_;
|
35 |
+
fd_ = -1;
|
36 |
+
return ret;
|
37 |
+
}
|
38 |
+
|
39 |
+
private:
|
40 |
+
int fd_;
|
41 |
+
|
42 |
+
scoped_fd(const scoped_fd &);
|
43 |
+
scoped_fd &operator=(const scoped_fd &);
|
44 |
+
};
|
45 |
+
|
46 |
+
struct scoped_FILE_closer {
|
47 |
+
static void Close(std::FILE *file);
|
48 |
+
};
|
49 |
+
typedef scoped<std::FILE, scoped_FILE_closer> scoped_FILE;
|
50 |
+
|
51 |
+
/* Thrown for any operation where the fd is known. */
|
52 |
+
class FDException : public ErrnoException {
|
53 |
+
public:
|
54 |
+
explicit FDException(int fd) throw();
|
55 |
+
|
56 |
+
virtual ~FDException() throw();
|
57 |
+
|
58 |
+
// This may no longer be valid if the exception was thrown past open.
|
59 |
+
int FD() const { return fd_; }
|
60 |
+
|
61 |
+
// Guess from NameFromFD.
|
62 |
+
const std::string &NameGuess() const { return name_guess_; }
|
63 |
+
|
64 |
+
private:
|
65 |
+
int fd_;
|
66 |
+
|
67 |
+
std::string name_guess_;
|
68 |
+
};
|
69 |
+
|
70 |
+
// End of file reached.
|
71 |
+
class EndOfFileException : public Exception {
|
72 |
+
public:
|
73 |
+
EndOfFileException() throw();
|
74 |
+
~EndOfFileException() throw();
|
75 |
+
};
|
76 |
+
|
77 |
+
// Open for read only.
|
78 |
+
int OpenReadOrThrow(const char *name);
|
79 |
+
// Create file if it doesn't exist, truncate if it does. Opened for write.
|
80 |
+
int CreateOrThrow(const char *name);
|
81 |
+
|
82 |
+
// Return value for SizeFile when it can't size properly.
|
83 |
+
const uint64_t kBadSize = (uint64_t)-1;
|
84 |
+
uint64_t SizeFile(int fd);
|
85 |
+
uint64_t SizeOrThrow(int fd);
|
86 |
+
|
87 |
+
void ResizeOrThrow(int fd, uint64_t to);
|
88 |
+
|
89 |
+
std::size_t PartialRead(int fd, void *to, std::size_t size);
|
90 |
+
void ReadOrThrow(int fd, void *to, std::size_t size);
|
91 |
+
std::size_t ReadOrEOF(int fd, void *to_void, std::size_t size);
|
92 |
+
|
93 |
+
void WriteOrThrow(int fd, const void *data_void, std::size_t size);
|
94 |
+
void WriteOrThrow(FILE *to, const void *data, std::size_t size);
|
95 |
+
|
96 |
+
/* These call pread/pwrite in a loop. However, on Windows they call ReadFile/
|
97 |
+
* WriteFile which changes the file pointer. So it's safe to call ErsatzPRead
|
98 |
+
* and ErsatzPWrite concurrently (or any combination thereof). But it changes
|
99 |
+
* the file pointer on windows, so it's not safe to call concurrently with
|
100 |
+
* anything that uses the implicit file pointer e.g. the Read/Write functions
|
101 |
+
* above.
|
102 |
+
*/
|
103 |
+
void ErsatzPRead(int fd, void *to, std::size_t size, uint64_t off);
|
104 |
+
void ErsatzPWrite(int fd, const void *data_void, std::size_t size, uint64_t off);
|
105 |
+
|
106 |
+
void FSyncOrThrow(int fd);
|
107 |
+
|
108 |
+
// Seeking
|
109 |
+
void SeekOrThrow(int fd, uint64_t off);
|
110 |
+
void AdvanceOrThrow(int fd, int64_t off);
|
111 |
+
void SeekEnd(int fd);
|
112 |
+
|
113 |
+
std::FILE *FDOpenOrThrow(scoped_fd &file);
|
114 |
+
std::FILE *FDOpenReadOrThrow(scoped_fd &file);
|
115 |
+
|
116 |
+
// Temporary files
|
117 |
+
// Append a / if base is a directory.
|
118 |
+
void NormalizeTempPrefix(std::string &base);
|
119 |
+
int MakeTemp(const StringPiece &prefix);
|
120 |
+
std::FILE *FMakeTemp(const StringPiece &prefix);
|
121 |
+
|
122 |
+
// dup an fd.
|
123 |
+
int DupOrThrow(int fd);
|
124 |
+
|
125 |
+
/* Attempt get file name from fd. This won't always work (i.e. on Windows or
|
126 |
+
* a pipe). The file might have been renamed. It's intended for diagnostics
|
127 |
+
* and logging only.
|
128 |
+
*/
|
129 |
+
std::string NameFromFD(int fd);
|
130 |
+
|
131 |
+
} // namespace util
|
132 |
+
|
133 |
+
#endif // UTIL_FILE_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/fixed_array.hh
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_FIXED_ARRAY_H
|
2 |
+
#define UTIL_FIXED_ARRAY_H
|
3 |
+
|
4 |
+
#include "util/scoped.hh"
|
5 |
+
|
6 |
+
#include <cstddef>
|
7 |
+
|
8 |
+
#include <assert.h>
|
9 |
+
#include <stdlib.h>
|
10 |
+
|
11 |
+
namespace util {
|
12 |
+
|
13 |
+
/**
|
14 |
+
* Defines a fixed-size collection.
|
15 |
+
*
|
16 |
+
* Ever want an array of things by they don't have a default constructor or are
|
17 |
+
* non-copyable? FixedArray allows constructing one at a time.
|
18 |
+
*/
|
19 |
+
template <class T> class FixedArray {
|
20 |
+
public:
|
21 |
+
/** Initialize with a given size bound but do not construct the objects. */
|
22 |
+
explicit FixedArray(std::size_t limit) {
|
23 |
+
Init(limit);
|
24 |
+
}
|
25 |
+
|
26 |
+
/**
|
27 |
+
* Constructs an instance, but does not initialize it.
|
28 |
+
*
|
29 |
+
* Any objects constructed in this manner must be subsequently @ref FixedArray::Init() "initialized" prior to use.
|
30 |
+
*
|
31 |
+
* @see FixedArray::Init()
|
32 |
+
*/
|
33 |
+
FixedArray()
|
34 |
+
: newed_end_(NULL)
|
35 |
+
#ifndef NDEBUG
|
36 |
+
, allocated_end_(NULL)
|
37 |
+
#endif
|
38 |
+
{}
|
39 |
+
|
40 |
+
/**
|
41 |
+
* Initialize with a given size bound but do not construct the objects.
|
42 |
+
*
|
43 |
+
* This method is responsible for allocating memory.
|
44 |
+
* Objects stored in this array will be constructed in a location within this allocated memory.
|
45 |
+
*/
|
46 |
+
void Init(std::size_t count) {
|
47 |
+
assert(!block_.get());
|
48 |
+
block_.reset(malloc(sizeof(T) * count));
|
49 |
+
if (!block_.get()) throw std::bad_alloc();
|
50 |
+
newed_end_ = begin();
|
51 |
+
#ifndef NDEBUG
|
52 |
+
allocated_end_ = begin() + count;
|
53 |
+
#endif
|
54 |
+
}
|
55 |
+
|
56 |
+
/**
|
57 |
+
* Constructs a copy of the provided array.
|
58 |
+
*
|
59 |
+
* @param from Array whose elements should be copied into this newly-constructed data structure.
|
60 |
+
*/
|
61 |
+
FixedArray(const FixedArray &from) {
|
62 |
+
std::size_t size = from.newed_end_ - static_cast<const T*>(from.block_.get());
|
63 |
+
Init(size);
|
64 |
+
for (std::size_t i = 0; i < size; ++i) {
|
65 |
+
push_back(from[i]);
|
66 |
+
}
|
67 |
+
}
|
68 |
+
|
69 |
+
/**
|
70 |
+
* Frees the memory held by this object.
|
71 |
+
*/
|
72 |
+
~FixedArray() { clear(); }
|
73 |
+
|
74 |
+
/** Gets a pointer to the first object currently stored in this data structure. */
|
75 |
+
T *begin() { return static_cast<T*>(block_.get()); }
|
76 |
+
|
77 |
+
/** Gets a const pointer to the last object currently stored in this data structure. */
|
78 |
+
const T *begin() const { return static_cast<const T*>(block_.get()); }
|
79 |
+
|
80 |
+
/** Gets a pointer to the last object currently stored in this data structure. */
|
81 |
+
T *end() { return newed_end_; }
|
82 |
+
|
83 |
+
/** Gets a const pointer to the last object currently stored in this data structure. */
|
84 |
+
const T *end() const { return newed_end_; }
|
85 |
+
|
86 |
+
/** Gets a reference to the last object currently stored in this data structure. */
|
87 |
+
T &back() { return *(end() - 1); }
|
88 |
+
|
89 |
+
/** Gets a const reference to the last object currently stored in this data structure. */
|
90 |
+
const T &back() const { return *(end() - 1); }
|
91 |
+
|
92 |
+
/** Gets the number of objects currently stored in this data structure. */
|
93 |
+
std::size_t size() const { return end() - begin(); }
|
94 |
+
|
95 |
+
/** Returns true if there are no objects currently stored in this data structure. */
|
96 |
+
bool empty() const { return begin() == end(); }
|
97 |
+
|
98 |
+
/**
|
99 |
+
* Gets a reference to the object with index i currently stored in this data structure.
|
100 |
+
*
|
101 |
+
* @param i Index of the object to reference
|
102 |
+
*/
|
103 |
+
T &operator[](std::size_t i) { return begin()[i]; }
|
104 |
+
|
105 |
+
/**
|
106 |
+
* Gets a const reference to the object with index i currently stored in this data structure.
|
107 |
+
*
|
108 |
+
* @param i Index of the object to reference
|
109 |
+
*/
|
110 |
+
const T &operator[](std::size_t i) const { return begin()[i]; }
|
111 |
+
|
112 |
+
/**
|
113 |
+
* Constructs a new object using the provided parameter,
|
114 |
+
* and stores it in this data structure.
|
115 |
+
*
|
116 |
+
* The memory backing the constructed object is managed by this data structure.
|
117 |
+
*/
|
118 |
+
template <class C> void push_back(const C &c) {
|
119 |
+
new (end()) T(c); // use "placement new" syntax to initalize T in an already-allocated memory location
|
120 |
+
Constructed();
|
121 |
+
}
|
122 |
+
|
123 |
+
/**
|
124 |
+
* Removes all elements from this array.
|
125 |
+
*/
|
126 |
+
void clear() {
|
127 |
+
for (T *i = begin(); i != end(); ++i)
|
128 |
+
i->~T();
|
129 |
+
newed_end_ = begin();
|
130 |
+
}
|
131 |
+
|
132 |
+
protected:
|
133 |
+
// Always call Constructed after successful completion of new.
|
134 |
+
void Constructed() {
|
135 |
+
++newed_end_;
|
136 |
+
#ifndef NDEBUG
|
137 |
+
assert(newed_end_ <= allocated_end_);
|
138 |
+
#endif
|
139 |
+
}
|
140 |
+
|
141 |
+
private:
|
142 |
+
util::scoped_malloc block_;
|
143 |
+
|
144 |
+
T *newed_end_;
|
145 |
+
|
146 |
+
#ifndef NDEBUG
|
147 |
+
T *allocated_end_;
|
148 |
+
#endif
|
149 |
+
};
|
150 |
+
|
151 |
+
} // namespace util
|
152 |
+
|
153 |
+
#endif // UTIL_FIXED_ARRAY_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/getopt.hh
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
POSIX getopt for Windows
|
3 |
+
|
4 |
+
AT&T Public License
|
5 |
+
|
6 |
+
Code given out at the 1985 UNIFORUM conference in Dallas.
|
7 |
+
*/
|
8 |
+
|
9 |
+
#ifdef __GNUC__
|
10 |
+
#include <getopt.h>
|
11 |
+
#endif
|
12 |
+
#ifndef __GNUC__
|
13 |
+
|
14 |
+
#ifndef UTIL_GETOPT_H
|
15 |
+
#define UTIL_GETOPT_H
|
16 |
+
|
17 |
+
#ifdef __cplusplus
|
18 |
+
extern "C" {
|
19 |
+
#endif
|
20 |
+
|
21 |
+
extern int opterr;
|
22 |
+
extern int optind;
|
23 |
+
extern int optopt;
|
24 |
+
extern char *optarg;
|
25 |
+
extern int getopt(int argc, char **argv, char *opts);
|
26 |
+
|
27 |
+
#ifdef __cplusplus
|
28 |
+
}
|
29 |
+
#endif
|
30 |
+
|
31 |
+
#endif /* UTIL_GETOPT_H */
|
32 |
+
#endif /* __GNUC__ */
|
33 |
+
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/joint_sort.hh
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_JOINT_SORT_H
|
2 |
+
#define UTIL_JOINT_SORT_H
|
3 |
+
|
4 |
+
/* A terrifying amount of C++ to coax std::sort into soring one range while
|
5 |
+
* also permuting another range the same way.
|
6 |
+
*/
|
7 |
+
|
8 |
+
#include "util/proxy_iterator.hh"
|
9 |
+
|
10 |
+
#include <algorithm>
|
11 |
+
#include <functional>
|
12 |
+
|
13 |
+
namespace util {
|
14 |
+
|
15 |
+
namespace detail {
|
16 |
+
|
17 |
+
template <class KeyIter, class ValueIter> class JointProxy;
|
18 |
+
|
19 |
+
template <class KeyIter, class ValueIter> class JointIter {
|
20 |
+
public:
|
21 |
+
JointIter() {}
|
22 |
+
|
23 |
+
JointIter(const KeyIter &key_iter, const ValueIter &value_iter) : key_(key_iter), value_(value_iter) {}
|
24 |
+
|
25 |
+
bool operator==(const JointIter<KeyIter, ValueIter> &other) const { return key_ == other.key_; }
|
26 |
+
|
27 |
+
bool operator<(const JointIter<KeyIter, ValueIter> &other) const { return (key_ < other.key_); }
|
28 |
+
|
29 |
+
std::ptrdiff_t operator-(const JointIter<KeyIter, ValueIter> &other) const { return key_ - other.key_; }
|
30 |
+
|
31 |
+
JointIter<KeyIter, ValueIter> &operator+=(std::ptrdiff_t amount) {
|
32 |
+
key_ += amount;
|
33 |
+
value_ += amount;
|
34 |
+
return *this;
|
35 |
+
}
|
36 |
+
|
37 |
+
friend void swap(JointIter &first, JointIter &second) {
|
38 |
+
using std::swap;
|
39 |
+
swap(first.key_, second.key_);
|
40 |
+
swap(first.value_, second.value_);
|
41 |
+
}
|
42 |
+
|
43 |
+
void DeepSwap(JointIter &other) {
|
44 |
+
using std::swap;
|
45 |
+
swap(*key_, *other.key_);
|
46 |
+
swap(*value_, *other.value_);
|
47 |
+
}
|
48 |
+
|
49 |
+
private:
|
50 |
+
friend class JointProxy<KeyIter, ValueIter>;
|
51 |
+
KeyIter key_;
|
52 |
+
ValueIter value_;
|
53 |
+
};
|
54 |
+
|
55 |
+
template <class KeyIter, class ValueIter> class JointProxy {
|
56 |
+
private:
|
57 |
+
typedef JointIter<KeyIter, ValueIter> InnerIterator;
|
58 |
+
|
59 |
+
public:
|
60 |
+
typedef struct {
|
61 |
+
typename std::iterator_traits<KeyIter>::value_type key;
|
62 |
+
typename std::iterator_traits<ValueIter>::value_type value;
|
63 |
+
const typename std::iterator_traits<KeyIter>::value_type &GetKey() const { return key; }
|
64 |
+
} value_type;
|
65 |
+
|
66 |
+
JointProxy(const KeyIter &key_iter, const ValueIter &value_iter) : inner_(key_iter, value_iter) {}
|
67 |
+
JointProxy(const JointProxy<KeyIter, ValueIter> &other) : inner_(other.inner_) {}
|
68 |
+
|
69 |
+
operator value_type() const {
|
70 |
+
value_type ret;
|
71 |
+
ret.key = *inner_.key_;
|
72 |
+
ret.value = *inner_.value_;
|
73 |
+
return ret;
|
74 |
+
}
|
75 |
+
|
76 |
+
JointProxy &operator=(const JointProxy &other) {
|
77 |
+
*inner_.key_ = *other.inner_.key_;
|
78 |
+
*inner_.value_ = *other.inner_.value_;
|
79 |
+
return *this;
|
80 |
+
}
|
81 |
+
|
82 |
+
JointProxy &operator=(const value_type &other) {
|
83 |
+
*inner_.key_ = other.key;
|
84 |
+
*inner_.value_ = other.value;
|
85 |
+
return *this;
|
86 |
+
}
|
87 |
+
|
88 |
+
typename std::iterator_traits<KeyIter>::reference GetKey() const {
|
89 |
+
return *(inner_.key_);
|
90 |
+
}
|
91 |
+
|
92 |
+
friend void swap(JointProxy<KeyIter, ValueIter> first, JointProxy<KeyIter, ValueIter> second) {
|
93 |
+
first.Inner().DeepSwap(second.Inner());
|
94 |
+
}
|
95 |
+
|
96 |
+
private:
|
97 |
+
friend class ProxyIterator<JointProxy<KeyIter, ValueIter> >;
|
98 |
+
|
99 |
+
InnerIterator &Inner() { return inner_; }
|
100 |
+
const InnerIterator &Inner() const { return inner_; }
|
101 |
+
InnerIterator inner_;
|
102 |
+
};
|
103 |
+
|
104 |
+
template <class Proxy, class Less> class LessWrapper : public std::binary_function<const typename Proxy::value_type &, const typename Proxy::value_type &, bool> {
|
105 |
+
public:
|
106 |
+
explicit LessWrapper(const Less &less) : less_(less) {}
|
107 |
+
|
108 |
+
bool operator()(const Proxy &left, const Proxy &right) const {
|
109 |
+
return less_(left.GetKey(), right.GetKey());
|
110 |
+
}
|
111 |
+
bool operator()(const Proxy &left, const typename Proxy::value_type &right) const {
|
112 |
+
return less_(left.GetKey(), right.GetKey());
|
113 |
+
}
|
114 |
+
bool operator()(const typename Proxy::value_type &left, const Proxy &right) const {
|
115 |
+
return less_(left.GetKey(), right.GetKey());
|
116 |
+
}
|
117 |
+
bool operator()(const typename Proxy::value_type &left, const typename Proxy::value_type &right) const {
|
118 |
+
return less_(left.GetKey(), right.GetKey());
|
119 |
+
}
|
120 |
+
|
121 |
+
private:
|
122 |
+
const Less less_;
|
123 |
+
};
|
124 |
+
|
125 |
+
} // namespace detail
|
126 |
+
|
127 |
+
template <class KeyIter, class ValueIter> class PairedIterator : public ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > {
|
128 |
+
public:
|
129 |
+
PairedIterator(const KeyIter &key, const ValueIter &value) :
|
130 |
+
ProxyIterator<detail::JointProxy<KeyIter, ValueIter> >(detail::JointProxy<KeyIter, ValueIter>(key, value)) {}
|
131 |
+
};
|
132 |
+
|
133 |
+
template <class KeyIter, class ValueIter, class Less> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin, const Less &less) {
|
134 |
+
ProxyIterator<detail::JointProxy<KeyIter, ValueIter> > full_begin(detail::JointProxy<KeyIter, ValueIter>(key_begin, value_begin));
|
135 |
+
detail::LessWrapper<detail::JointProxy<KeyIter, ValueIter>, Less> less_wrap(less);
|
136 |
+
std::sort(full_begin, full_begin + (key_end - key_begin), less_wrap);
|
137 |
+
}
|
138 |
+
|
139 |
+
|
140 |
+
template <class KeyIter, class ValueIter> void JointSort(const KeyIter &key_begin, const KeyIter &key_end, const ValueIter &value_begin) {
|
141 |
+
JointSort(key_begin, key_end, value_begin, std::less<typename std::iterator_traits<KeyIter>::value_type>());
|
142 |
+
}
|
143 |
+
|
144 |
+
} // namespace util
|
145 |
+
|
146 |
+
#endif // UTIL_JOINT_SORT_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/mmap.hh
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_MMAP_H
|
2 |
+
#define UTIL_MMAP_H
|
3 |
+
// Utilities for mmaped files.
|
4 |
+
|
5 |
+
#include <cstddef>
|
6 |
+
#include <limits>
|
7 |
+
|
8 |
+
#include <stdint.h>
|
9 |
+
#include <sys/types.h>
|
10 |
+
|
11 |
+
namespace util {
|
12 |
+
|
13 |
+
class scoped_fd;
|
14 |
+
|
15 |
+
long SizePage();
|
16 |
+
|
17 |
+
// (void*)-1 is MAP_FAILED; this is done to avoid including the mmap header here.
|
18 |
+
class scoped_mmap {
|
19 |
+
public:
|
20 |
+
scoped_mmap() : data_((void*)-1), size_(0) {}
|
21 |
+
scoped_mmap(void *data, std::size_t size) : data_(data), size_(size) {}
|
22 |
+
~scoped_mmap();
|
23 |
+
|
24 |
+
void *get() const { return data_; }
|
25 |
+
|
26 |
+
const uint8_t *begin() const { return reinterpret_cast<uint8_t*>(data_); }
|
27 |
+
const uint8_t *end() const { return reinterpret_cast<uint8_t*>(data_) + size_; }
|
28 |
+
std::size_t size() const { return size_; }
|
29 |
+
|
30 |
+
void reset(void *data, std::size_t size) {
|
31 |
+
scoped_mmap other(data_, size_);
|
32 |
+
data_ = data;
|
33 |
+
size_ = size;
|
34 |
+
}
|
35 |
+
|
36 |
+
void reset() {
|
37 |
+
reset((void*)-1, 0);
|
38 |
+
}
|
39 |
+
|
40 |
+
private:
|
41 |
+
void *data_;
|
42 |
+
std::size_t size_;
|
43 |
+
|
44 |
+
scoped_mmap(const scoped_mmap &);
|
45 |
+
scoped_mmap &operator=(const scoped_mmap &);
|
46 |
+
};
|
47 |
+
|
48 |
+
/* For when the memory might come from mmap, new char[], or malloc. Uses NULL
|
49 |
+
* and 0 for blanks even though mmap signals errors with (void*)-1). The reset
|
50 |
+
* function checks that blank for mmap.
|
51 |
+
*/
|
52 |
+
class scoped_memory {
|
53 |
+
public:
|
54 |
+
typedef enum {MMAP_ALLOCATED, ARRAY_ALLOCATED, MALLOC_ALLOCATED, NONE_ALLOCATED} Alloc;
|
55 |
+
|
56 |
+
scoped_memory(void *data, std::size_t size, Alloc source)
|
57 |
+
: data_(data), size_(size), source_(source) {}
|
58 |
+
|
59 |
+
scoped_memory() : data_(NULL), size_(0), source_(NONE_ALLOCATED) {}
|
60 |
+
|
61 |
+
~scoped_memory() { reset(); }
|
62 |
+
|
63 |
+
void *get() const { return data_; }
|
64 |
+
const char *begin() const { return reinterpret_cast<char*>(data_); }
|
65 |
+
const char *end() const { return reinterpret_cast<char*>(data_) + size_; }
|
66 |
+
std::size_t size() const { return size_; }
|
67 |
+
|
68 |
+
Alloc source() const { return source_; }
|
69 |
+
|
70 |
+
void reset() { reset(NULL, 0, NONE_ALLOCATED); }
|
71 |
+
|
72 |
+
void reset(void *data, std::size_t size, Alloc from);
|
73 |
+
|
74 |
+
// realloc allows the current data to escape hence the need for this call
|
75 |
+
// If realloc fails, destroys the original too and get() returns NULL.
|
76 |
+
void call_realloc(std::size_t to);
|
77 |
+
|
78 |
+
private:
|
79 |
+
void *data_;
|
80 |
+
std::size_t size_;
|
81 |
+
|
82 |
+
Alloc source_;
|
83 |
+
|
84 |
+
scoped_memory(const scoped_memory &);
|
85 |
+
scoped_memory &operator=(const scoped_memory &);
|
86 |
+
};
|
87 |
+
|
88 |
+
typedef enum {
|
89 |
+
// mmap with no prepopulate
|
90 |
+
LAZY,
|
91 |
+
// On linux, pass MAP_POPULATE to mmap.
|
92 |
+
POPULATE_OR_LAZY,
|
93 |
+
// Populate on Linux. malloc and read on non-Linux.
|
94 |
+
POPULATE_OR_READ,
|
95 |
+
// malloc and read.
|
96 |
+
READ,
|
97 |
+
// malloc and read in parallel (recommended for Lustre)
|
98 |
+
PARALLEL_READ,
|
99 |
+
} LoadMethod;
|
100 |
+
|
101 |
+
extern const int kFileFlags;
|
102 |
+
|
103 |
+
// Wrapper around mmap to check it worked and hide some platform macros.
|
104 |
+
void *MapOrThrow(std::size_t size, bool for_write, int flags, bool prefault, int fd, uint64_t offset = 0);
|
105 |
+
|
106 |
+
void MapRead(LoadMethod method, int fd, uint64_t offset, std::size_t size, scoped_memory &out);
|
107 |
+
|
108 |
+
void MapAnonymous(std::size_t size, scoped_memory &to);
|
109 |
+
|
110 |
+
// Open file name with mmap of size bytes, all of which are initially zero.
|
111 |
+
void *MapZeroedWrite(int fd, std::size_t size);
|
112 |
+
void *MapZeroedWrite(const char *name, std::size_t size, scoped_fd &file);
|
113 |
+
|
114 |
+
// msync wrapper
|
115 |
+
void SyncOrThrow(void *start, size_t length);
|
116 |
+
|
117 |
+
// Forward rolling memory map with no overlap.
|
118 |
+
class Rolling {
|
119 |
+
public:
|
120 |
+
Rolling() {}
|
121 |
+
|
122 |
+
explicit Rolling(void *data) { Init(data); }
|
123 |
+
|
124 |
+
Rolling(const Rolling ©_from, uint64_t increase = 0);
|
125 |
+
Rolling &operator=(const Rolling ©_from);
|
126 |
+
|
127 |
+
// For an actual rolling mmap.
|
128 |
+
explicit Rolling(int fd, bool for_write, std::size_t block, std::size_t read_bound, uint64_t offset, uint64_t amount);
|
129 |
+
|
130 |
+
// For a static mapping
|
131 |
+
void Init(void *data) {
|
132 |
+
ptr_ = data;
|
133 |
+
current_end_ = std::numeric_limits<uint64_t>::max();
|
134 |
+
current_begin_ = 0;
|
135 |
+
// Mark as a pass-through.
|
136 |
+
fd_ = -1;
|
137 |
+
}
|
138 |
+
|
139 |
+
void IncreaseBase(uint64_t by) {
|
140 |
+
file_begin_ += by;
|
141 |
+
ptr_ = static_cast<uint8_t*>(ptr_) + by;
|
142 |
+
if (!IsPassthrough()) current_end_ = 0;
|
143 |
+
}
|
144 |
+
|
145 |
+
void DecreaseBase(uint64_t by) {
|
146 |
+
file_begin_ -= by;
|
147 |
+
ptr_ = static_cast<uint8_t*>(ptr_) - by;
|
148 |
+
if (!IsPassthrough()) current_end_ = 0;
|
149 |
+
}
|
150 |
+
|
151 |
+
void *ExtractNonRolling(scoped_memory &out, uint64_t index, std::size_t size);
|
152 |
+
|
153 |
+
// Returns base pointer
|
154 |
+
void *get() const { return ptr_; }
|
155 |
+
|
156 |
+
// Returns base pointer.
|
157 |
+
void *CheckedBase(uint64_t index) {
|
158 |
+
if (index >= current_end_ || index < current_begin_) {
|
159 |
+
Roll(index);
|
160 |
+
}
|
161 |
+
return ptr_;
|
162 |
+
}
|
163 |
+
|
164 |
+
// Returns indexed pointer.
|
165 |
+
void *CheckedIndex(uint64_t index) {
|
166 |
+
return static_cast<uint8_t*>(CheckedBase(index)) + index;
|
167 |
+
}
|
168 |
+
|
169 |
+
private:
|
170 |
+
void Roll(uint64_t index);
|
171 |
+
|
172 |
+
// True if this is just a thin wrapper on a pointer.
|
173 |
+
bool IsPassthrough() const { return fd_ == -1; }
|
174 |
+
|
175 |
+
void *ptr_;
|
176 |
+
uint64_t current_begin_;
|
177 |
+
uint64_t current_end_;
|
178 |
+
|
179 |
+
scoped_memory mem_;
|
180 |
+
|
181 |
+
int fd_;
|
182 |
+
uint64_t file_begin_;
|
183 |
+
uint64_t file_end_;
|
184 |
+
|
185 |
+
bool for_write_;
|
186 |
+
std::size_t block_;
|
187 |
+
std::size_t read_bound_;
|
188 |
+
};
|
189 |
+
|
190 |
+
} // namespace util
|
191 |
+
|
192 |
+
#endif // UTIL_MMAP_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/multi_intersection.hh
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_MULTI_INTERSECTION_H
|
2 |
+
#define UTIL_MULTI_INTERSECTION_H
|
3 |
+
|
4 |
+
#include <boost/optional.hpp>
|
5 |
+
#include <boost/range/iterator_range.hpp>
|
6 |
+
|
7 |
+
#include <algorithm>
|
8 |
+
#include <functional>
|
9 |
+
#include <vector>
|
10 |
+
|
11 |
+
namespace util {
|
12 |
+
|
13 |
+
namespace detail {
|
14 |
+
template <class Range> struct RangeLessBySize : public std::binary_function<const Range &, const Range &, bool> {
|
15 |
+
bool operator()(const Range &left, const Range &right) const {
|
16 |
+
return left.size() < right.size();
|
17 |
+
}
|
18 |
+
};
|
19 |
+
|
20 |
+
/* Takes sets specified by their iterators and a boost::optional containing
|
21 |
+
* the lowest intersection if any. Each set must be sorted in increasing
|
22 |
+
* order. sets is changed to truncate the beginning of each sequence to the
|
23 |
+
* location of the match or an empty set. Precondition: sets is not empty
|
24 |
+
* since the intersection over null is the universe and this function does not
|
25 |
+
* know the universe.
|
26 |
+
*/
|
27 |
+
template <class Iterator, class Less> boost::optional<typename std::iterator_traits<Iterator>::value_type> FirstIntersectionSorted(std::vector<boost::iterator_range<Iterator> > &sets, const Less &less = std::less<typename std::iterator_traits<Iterator>::value_type>()) {
|
28 |
+
typedef std::vector<boost::iterator_range<Iterator> > Sets;
|
29 |
+
typedef typename std::iterator_traits<Iterator>::value_type Value;
|
30 |
+
|
31 |
+
assert(!sets.empty());
|
32 |
+
|
33 |
+
if (sets.front().empty()) return boost::optional<Value>();
|
34 |
+
// Possibly suboptimal to copy for general Value; makes unsigned int go slightly faster.
|
35 |
+
Value highest(sets.front().front());
|
36 |
+
for (typename Sets::iterator i(sets.begin()); i != sets.end(); ) {
|
37 |
+
i->advance_begin(std::lower_bound(i->begin(), i->end(), highest, less) - i->begin());
|
38 |
+
if (i->empty()) return boost::optional<Value>();
|
39 |
+
if (less(highest, i->front())) {
|
40 |
+
highest = i->front();
|
41 |
+
// start over
|
42 |
+
i = sets.begin();
|
43 |
+
} else {
|
44 |
+
++i;
|
45 |
+
}
|
46 |
+
}
|
47 |
+
return boost::optional<Value>(highest);
|
48 |
+
}
|
49 |
+
|
50 |
+
} // namespace detail
|
51 |
+
|
52 |
+
template <class Iterator, class Less> boost::optional<typename std::iterator_traits<Iterator>::value_type> FirstIntersection(std::vector<boost::iterator_range<Iterator> > &sets, const Less less) {
|
53 |
+
assert(!sets.empty());
|
54 |
+
|
55 |
+
std::sort(sets.begin(), sets.end(), detail::RangeLessBySize<boost::iterator_range<Iterator> >());
|
56 |
+
return detail::FirstIntersectionSorted(sets, less);
|
57 |
+
}
|
58 |
+
|
59 |
+
template <class Iterator> boost::optional<typename std::iterator_traits<Iterator>::value_type> FirstIntersection(std::vector<boost::iterator_range<Iterator> > &sets) {
|
60 |
+
return FirstIntersection(sets, std::less<typename std::iterator_traits<Iterator>::value_type>());
|
61 |
+
}
|
62 |
+
|
63 |
+
template <class Iterator, class Output, class Less> void AllIntersection(std::vector<boost::iterator_range<Iterator> > &sets, Output &out, const Less less) {
|
64 |
+
typedef typename std::iterator_traits<Iterator>::value_type Value;
|
65 |
+
assert(!sets.empty());
|
66 |
+
|
67 |
+
std::sort(sets.begin(), sets.end(), detail::RangeLessBySize<boost::iterator_range<Iterator> >());
|
68 |
+
boost::optional<Value> ret;
|
69 |
+
for (boost::optional<Value> ret; (ret = detail::FirstIntersectionSorted(sets, less)); sets.front().advance_begin(1)) {
|
70 |
+
out(*ret);
|
71 |
+
}
|
72 |
+
}
|
73 |
+
|
74 |
+
template <class Iterator, class Output> void AllIntersection(std::vector<boost::iterator_range<Iterator> > &sets, Output &out) {
|
75 |
+
AllIntersection(sets, out, std::less<typename std::iterator_traits<Iterator>::value_type>());
|
76 |
+
}
|
77 |
+
|
78 |
+
} // namespace util
|
79 |
+
|
80 |
+
#endif // UTIL_MULTI_INTERSECTION_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/murmur_hash.hh
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_MURMUR_HASH_H
|
2 |
+
#define UTIL_MURMUR_HASH_H
|
3 |
+
#include <cstddef>
|
4 |
+
#include <stdint.h>
|
5 |
+
|
6 |
+
namespace util {
|
7 |
+
|
8 |
+
// 64-bit machine version
|
9 |
+
uint64_t MurmurHash64A(const void * key, std::size_t len, uint64_t seed = 0);
|
10 |
+
// 32-bit machine version (not the same function as above)
|
11 |
+
uint64_t MurmurHash64B(const void * key, std::size_t len, uint64_t seed = 0);
|
12 |
+
// Use the version for this arch. Because the values differ across
|
13 |
+
// architectures, really only use it for in-memory structures.
|
14 |
+
uint64_t MurmurHashNative(const void * key, std::size_t len, uint64_t seed = 0);
|
15 |
+
|
16 |
+
} // namespace util
|
17 |
+
|
18 |
+
#endif // UTIL_MURMUR_HASH_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/read_compressed.hh
ADDED
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_READ_COMPRESSED_H
|
2 |
+
#define UTIL_READ_COMPRESSED_H
|
3 |
+
|
4 |
+
#include "util/exception.hh"
|
5 |
+
#include "util/scoped.hh"
|
6 |
+
|
7 |
+
#include <cstddef>
|
8 |
+
|
9 |
+
#include <stdint.h>
|
10 |
+
|
11 |
+
namespace util {
|
12 |
+
|
13 |
+
class CompressedException : public Exception {
|
14 |
+
public:
|
15 |
+
CompressedException() throw();
|
16 |
+
virtual ~CompressedException() throw();
|
17 |
+
};
|
18 |
+
|
19 |
+
class GZException : public CompressedException {
|
20 |
+
public:
|
21 |
+
GZException() throw();
|
22 |
+
~GZException() throw();
|
23 |
+
};
|
24 |
+
|
25 |
+
class BZException : public CompressedException {
|
26 |
+
public:
|
27 |
+
BZException() throw();
|
28 |
+
~BZException() throw();
|
29 |
+
};
|
30 |
+
|
31 |
+
class XZException : public CompressedException {
|
32 |
+
public:
|
33 |
+
XZException() throw();
|
34 |
+
~XZException() throw();
|
35 |
+
};
|
36 |
+
|
37 |
+
class ReadBase;
|
38 |
+
|
39 |
+
class ReadCompressed {
|
40 |
+
public:
|
41 |
+
static const std::size_t kMagicSize = 6;
|
42 |
+
// Must have at least kMagicSize bytes.
|
43 |
+
static bool DetectCompressedMagic(const void *from);
|
44 |
+
|
45 |
+
// Takes ownership of fd.
|
46 |
+
explicit ReadCompressed(int fd);
|
47 |
+
|
48 |
+
// Try to avoid using this. Use the fd instead.
|
49 |
+
// There is no decompression support for istreams.
|
50 |
+
explicit ReadCompressed(std::istream &in);
|
51 |
+
|
52 |
+
// Must call Reset later.
|
53 |
+
ReadCompressed();
|
54 |
+
|
55 |
+
~ReadCompressed();
|
56 |
+
|
57 |
+
// Takes ownership of fd.
|
58 |
+
void Reset(int fd);
|
59 |
+
|
60 |
+
// Same advice as the constructor.
|
61 |
+
void Reset(std::istream &in);
|
62 |
+
|
63 |
+
std::size_t Read(void *to, std::size_t amount);
|
64 |
+
|
65 |
+
// Repeatedly call read to fill a buffer unless EOF is hit.
|
66 |
+
// Return number of bytes read.
|
67 |
+
std::size_t ReadOrEOF(void *const to, std::size_t amount);
|
68 |
+
|
69 |
+
uint64_t RawAmount() const { return raw_amount_; }
|
70 |
+
|
71 |
+
private:
|
72 |
+
friend class ReadBase;
|
73 |
+
|
74 |
+
scoped_ptr<ReadBase> internal_;
|
75 |
+
|
76 |
+
uint64_t raw_amount_;
|
77 |
+
|
78 |
+
// No copying.
|
79 |
+
ReadCompressed(const ReadCompressed &);
|
80 |
+
void operator=(const ReadCompressed &);
|
81 |
+
};
|
82 |
+
|
83 |
+
} // namespace util
|
84 |
+
|
85 |
+
#endif // UTIL_READ_COMPRESSED_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/string_piece.hh
ADDED
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* If you use ICU in your program, then compile with -DHAVE_ICU -licui18n. If
|
2 |
+
* you don't use ICU, then this will use the Google implementation from Chrome.
|
3 |
+
* This has been modified from the original version to let you choose.
|
4 |
+
*/
|
5 |
+
|
6 |
+
// Copyright 2008, Google Inc.
|
7 |
+
// All rights reserved.
|
8 |
+
//
|
9 |
+
// Redistribution and use in source and binary forms, with or without
|
10 |
+
// modification, are permitted provided that the following conditions are
|
11 |
+
// met:
|
12 |
+
//
|
13 |
+
// * Redistributions of source code must retain the above copyright
|
14 |
+
// notice, this list of conditions and the following disclaimer.
|
15 |
+
// * Redistributions in binary form must reproduce the above
|
16 |
+
// copyright notice, this list of conditions and the following disclaimer
|
17 |
+
// in the documentation and/or other materials provided with the
|
18 |
+
// distribution.
|
19 |
+
// * Neither the name of Google Inc. nor the names of its
|
20 |
+
// contributors may be used to endorse or promote products derived from
|
21 |
+
// this software without specific prior written permission.
|
22 |
+
//
|
23 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
24 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
25 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
26 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
27 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
28 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
29 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
30 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
31 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
32 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
33 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
34 |
+
// Copied from strings/stringpiece.h with modifications
|
35 |
+
//
|
36 |
+
// A string-like object that points to a sized piece of memory.
|
37 |
+
//
|
38 |
+
// Functions or methods may use const StringPiece& parameters to accept either
|
39 |
+
// a "const char*" or a "string" value that will be implicitly converted to
|
40 |
+
// a StringPiece. The implicit conversion means that it is often appropriate
|
41 |
+
// to include this .h file in other files rather than forward-declaring
|
42 |
+
// StringPiece as would be appropriate for most other Google classes.
|
43 |
+
//
|
44 |
+
// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
|
45 |
+
// conversions from "const char*" to "string" and back again.
|
46 |
+
//
|
47 |
+
|
48 |
+
#ifndef UTIL_STRING_PIECE_H
|
49 |
+
#define UTIL_STRING_PIECE_H
|
50 |
+
|
51 |
+
#include "util/have.hh"
|
52 |
+
|
53 |
+
#include <cstring>
|
54 |
+
#include <iosfwd>
|
55 |
+
#include <ostream>
|
56 |
+
|
57 |
+
#ifdef HAVE_ICU
|
58 |
+
#include <unicode/stringpiece.h>
|
59 |
+
#include <unicode/uversion.h>
|
60 |
+
|
61 |
+
// Old versions of ICU don't define operator== and operator!=.
|
62 |
+
#if (U_ICU_VERSION_MAJOR_NUM < 4) || ((U_ICU_VERSION_MAJOR_NUM == 4) && (U_ICU_VERSION_MINOR_NUM < 4))
|
63 |
+
#warning You are using an old version of ICU. Consider upgrading to ICU >= 4.6.
|
64 |
+
inline bool operator==(const StringPiece& x, const StringPiece& y) {
|
65 |
+
if (x.size() != y.size())
|
66 |
+
return false;
|
67 |
+
|
68 |
+
return std::memcmp(x.data(), y.data(), x.size()) == 0;
|
69 |
+
}
|
70 |
+
|
71 |
+
inline bool operator!=(const StringPiece& x, const StringPiece& y) {
|
72 |
+
return !(x == y);
|
73 |
+
}
|
74 |
+
#endif // old version of ICU
|
75 |
+
|
76 |
+
U_NAMESPACE_BEGIN
|
77 |
+
|
78 |
+
inline bool starts_with(const StringPiece& longer, const StringPiece& prefix) {
|
79 |
+
int longersize = longer.size(), prefixsize = prefix.size();
|
80 |
+
return longersize >= prefixsize && std::memcmp(longer.data(), prefix.data(), prefixsize) == 0;
|
81 |
+
}
|
82 |
+
|
83 |
+
#else
|
84 |
+
|
85 |
+
#include <algorithm>
|
86 |
+
#include <cstddef>
|
87 |
+
#include <string>
|
88 |
+
#include <string.h>
|
89 |
+
|
90 |
+
#ifdef WIN32
|
91 |
+
#undef max
|
92 |
+
#undef min
|
93 |
+
#endif
|
94 |
+
|
95 |
+
class StringPiece {
|
96 |
+
public:
|
97 |
+
typedef size_t size_type;
|
98 |
+
|
99 |
+
private:
|
100 |
+
const char* ptr_;
|
101 |
+
size_type length_;
|
102 |
+
|
103 |
+
public:
|
104 |
+
// We provide non-explicit singleton constructors so users can pass
|
105 |
+
// in a "const char*" or a "string" wherever a "StringPiece" is
|
106 |
+
// expected.
|
107 |
+
StringPiece() : ptr_(NULL), length_(0) { }
|
108 |
+
StringPiece(const char* str)
|
109 |
+
: ptr_(str), length_((str == NULL) ? 0 : strlen(str)) { }
|
110 |
+
StringPiece(const std::string& str)
|
111 |
+
: ptr_(str.data()), length_(str.size()) { }
|
112 |
+
StringPiece(const char* offset, size_type len)
|
113 |
+
: ptr_(offset), length_(len) { }
|
114 |
+
|
115 |
+
// data() may return a pointer to a buffer with embedded NULs, and the
|
116 |
+
// returned buffer may or may not be null terminated. Therefore it is
|
117 |
+
// typically a mistake to pass data() to a routine that expects a NUL
|
118 |
+
// terminated string.
|
119 |
+
const char* data() const { return ptr_; }
|
120 |
+
size_type size() const { return length_; }
|
121 |
+
size_type length() const { return length_; }
|
122 |
+
bool empty() const { return length_ == 0; }
|
123 |
+
|
124 |
+
void clear() { ptr_ = NULL; length_ = 0; }
|
125 |
+
void set(const char* data, size_type len) { ptr_ = data; length_ = len; }
|
126 |
+
void set(const char* str) {
|
127 |
+
ptr_ = str;
|
128 |
+
length_ = str ? strlen(str) : 0;
|
129 |
+
}
|
130 |
+
void set(const void* data, size_type len) {
|
131 |
+
ptr_ = reinterpret_cast<const char*>(data);
|
132 |
+
length_ = len;
|
133 |
+
}
|
134 |
+
|
135 |
+
char operator[](size_type i) const { return ptr_[i]; }
|
136 |
+
|
137 |
+
void remove_prefix(size_type n) {
|
138 |
+
ptr_ += n;
|
139 |
+
length_ -= n;
|
140 |
+
}
|
141 |
+
|
142 |
+
void remove_suffix(size_type n) {
|
143 |
+
length_ -= n;
|
144 |
+
}
|
145 |
+
|
146 |
+
int compare(const StringPiece& x) const {
|
147 |
+
int r = wordmemcmp(ptr_, x.ptr_, std::min(length_, x.length_));
|
148 |
+
if (r == 0) {
|
149 |
+
if (length_ < x.length_) r = -1;
|
150 |
+
else if (length_ > x.length_) r = +1;
|
151 |
+
}
|
152 |
+
return r;
|
153 |
+
}
|
154 |
+
|
155 |
+
std::string as_string() const {
|
156 |
+
// std::string doesn't like to take a NULL pointer even with a 0 size.
|
157 |
+
return std::string(!empty() ? data() : "", size());
|
158 |
+
}
|
159 |
+
|
160 |
+
void CopyToString(std::string* target) const;
|
161 |
+
void AppendToString(std::string* target) const;
|
162 |
+
|
163 |
+
// Does "this" start with "x"
|
164 |
+
bool starts_with(const StringPiece& x) const {
|
165 |
+
return ((length_ >= x.length_) &&
|
166 |
+
(wordmemcmp(ptr_, x.ptr_, x.length_) == 0));
|
167 |
+
}
|
168 |
+
|
169 |
+
// Does "this" end with "x"
|
170 |
+
bool ends_with(const StringPiece& x) const {
|
171 |
+
return ((length_ >= x.length_) &&
|
172 |
+
(wordmemcmp(ptr_ + (length_-x.length_), x.ptr_, x.length_) == 0));
|
173 |
+
}
|
174 |
+
|
175 |
+
// standard STL container boilerplate
|
176 |
+
typedef char value_type;
|
177 |
+
typedef const char* pointer;
|
178 |
+
typedef const char& reference;
|
179 |
+
typedef const char& const_reference;
|
180 |
+
typedef ptrdiff_t difference_type;
|
181 |
+
static const size_type npos;
|
182 |
+
typedef const char* const_iterator;
|
183 |
+
typedef const char* iterator;
|
184 |
+
typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
|
185 |
+
typedef std::reverse_iterator<iterator> reverse_iterator;
|
186 |
+
iterator begin() const { return ptr_; }
|
187 |
+
iterator end() const { return ptr_ + length_; }
|
188 |
+
const_reverse_iterator rbegin() const {
|
189 |
+
return const_reverse_iterator(ptr_ + length_);
|
190 |
+
}
|
191 |
+
const_reverse_iterator rend() const {
|
192 |
+
return const_reverse_iterator(ptr_);
|
193 |
+
}
|
194 |
+
|
195 |
+
size_type max_size() const { return length_; }
|
196 |
+
size_type capacity() const { return length_; }
|
197 |
+
|
198 |
+
size_type copy(char* buf, size_type n, size_type pos = 0) const;
|
199 |
+
|
200 |
+
size_type find(const StringPiece& s, size_type pos = 0) const;
|
201 |
+
size_type find(char c, size_type pos = 0) const;
|
202 |
+
size_type rfind(const StringPiece& s, size_type pos = npos) const;
|
203 |
+
size_type rfind(char c, size_type pos = npos) const;
|
204 |
+
|
205 |
+
size_type find_first_of(const StringPiece& s, size_type pos = 0) const;
|
206 |
+
size_type find_first_of(char c, size_type pos = 0) const {
|
207 |
+
return find(c, pos);
|
208 |
+
}
|
209 |
+
size_type find_first_not_of(const StringPiece& s, size_type pos = 0) const;
|
210 |
+
size_type find_first_not_of(char c, size_type pos = 0) const;
|
211 |
+
size_type find_last_of(const StringPiece& s, size_type pos = npos) const;
|
212 |
+
size_type find_last_of(char c, size_type pos = npos) const {
|
213 |
+
return rfind(c, pos);
|
214 |
+
}
|
215 |
+
size_type find_last_not_of(const StringPiece& s, size_type pos = npos) const;
|
216 |
+
size_type find_last_not_of(char c, size_type pos = npos) const;
|
217 |
+
|
218 |
+
StringPiece substr(size_type pos, size_type n = npos) const;
|
219 |
+
|
220 |
+
static int wordmemcmp(const char* p, const char* p2, size_type N) {
|
221 |
+
return std::memcmp(p, p2, N);
|
222 |
+
}
|
223 |
+
};
|
224 |
+
|
225 |
+
inline bool operator==(const StringPiece& x, const StringPiece& y) {
|
226 |
+
if (x.size() != y.size())
|
227 |
+
return false;
|
228 |
+
|
229 |
+
return std::memcmp(x.data(), y.data(), x.size()) == 0;
|
230 |
+
}
|
231 |
+
|
232 |
+
inline bool operator!=(const StringPiece& x, const StringPiece& y) {
|
233 |
+
return !(x == y);
|
234 |
+
}
|
235 |
+
|
236 |
+
inline bool starts_with(const StringPiece& longer, const StringPiece& prefix) {
|
237 |
+
return longer.starts_with(prefix);
|
238 |
+
}
|
239 |
+
|
240 |
+
#endif // HAVE_ICU undefined
|
241 |
+
|
242 |
+
inline bool operator<(const StringPiece& x, const StringPiece& y) {
|
243 |
+
const int r = std::memcmp(x.data(), y.data(),
|
244 |
+
std::min(x.size(), y.size()));
|
245 |
+
return ((r < 0) || ((r == 0) && (x.size() < y.size())));
|
246 |
+
}
|
247 |
+
|
248 |
+
inline bool operator>(const StringPiece& x, const StringPiece& y) {
|
249 |
+
return y < x;
|
250 |
+
}
|
251 |
+
|
252 |
+
inline bool operator<=(const StringPiece& x, const StringPiece& y) {
|
253 |
+
return !(x > y);
|
254 |
+
}
|
255 |
+
|
256 |
+
inline bool operator>=(const StringPiece& x, const StringPiece& y) {
|
257 |
+
return !(x < y);
|
258 |
+
}
|
259 |
+
|
260 |
+
// allow StringPiece to be logged (needed for unit testing).
|
261 |
+
inline std::ostream& operator<<(std::ostream& o, const StringPiece& piece) {
|
262 |
+
return o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
|
263 |
+
}
|
264 |
+
|
265 |
+
#ifdef HAVE_ICU
|
266 |
+
U_NAMESPACE_END
|
267 |
+
using U_NAMESPACE_QUALIFIER StringPiece;
|
268 |
+
#endif
|
269 |
+
|
270 |
+
#endif // UTIL_STRING_PIECE_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/string_piece_hash.hh
ADDED
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_STRING_PIECE_HASH_H
|
2 |
+
#define UTIL_STRING_PIECE_HASH_H
|
3 |
+
|
4 |
+
#include "util/string_piece.hh"
|
5 |
+
|
6 |
+
#include <boost/functional/hash.hpp>
|
7 |
+
#include <boost/version.hpp>
|
8 |
+
|
9 |
+
inline size_t hash_value(const StringPiece &str) {
|
10 |
+
return boost::hash_range(str.data(), str.data() + str.length());
|
11 |
+
}
|
12 |
+
|
13 |
+
/* Support for lookup of StringPiece in boost::unordered_map<std::string> */
|
14 |
+
struct StringPieceCompatibleHash : public std::unary_function<const StringPiece &, size_t> {
|
15 |
+
size_t operator()(const StringPiece &str) const {
|
16 |
+
return hash_value(str);
|
17 |
+
}
|
18 |
+
};
|
19 |
+
|
20 |
+
struct StringPieceCompatibleEquals : public std::binary_function<const StringPiece &, const std::string &, bool> {
|
21 |
+
bool operator()(const StringPiece &first, const StringPiece &second) const {
|
22 |
+
return first == second;
|
23 |
+
}
|
24 |
+
};
|
25 |
+
template <class T> typename T::const_iterator FindStringPiece(const T &t, const StringPiece &key) {
|
26 |
+
#if BOOST_VERSION < 104200
|
27 |
+
std::string temp(key.data(), key.size());
|
28 |
+
return t.find(temp);
|
29 |
+
#else
|
30 |
+
return t.find(key, StringPieceCompatibleHash(), StringPieceCompatibleEquals());
|
31 |
+
#endif
|
32 |
+
}
|
33 |
+
|
34 |
+
template <class T> typename T::iterator FindStringPiece(T &t, const StringPiece &key) {
|
35 |
+
#if BOOST_VERSION < 104200
|
36 |
+
std::string temp(key.data(), key.size());
|
37 |
+
return t.find(temp);
|
38 |
+
#else
|
39 |
+
return t.find(key, StringPieceCompatibleHash(), StringPieceCompatibleEquals());
|
40 |
+
#endif
|
41 |
+
}
|
42 |
+
|
43 |
+
#endif // UTIL_STRING_PIECE_HASH_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/thread_pool.hh
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_THREAD_POOL_H
|
2 |
+
#define UTIL_THREAD_POOL_H
|
3 |
+
|
4 |
+
#include "util/pcqueue.hh"
|
5 |
+
|
6 |
+
#include <boost/ptr_container/ptr_vector.hpp>
|
7 |
+
#include <boost/optional.hpp>
|
8 |
+
#include <boost/thread.hpp>
|
9 |
+
|
10 |
+
#include <iostream>
|
11 |
+
|
12 |
+
#include <stdlib.h>
|
13 |
+
|
14 |
+
namespace util {
|
15 |
+
|
16 |
+
template <class HandlerT> class Worker : boost::noncopyable {
|
17 |
+
public:
|
18 |
+
typedef HandlerT Handler;
|
19 |
+
typedef typename Handler::Request Request;
|
20 |
+
|
21 |
+
template <class Construct> Worker(PCQueue<Request> &in, Construct &construct, const Request &poison)
|
22 |
+
: in_(in), handler_(construct), poison_(poison), thread_(boost::ref(*this)) {}
|
23 |
+
|
24 |
+
// Only call from thread.
|
25 |
+
void operator()() {
|
26 |
+
Request request;
|
27 |
+
while (1) {
|
28 |
+
in_.Consume(request);
|
29 |
+
if (request == poison_) return;
|
30 |
+
try {
|
31 |
+
(*handler_)(request);
|
32 |
+
}
|
33 |
+
catch(const std::exception &e) {
|
34 |
+
std::cerr << "Handler threw " << e.what() << std::endl;
|
35 |
+
abort();
|
36 |
+
}
|
37 |
+
catch(...) {
|
38 |
+
std::cerr << "Handler threw an exception, dropping request" << std::endl;
|
39 |
+
abort();
|
40 |
+
}
|
41 |
+
}
|
42 |
+
}
|
43 |
+
|
44 |
+
void Join() {
|
45 |
+
thread_.join();
|
46 |
+
}
|
47 |
+
|
48 |
+
private:
|
49 |
+
PCQueue<Request> &in_;
|
50 |
+
|
51 |
+
boost::optional<Handler> handler_;
|
52 |
+
|
53 |
+
const Request poison_;
|
54 |
+
|
55 |
+
boost::thread thread_;
|
56 |
+
};
|
57 |
+
|
58 |
+
template <class HandlerT> class ThreadPool : boost::noncopyable {
|
59 |
+
public:
|
60 |
+
typedef HandlerT Handler;
|
61 |
+
typedef typename Handler::Request Request;
|
62 |
+
|
63 |
+
template <class Construct> ThreadPool(size_t queue_length, size_t workers, Construct handler_construct, Request poison) : in_(queue_length), poison_(poison) {
|
64 |
+
for (size_t i = 0; i < workers; ++i) {
|
65 |
+
workers_.push_back(new Worker<Handler>(in_, handler_construct, poison));
|
66 |
+
}
|
67 |
+
}
|
68 |
+
|
69 |
+
~ThreadPool() {
|
70 |
+
for (size_t i = 0; i < workers_.size(); ++i) {
|
71 |
+
Produce(poison_);
|
72 |
+
}
|
73 |
+
for (typename boost::ptr_vector<Worker<Handler> >::iterator i = workers_.begin(); i != workers_.end(); ++i) {
|
74 |
+
i->Join();
|
75 |
+
}
|
76 |
+
}
|
77 |
+
|
78 |
+
void Produce(const Request &request) {
|
79 |
+
in_.Produce(request);
|
80 |
+
}
|
81 |
+
|
82 |
+
// For adding to the queue.
|
83 |
+
PCQueue<Request> &In() { return in_; }
|
84 |
+
|
85 |
+
private:
|
86 |
+
PCQueue<Request> in_;
|
87 |
+
|
88 |
+
boost::ptr_vector<Worker<Handler> > workers_;
|
89 |
+
|
90 |
+
Request poison_;
|
91 |
+
};
|
92 |
+
|
93 |
+
} // namespace util
|
94 |
+
|
95 |
+
#endif // UTIL_THREAD_POOL_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/tokenize_piece.hh
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_TOKENIZE_PIECE_H
|
2 |
+
#define UTIL_TOKENIZE_PIECE_H
|
3 |
+
|
4 |
+
#include "util/exception.hh"
|
5 |
+
#include "util/string_piece.hh"
|
6 |
+
|
7 |
+
#include <boost/iterator/iterator_facade.hpp>
|
8 |
+
|
9 |
+
#include <algorithm>
|
10 |
+
|
11 |
+
#include <string.h>
|
12 |
+
|
13 |
+
namespace util {
|
14 |
+
|
15 |
+
// Thrown on dereference when out of tokens to parse
|
16 |
+
class OutOfTokens : public Exception {
|
17 |
+
public:
|
18 |
+
OutOfTokens() throw() {}
|
19 |
+
~OutOfTokens() throw() {}
|
20 |
+
};
|
21 |
+
|
22 |
+
class SingleCharacter {
|
23 |
+
public:
|
24 |
+
SingleCharacter() {}
|
25 |
+
explicit SingleCharacter(char delim) : delim_(delim) {}
|
26 |
+
|
27 |
+
StringPiece Find(const StringPiece &in) const {
|
28 |
+
return StringPiece(std::find(in.data(), in.data() + in.size(), delim_), 1);
|
29 |
+
}
|
30 |
+
|
31 |
+
private:
|
32 |
+
char delim_;
|
33 |
+
};
|
34 |
+
|
35 |
+
class MultiCharacter {
|
36 |
+
public:
|
37 |
+
MultiCharacter() {}
|
38 |
+
|
39 |
+
explicit MultiCharacter(const StringPiece &delimiter) : delimiter_(delimiter) {}
|
40 |
+
|
41 |
+
StringPiece Find(const StringPiece &in) const {
|
42 |
+
return StringPiece(std::search(in.data(), in.data() + in.size(), delimiter_.data(), delimiter_.data() + delimiter_.size()), delimiter_.size());
|
43 |
+
}
|
44 |
+
|
45 |
+
private:
|
46 |
+
StringPiece delimiter_;
|
47 |
+
};
|
48 |
+
|
49 |
+
class AnyCharacter {
|
50 |
+
public:
|
51 |
+
AnyCharacter() {}
|
52 |
+
explicit AnyCharacter(const StringPiece &chars) : chars_(chars) {}
|
53 |
+
|
54 |
+
StringPiece Find(const StringPiece &in) const {
|
55 |
+
return StringPiece(std::find_first_of(in.data(), in.data() + in.size(), chars_.data(), chars_.data() + chars_.size()), 1);
|
56 |
+
}
|
57 |
+
|
58 |
+
private:
|
59 |
+
StringPiece chars_;
|
60 |
+
};
|
61 |
+
|
62 |
+
class BoolCharacter {
|
63 |
+
public:
|
64 |
+
BoolCharacter() {}
|
65 |
+
|
66 |
+
explicit BoolCharacter(const bool *delimiter) { delimiter_ = delimiter; }
|
67 |
+
|
68 |
+
StringPiece Find(const StringPiece &in) const {
|
69 |
+
for (const char *i = in.data(); i != in.data() + in.size(); ++i) {
|
70 |
+
if (delimiter_[static_cast<unsigned char>(*i)]) return StringPiece(i, 1);
|
71 |
+
}
|
72 |
+
return StringPiece(in.data() + in.size(), 0);
|
73 |
+
}
|
74 |
+
|
75 |
+
template <unsigned Length> static void Build(const char (&characters)[Length], bool (&out)[256]) {
|
76 |
+
memset(out, 0, sizeof(out));
|
77 |
+
for (const char *i = characters; i != characters + Length; ++i) {
|
78 |
+
out[static_cast<unsigned char>(*i)] = true;
|
79 |
+
}
|
80 |
+
}
|
81 |
+
|
82 |
+
private:
|
83 |
+
const bool *delimiter_;
|
84 |
+
};
|
85 |
+
|
86 |
+
class AnyCharacterLast {
|
87 |
+
public:
|
88 |
+
AnyCharacterLast() {}
|
89 |
+
|
90 |
+
explicit AnyCharacterLast(const StringPiece &chars) : chars_(chars) {}
|
91 |
+
|
92 |
+
StringPiece Find(const StringPiece &in) const {
|
93 |
+
return StringPiece(std::find_end(in.data(), in.data() + in.size(), chars_.data(), chars_.data() + chars_.size()), 1);
|
94 |
+
}
|
95 |
+
|
96 |
+
private:
|
97 |
+
StringPiece chars_;
|
98 |
+
};
|
99 |
+
|
100 |
+
template <class Find, bool SkipEmpty = false> class TokenIter : public boost::iterator_facade<TokenIter<Find, SkipEmpty>, const StringPiece, boost::forward_traversal_tag> {
|
101 |
+
public:
|
102 |
+
TokenIter() {}
|
103 |
+
|
104 |
+
template <class Construct> TokenIter(const StringPiece &str, const Construct &construct) : after_(str), finder_(construct) {
|
105 |
+
increment();
|
106 |
+
}
|
107 |
+
|
108 |
+
bool operator!() const {
|
109 |
+
return current_.data() == 0;
|
110 |
+
}
|
111 |
+
operator bool() const {
|
112 |
+
return current_.data() != 0;
|
113 |
+
}
|
114 |
+
|
115 |
+
static TokenIter<Find, SkipEmpty> end() {
|
116 |
+
return TokenIter<Find, SkipEmpty>();
|
117 |
+
}
|
118 |
+
|
119 |
+
private:
|
120 |
+
friend class boost::iterator_core_access;
|
121 |
+
|
122 |
+
void increment() {
|
123 |
+
do {
|
124 |
+
StringPiece found(finder_.Find(after_));
|
125 |
+
current_ = StringPiece(after_.data(), found.data() - after_.data());
|
126 |
+
if (found.data() == after_.data() + after_.size()) {
|
127 |
+
after_ = StringPiece(NULL, 0);
|
128 |
+
} else {
|
129 |
+
after_ = StringPiece(found.data() + found.size(), after_.data() - found.data() + after_.size() - found.size());
|
130 |
+
}
|
131 |
+
} while (SkipEmpty && current_.data() && current_.empty()); // Compiler should optimize this away if SkipEmpty is false.
|
132 |
+
}
|
133 |
+
|
134 |
+
bool equal(const TokenIter<Find, SkipEmpty> &other) const {
|
135 |
+
return current_.data() == other.current_.data();
|
136 |
+
}
|
137 |
+
|
138 |
+
const StringPiece &dereference() const {
|
139 |
+
UTIL_THROW_IF(!current_.data(), OutOfTokens, "Ran out of tokens");
|
140 |
+
return current_;
|
141 |
+
}
|
142 |
+
|
143 |
+
StringPiece current_;
|
144 |
+
StringPiece after_;
|
145 |
+
|
146 |
+
Find finder_;
|
147 |
+
};
|
148 |
+
|
149 |
+
} // namespace util
|
150 |
+
|
151 |
+
#endif // UTIL_TOKENIZE_PIECE_H
|
cc-multilingual-main/cc_net/third_party/kenlm/include/util/unistd.hh
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_UNISTD_H
|
2 |
+
#define UTIL_UNISTD_H
|
3 |
+
|
4 |
+
#if defined(_WIN32) || defined(_WIN64)
|
5 |
+
|
6 |
+
// Windows doesn't define <unistd.h>
|
7 |
+
//
|
8 |
+
// So we define what we need here instead:
|
9 |
+
//
|
10 |
+
#define STDIN_FILENO=0
|
11 |
+
#define STDOUT_FILENO=1
|
12 |
+
|
13 |
+
|
14 |
+
#else // Huzzah for POSIX!
|
15 |
+
|
16 |
+
#include <unistd.h>
|
17 |
+
|
18 |
+
#endif
|
19 |
+
|
20 |
+
|
21 |
+
|
22 |
+
#endif // UTIL_UNISTD_H
|
cc-multilingual-main/cc_net/third_party/kenlm/python/CMakeLists.txt
ADDED
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
find_package(PythonInterp REQUIRED)
|
2 |
+
find_package(PythonLibs ${PYTHON_VERSION_STRING} EXACT REQUIRED)
|
3 |
+
include_directories(${PYTHON_INCLUDE_DIRS} ${PROJECT_SOURCE_DIR})
|
4 |
+
|
5 |
+
add_library(kenlm_python MODULE kenlm.cpp score_sentence.cc)
|
6 |
+
set_target_properties(kenlm_python PROPERTIES OUTPUT_NAME kenlm)
|
7 |
+
set_target_properties(kenlm_python PROPERTIES PREFIX "")
|
8 |
+
|
9 |
+
if(APPLE)
|
10 |
+
set_target_properties(kenlm_python PROPERTIES SUFFIX ".so")
|
11 |
+
elseif(WIN32)
|
12 |
+
set_target_properties(kenlm_python PROPERTIES SUFFIX ".pyd")
|
13 |
+
endif()
|
14 |
+
|
15 |
+
target_link_libraries(kenlm_python PUBLIC kenlm)
|
16 |
+
if(WIN32)
|
17 |
+
target_link_libraries(kenlm_python PUBLIC ${PYTHON_LIBRARIES})
|
18 |
+
elseif(APPLE)
|
19 |
+
set_target_properties(kenlm_python PROPERTIES LINK_FLAGS "-undefined dynamic_lookup")
|
20 |
+
endif()
|
21 |
+
|
22 |
+
if (WIN32)
|
23 |
+
set (PYTHON_SITE_PACKAGES Lib/site-packages)
|
24 |
+
else ()
|
25 |
+
set (PYTHON_SITE_PACKAGES lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages)
|
26 |
+
endif ()
|
27 |
+
|
28 |
+
install(TARGETS kenlm_python DESTINATION ${PYTHON_SITE_PACKAGES})
|
cc-multilingual-main/cc_net/third_party/kenlm/python/kenlm.pyx
ADDED
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
cimport _kenlm
|
3 |
+
|
4 |
+
cdef bytes as_str(data):
|
5 |
+
if isinstance(data, bytes):
|
6 |
+
return data
|
7 |
+
elif isinstance(data, unicode):
|
8 |
+
return data.encode('utf8')
|
9 |
+
raise TypeError('Cannot convert %s to string' % type(data))
|
10 |
+
|
11 |
+
cdef class FullScoreReturn:
|
12 |
+
"""
|
13 |
+
Wrapper around FullScoreReturn.
|
14 |
+
|
15 |
+
Notes:
|
16 |
+
`prob` has been renamed to `log_prob`
|
17 |
+
`oov` has been added to flag whether the word is OOV
|
18 |
+
"""
|
19 |
+
|
20 |
+
cdef float log_prob
|
21 |
+
cdef int ngram_length
|
22 |
+
cdef bint oov
|
23 |
+
|
24 |
+
def __cinit__(self, log_prob, ngram_length, oov):
|
25 |
+
self.log_prob = log_prob
|
26 |
+
self.ngram_length = ngram_length
|
27 |
+
self.oov = oov
|
28 |
+
|
29 |
+
def __repr__(self):
|
30 |
+
return '{0}({1}, {2}, {3})'.format(self.__class__.__name__, repr(self.log_prob), repr(self.ngram_length), repr(self.oov))
|
31 |
+
|
32 |
+
property log_prob:
|
33 |
+
def __get__(self):
|
34 |
+
return self.log_prob
|
35 |
+
|
36 |
+
property ngram_length:
|
37 |
+
def __get__(self):
|
38 |
+
return self.ngram_length
|
39 |
+
|
40 |
+
property oov:
|
41 |
+
def __get__(self):
|
42 |
+
return self.oov
|
43 |
+
|
44 |
+
cdef class State:
|
45 |
+
"""
|
46 |
+
Wrapper around lm::ngram::State so that python code can make incremental queries.
|
47 |
+
|
48 |
+
Notes:
|
49 |
+
* rich comparisons
|
50 |
+
* hashable
|
51 |
+
"""
|
52 |
+
|
53 |
+
cdef _kenlm.State _c_state
|
54 |
+
|
55 |
+
def __richcmp__(State qa, State qb, int op):
|
56 |
+
r = qa._c_state.Compare(qb._c_state)
|
57 |
+
if op == 0: # <
|
58 |
+
return r < 0
|
59 |
+
elif op == 1: # <=
|
60 |
+
return r <= 0
|
61 |
+
elif op == 2: # ==
|
62 |
+
return r == 0
|
63 |
+
elif op == 3: # !=
|
64 |
+
return r != 0
|
65 |
+
elif op == 4: # >
|
66 |
+
return r > 0
|
67 |
+
else: # >=
|
68 |
+
return r >= 0
|
69 |
+
|
70 |
+
def __hash__(self):
|
71 |
+
return _kenlm.hash_value(self._c_state)
|
72 |
+
|
73 |
+
def __copy__(self):
|
74 |
+
ret = State()
|
75 |
+
ret._c_state = self._c_state
|
76 |
+
return ret
|
77 |
+
|
78 |
+
def __deepcopy__(self):
|
79 |
+
return self.__copy__()
|
80 |
+
|
81 |
+
class LoadMethod:
|
82 |
+
LAZY = _kenlm.LAZY
|
83 |
+
POPULATE_OR_LAZY = _kenlm.POPULATE_OR_LAZY
|
84 |
+
POPULATE_OR_READ = _kenlm.POPULATE_OR_READ
|
85 |
+
READ = _kenlm.READ
|
86 |
+
PARALLEL_READ = _kenlm.PARALLEL_READ
|
87 |
+
|
88 |
+
class ARPALoadComplain:
|
89 |
+
ALL = _kenlm.ALL
|
90 |
+
EXPENSIVE = _kenlm.EXPENSIVE
|
91 |
+
NONE = _kenlm.NONE
|
92 |
+
|
93 |
+
cdef class Config:
|
94 |
+
"""
|
95 |
+
Wrapper around lm::ngram::Config.
|
96 |
+
Pass this to Model's constructor to set configuration options.
|
97 |
+
"""
|
98 |
+
cdef _kenlm.Config _c_config
|
99 |
+
|
100 |
+
def __init__(self):
|
101 |
+
self._c_config = _kenlm.Config()
|
102 |
+
|
103 |
+
property load_method:
|
104 |
+
def __get__(self):
|
105 |
+
return self._c_config.load_method
|
106 |
+
def __set__(self, to):
|
107 |
+
self._c_config.load_method = to
|
108 |
+
|
109 |
+
property show_progress:
|
110 |
+
def __get__(self):
|
111 |
+
return self._c_config.show_progress
|
112 |
+
def __set__(self, to):
|
113 |
+
self._c_config.show_progress = to
|
114 |
+
|
115 |
+
property arpa_complain:
|
116 |
+
def __get__(self):
|
117 |
+
return self._c_config.arpa_complain
|
118 |
+
def __set__(self, to):
|
119 |
+
self._c_config.arpa_complain = to
|
120 |
+
|
121 |
+
cdef class Model:
|
122 |
+
"""
|
123 |
+
Wrapper around lm::ngram::Model.
|
124 |
+
"""
|
125 |
+
|
126 |
+
cdef _kenlm.Model* model
|
127 |
+
cdef public bytes path
|
128 |
+
cdef _kenlm.const_Vocabulary* vocab
|
129 |
+
|
130 |
+
def __init__(self, path, Config config = Config()):
|
131 |
+
"""
|
132 |
+
Load the language model.
|
133 |
+
|
134 |
+
:param path: path to an arpa file or a kenlm binary file.
|
135 |
+
:param config: configuration options (see lm/config.hh for documentation)
|
136 |
+
"""
|
137 |
+
self.path = os.path.abspath(as_str(path))
|
138 |
+
try:
|
139 |
+
self.model = _kenlm.LoadVirtual(self.path, config._c_config)
|
140 |
+
except RuntimeError as exception:
|
141 |
+
exception_message = str(exception).replace('\n', ' ')
|
142 |
+
raise IOError('Cannot read model \'{}\' ({})'.format(path, exception_message))\
|
143 |
+
from exception
|
144 |
+
self.vocab = &self.model.BaseVocabulary()
|
145 |
+
|
146 |
+
def __dealloc__(self):
|
147 |
+
del self.model
|
148 |
+
|
149 |
+
property order:
|
150 |
+
def __get__(self):
|
151 |
+
return self.model.Order()
|
152 |
+
|
153 |
+
def score(self, sentence, bos = True, eos = True):
|
154 |
+
"""
|
155 |
+
Return the log10 probability of a string. By default, the string is
|
156 |
+
treated as a sentence.
|
157 |
+
return log10 p(sentence </s> | <s>)
|
158 |
+
|
159 |
+
If you do not want to condition on the beginning of sentence, pass
|
160 |
+
bos = False
|
161 |
+
Never include <s> as part of the string. That would be predicting the
|
162 |
+
beginning of sentence. Language models are only supposed to condition
|
163 |
+
on it as context.
|
164 |
+
|
165 |
+
Similarly, the end of sentence token </s> can be omitted with
|
166 |
+
eos = False
|
167 |
+
Since language models explicitly predict </s>, it can be part of the
|
168 |
+
string.
|
169 |
+
|
170 |
+
Examples:
|
171 |
+
|
172 |
+
#Good: returns log10 p(this is a sentence . </s> | <s>)
|
173 |
+
model.score("this is a sentence .")
|
174 |
+
#Good: same as the above but more explicit
|
175 |
+
model.score("this is a sentence .", bos = True, eos = True)
|
176 |
+
|
177 |
+
#Bad: never include <s>
|
178 |
+
model.score("<s> this is a sentence")
|
179 |
+
#Bad: never include <s>, even if bos = False.
|
180 |
+
model.score("<s> this is a sentence", bos = False)
|
181 |
+
|
182 |
+
#Good: returns log10 p(a fragment)
|
183 |
+
model.score("a fragment", bos = False, eos = False)
|
184 |
+
|
185 |
+
#Good: returns log10 p(a fragment </s>)
|
186 |
+
model.score("a fragment", bos = False, eos = True)
|
187 |
+
|
188 |
+
#Ok, but bad practice: returns log10 p(a fragment </s>)
|
189 |
+
#Unlike <s>, the end of sentence token </s> can appear explicitly.
|
190 |
+
model.score("a fragment </s>", bos = False, eos = False)
|
191 |
+
"""
|
192 |
+
if bos and eos:
|
193 |
+
return _kenlm.ScoreSentence(self.model, as_str(sentence))
|
194 |
+
cdef list words = as_str(sentence).split()
|
195 |
+
cdef _kenlm.State state
|
196 |
+
if bos:
|
197 |
+
self.model.BeginSentenceWrite(&state)
|
198 |
+
else:
|
199 |
+
self.model.NullContextWrite(&state)
|
200 |
+
cdef _kenlm.State out_state
|
201 |
+
cdef float total = 0
|
202 |
+
for word in words:
|
203 |
+
total += self.model.BaseScore(&state, self.vocab.Index(word), &out_state)
|
204 |
+
state = out_state
|
205 |
+
if eos:
|
206 |
+
total += self.model.BaseScore(&state, self.vocab.EndSentence(), &out_state)
|
207 |
+
return total
|
208 |
+
|
209 |
+
def perplexity(self, sentence):
|
210 |
+
"""
|
211 |
+
Compute perplexity of a sentence.
|
212 |
+
@param sentence One full sentence to score. Do not include <s> or </s>.
|
213 |
+
"""
|
214 |
+
words = len(as_str(sentence).split()) + 1 # For </s>
|
215 |
+
return 10.0**(-self.score(sentence) / words)
|
216 |
+
|
217 |
+
def full_scores(self, sentence, bos = True, eos = True):
|
218 |
+
"""
|
219 |
+
full_scores(sentence, bos = True, eos = True) -> generate full scores (prob, ngram length, oov)
|
220 |
+
@param sentence is a string (do not use boundary symbols)
|
221 |
+
@param bos should kenlm add a bos state
|
222 |
+
@param eos should kenlm add an eos state
|
223 |
+
"""
|
224 |
+
cdef list words = as_str(sentence).split()
|
225 |
+
cdef _kenlm.State state
|
226 |
+
if bos:
|
227 |
+
self.model.BeginSentenceWrite(&state)
|
228 |
+
else:
|
229 |
+
self.model.NullContextWrite(&state)
|
230 |
+
cdef _kenlm.State out_state
|
231 |
+
cdef _kenlm.FullScoreReturn ret
|
232 |
+
cdef float total = 0
|
233 |
+
cdef _kenlm.WordIndex wid
|
234 |
+
for word in words:
|
235 |
+
wid = self.vocab.Index(word)
|
236 |
+
ret = self.model.BaseFullScore(&state, wid, &out_state)
|
237 |
+
yield (ret.prob, ret.ngram_length, wid == 0)
|
238 |
+
state = out_state
|
239 |
+
if eos:
|
240 |
+
ret = self.model.BaseFullScore(&state,
|
241 |
+
self.vocab.EndSentence(), &out_state)
|
242 |
+
yield (ret.prob, ret.ngram_length, False)
|
243 |
+
|
244 |
+
|
245 |
+
def BeginSentenceWrite(self, State state):
|
246 |
+
"""Change the given state to a BOS state."""
|
247 |
+
self.model.BeginSentenceWrite(&state._c_state)
|
248 |
+
|
249 |
+
def NullContextWrite(self, State state):
|
250 |
+
"""Change the given state to a NULL state."""
|
251 |
+
self.model.NullContextWrite(&state._c_state)
|
252 |
+
|
253 |
+
def BaseScore(self, State in_state, str word, State out_state):
|
254 |
+
"""
|
255 |
+
Return p(word|in_state) and update the output state.
|
256 |
+
Wrapper around model.BaseScore(in_state, Index(word), out_state)
|
257 |
+
|
258 |
+
:param word: the suffix
|
259 |
+
:param state: the context (defaults to NullContext)
|
260 |
+
:returns: p(word|state)
|
261 |
+
"""
|
262 |
+
cdef float total = self.model.BaseScore(&in_state._c_state, self.vocab.Index(as_str(word)), &out_state._c_state)
|
263 |
+
return total
|
264 |
+
|
265 |
+
def BaseFullScore(self, State in_state, str word, State out_state):
|
266 |
+
"""
|
267 |
+
Wrapper around model.BaseFullScore(in_state, Index(word), out_state)
|
268 |
+
|
269 |
+
:param word: the suffix
|
270 |
+
:param state: the context (defaults to NullContext)
|
271 |
+
:returns: FullScoreReturn(word|state)
|
272 |
+
"""
|
273 |
+
cdef _kenlm.WordIndex wid = self.vocab.Index(as_str(word))
|
274 |
+
cdef _kenlm.FullScoreReturn ret = self.model.BaseFullScore(&in_state._c_state, wid, &out_state._c_state)
|
275 |
+
return FullScoreReturn(ret.prob, ret.ngram_length, wid == 0)
|
276 |
+
|
277 |
+
def __contains__(self, word):
|
278 |
+
cdef bytes w = as_str(word)
|
279 |
+
return (self.vocab.Index(w) != 0)
|
280 |
+
|
281 |
+
def __repr__(self):
|
282 |
+
return '<Model from {0}>'.format(os.path.basename(self.path))
|
283 |
+
|
284 |
+
def __reduce__(self):
|
285 |
+
return (Model, (self.path,))
|
286 |
+
|
287 |
+
class LanguageModel(Model):
|
288 |
+
"""Backwards compatability stub. Use Model."""
|
cc-multilingual-main/cc_net/third_party/kenlm/util/CMakeLists.txt
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Explicitly list the source files for this subdirectory
|
2 |
+
#
|
3 |
+
# If you add any source files to this subdirectory
|
4 |
+
# that should be included in the kenlm library,
|
5 |
+
# (this excludes any unit test files)
|
6 |
+
# you should add them to the following list:
|
7 |
+
#
|
8 |
+
# Because we do not set PARENT_SCOPE in the following definition,
|
9 |
+
# CMake files in the parent directory won't be able to access this variable.
|
10 |
+
#
|
11 |
+
set(KENLM_UTIL_SOURCE
|
12 |
+
bit_packing.cc
|
13 |
+
ersatz_progress.cc
|
14 |
+
exception.cc
|
15 |
+
file.cc
|
16 |
+
file_piece.cc
|
17 |
+
float_to_string.cc
|
18 |
+
integer_to_string.cc
|
19 |
+
mmap.cc
|
20 |
+
murmur_hash.cc
|
21 |
+
parallel_read.cc
|
22 |
+
pool.cc
|
23 |
+
read_compressed.cc
|
24 |
+
scoped.cc
|
25 |
+
spaces.cc
|
26 |
+
string_piece.cc
|
27 |
+
usage.cc
|
28 |
+
)
|
29 |
+
|
30 |
+
if (WIN32)
|
31 |
+
set(KENLM_UTIL_SOURCE ${KENLM_UTIL_SOURCE} getopt.c)
|
32 |
+
endif()
|
33 |
+
|
34 |
+
# This directory has children that need to be processed
|
35 |
+
add_subdirectory(double-conversion)
|
36 |
+
add_subdirectory(stream)
|
37 |
+
|
38 |
+
add_library(kenlm_util ${KENLM_UTIL_DOUBLECONVERSION_SOURCE} ${KENLM_UTIL_STREAM_SOURCE} ${KENLM_UTIL_SOURCE})
|
39 |
+
# Since headers are relative to `include/kenlm` at install time, not just `include`
|
40 |
+
target_include_directories(kenlm_util PUBLIC $<INSTALL_INTERFACE:include/kenlm>)
|
41 |
+
|
42 |
+
set(READ_COMPRESSED_FLAGS)
|
43 |
+
find_package(ZLIB)
|
44 |
+
if (ZLIB_FOUND)
|
45 |
+
set(READ_COMPRESSED_FLAGS "${READ_COMPRESSED_FLAGS} -DHAVE_ZLIB")
|
46 |
+
target_link_libraries(kenlm_util PRIVATE ${ZLIB_LIBRARIES})
|
47 |
+
include_directories(${ZLIB_INCLUDE_DIR})
|
48 |
+
endif()
|
49 |
+
|
50 |
+
find_package(BZip2)
|
51 |
+
if (BZIP2_FOUND)
|
52 |
+
set(READ_COMPRESSED_FLAGS "${READ_COMPRESSED_FLAGS} -DHAVE_BZLIB")
|
53 |
+
target_link_libraries(kenlm_util PRIVATE ${BZIP2_LIBRARIES})
|
54 |
+
include_directories(${BZIP2_INCLUDE_DIR})
|
55 |
+
endif()
|
56 |
+
|
57 |
+
find_package(LibLZMA)
|
58 |
+
if (LIBLZMA_FOUND)
|
59 |
+
set(READ_COMPRESSED_FLAGS "${READ_COMPRESSED_FLAGS} -DHAVE_XZLIB")
|
60 |
+
target_link_libraries(kenlm_util PRIVATE ${LIBLZMA_LIBRARIES})
|
61 |
+
include_directories(${LIBLZMA_INCLUDE_DIRS})
|
62 |
+
endif()
|
63 |
+
if (NOT "${READ_COMPRESSED_FLAGS}" STREQUAL "")
|
64 |
+
set_source_files_properties(read_compressed.cc PROPERTIES COMPILE_FLAGS ${READ_COMPRESSED_FLAGS})
|
65 |
+
set_source_files_properties(read_compressed_test.cc PROPERTIES COMPILE_FLAGS ${READ_COMPRESSED_FLAGS})
|
66 |
+
set_source_files_properties(file_piece_test.cc PROPERTIES COMPILE_FLAGS ${READ_COMPRESSED_FLAGS})
|
67 |
+
endif()
|
68 |
+
|
69 |
+
if(UNIX)
|
70 |
+
include(CheckLibraryExists)
|
71 |
+
check_library_exists(rt clock_gettime "clock_gettime from librt" HAVE_CLOCKGETTIME_RT)
|
72 |
+
if (HAVE_CLOCKGETTIME_RT)
|
73 |
+
set(RT rt)
|
74 |
+
else()
|
75 |
+
check_library_exists(c clock_gettime "clock_gettime from the libc" HAVE_CLOCKGETTIME)
|
76 |
+
endif()
|
77 |
+
|
78 |
+
if (HAVE_CLOCKGETTIME_RT OR HAVE_CLOCKGETTIME)
|
79 |
+
add_definitions(-DHAVE_CLOCKGETTIME)
|
80 |
+
endif()
|
81 |
+
endif()
|
82 |
+
|
83 |
+
# Group these objects together for later use.
|
84 |
+
set_target_properties(kenlm_util PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
85 |
+
target_link_libraries(kenlm_util
|
86 |
+
PUBLIC
|
87 |
+
# Boost is required for building binaries and tests
|
88 |
+
"$<BUILD_INTERFACE:${Boost_LIBRARIES}>"
|
89 |
+
PRIVATE
|
90 |
+
Threads::Threads
|
91 |
+
${RT})
|
92 |
+
|
93 |
+
install(
|
94 |
+
TARGETS kenlm_util
|
95 |
+
EXPORT kenlmTargets
|
96 |
+
RUNTIME DESTINATION bin
|
97 |
+
LIBRARY DESTINATION lib
|
98 |
+
ARCHIVE DESTINATION lib
|
99 |
+
INCLUDES DESTINATION include
|
100 |
+
)
|
101 |
+
|
102 |
+
if (NOT WIN32)
|
103 |
+
AddExes(EXES probing_hash_table_benchmark
|
104 |
+
LIBRARIES kenlm_util Threads::Threads)
|
105 |
+
endif()
|
106 |
+
|
107 |
+
# Only compile and run unit tests if tests should be run
|
108 |
+
if(BUILD_TESTING)
|
109 |
+
set(KENLM_BOOST_TESTS_LIST
|
110 |
+
bit_packing_test
|
111 |
+
integer_to_string_test
|
112 |
+
joint_sort_test
|
113 |
+
multi_intersection_test
|
114 |
+
pcqueue_test
|
115 |
+
probing_hash_table_test
|
116 |
+
read_compressed_test
|
117 |
+
sized_iterator_test
|
118 |
+
sorted_uniform_test
|
119 |
+
string_stream_test
|
120 |
+
tokenize_piece_test
|
121 |
+
)
|
122 |
+
|
123 |
+
AddTests(TESTS ${KENLM_BOOST_TESTS_LIST}
|
124 |
+
LIBRARIES kenlm_util Threads::Threads)
|
125 |
+
|
126 |
+
# file_piece_test requires an extra command line parameter
|
127 |
+
KenLMAddTest(TEST file_piece_test
|
128 |
+
LIBRARIES kenlm_util Threads::Threads
|
129 |
+
TEST_ARGS ${CMAKE_CURRENT_SOURCE_DIR}/file_piece.cc)
|
130 |
+
endif()
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/CMakeLists.txt
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This CMake file was created by Lane Schwartz <[email protected]>
|
2 |
+
|
3 |
+
# Explicitly list the source files for this subdirectory
|
4 |
+
#
|
5 |
+
# If you add any source files to this subdirectory
|
6 |
+
# that should be included in the kenlm library,
|
7 |
+
# (this excludes any unit test files)
|
8 |
+
# you should add them to the following list:
|
9 |
+
#
|
10 |
+
# In order to allow CMake files in the parent directory
|
11 |
+
# to see this variable definition, we set PARENT_SCOPE.
|
12 |
+
#
|
13 |
+
# In order to set correct paths to these files
|
14 |
+
# when this variable is referenced by CMake files in the parent directory,
|
15 |
+
# we prefix all files with ${CMAKE_CURRENT_SOURCE_DIR}.
|
16 |
+
#
|
17 |
+
set(KENLM_UTIL_DOUBLECONVERSION_SOURCE
|
18 |
+
${CMAKE_CURRENT_SOURCE_DIR}/bignum-dtoa.cc
|
19 |
+
${CMAKE_CURRENT_SOURCE_DIR}/bignum.cc
|
20 |
+
${CMAKE_CURRENT_SOURCE_DIR}/cached-powers.cc
|
21 |
+
${CMAKE_CURRENT_SOURCE_DIR}/diy-fp.cc
|
22 |
+
${CMAKE_CURRENT_SOURCE_DIR}/double-conversion.cc
|
23 |
+
${CMAKE_CURRENT_SOURCE_DIR}/fast-dtoa.cc
|
24 |
+
${CMAKE_CURRENT_SOURCE_DIR}/fixed-dtoa.cc
|
25 |
+
${CMAKE_CURRENT_SOURCE_DIR}/strtod.cc
|
26 |
+
PARENT_SCOPE)
|
27 |
+
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/LICENSE
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright 2006-2011, the V8 project authors. All rights reserved.
|
2 |
+
Redistribution and use in source and binary forms, with or without
|
3 |
+
modification, are permitted provided that the following conditions are
|
4 |
+
met:
|
5 |
+
|
6 |
+
* Redistributions of source code must retain the above copyright
|
7 |
+
notice, this list of conditions and the following disclaimer.
|
8 |
+
* Redistributions in binary form must reproduce the above
|
9 |
+
copyright notice, this list of conditions and the following
|
10 |
+
disclaimer in the documentation and/or other materials provided
|
11 |
+
with the distribution.
|
12 |
+
* Neither the name of Google Inc. nor the names of its
|
13 |
+
contributors may be used to endorse or promote products derived
|
14 |
+
from this software without specific prior written permission.
|
15 |
+
|
16 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum-dtoa.cc
ADDED
@@ -0,0 +1,641 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include <math.h>
|
29 |
+
|
30 |
+
#include "bignum-dtoa.h"
|
31 |
+
|
32 |
+
#include "bignum.h"
|
33 |
+
#include "ieee.h"
|
34 |
+
|
35 |
+
namespace double_conversion {
|
36 |
+
|
37 |
+
static int NormalizedExponent(uint64_t significand, int exponent) {
|
38 |
+
ASSERT(significand != 0);
|
39 |
+
while ((significand & Double::kHiddenBit) == 0) {
|
40 |
+
significand = significand << 1;
|
41 |
+
exponent = exponent - 1;
|
42 |
+
}
|
43 |
+
return exponent;
|
44 |
+
}
|
45 |
+
|
46 |
+
|
47 |
+
// Forward declarations:
|
48 |
+
// Returns an estimation of k such that 10^(k-1) <= v < 10^k.
|
49 |
+
static int EstimatePower(int exponent);
|
50 |
+
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
|
51 |
+
// and denominator.
|
52 |
+
static void InitialScaledStartValues(uint64_t significand,
|
53 |
+
int exponent,
|
54 |
+
bool lower_boundary_is_closer,
|
55 |
+
int estimated_power,
|
56 |
+
bool need_boundary_deltas,
|
57 |
+
Bignum* numerator,
|
58 |
+
Bignum* denominator,
|
59 |
+
Bignum* delta_minus,
|
60 |
+
Bignum* delta_plus);
|
61 |
+
// Multiplies numerator/denominator so that its values lies in the range 1-10.
|
62 |
+
// Returns decimal_point s.t.
|
63 |
+
// v = numerator'/denominator' * 10^(decimal_point-1)
|
64 |
+
// where numerator' and denominator' are the values of numerator and
|
65 |
+
// denominator after the call to this function.
|
66 |
+
static void FixupMultiply10(int estimated_power, bool is_even,
|
67 |
+
int* decimal_point,
|
68 |
+
Bignum* numerator, Bignum* denominator,
|
69 |
+
Bignum* delta_minus, Bignum* delta_plus);
|
70 |
+
// Generates digits from the left to the right and stops when the generated
|
71 |
+
// digits yield the shortest decimal representation of v.
|
72 |
+
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
73 |
+
Bignum* delta_minus, Bignum* delta_plus,
|
74 |
+
bool is_even,
|
75 |
+
Vector<char> buffer, int* length);
|
76 |
+
// Generates 'requested_digits' after the decimal point.
|
77 |
+
static void BignumToFixed(int requested_digits, int* decimal_point,
|
78 |
+
Bignum* numerator, Bignum* denominator,
|
79 |
+
Vector<char>(buffer), int* length);
|
80 |
+
// Generates 'count' digits of numerator/denominator.
|
81 |
+
// Once 'count' digits have been produced rounds the result depending on the
|
82 |
+
// remainder (remainders of exactly .5 round upwards). Might update the
|
83 |
+
// decimal_point when rounding up (for example for 0.9999).
|
84 |
+
static void GenerateCountedDigits(int count, int* decimal_point,
|
85 |
+
Bignum* numerator, Bignum* denominator,
|
86 |
+
Vector<char>(buffer), int* length);
|
87 |
+
|
88 |
+
|
89 |
+
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
90 |
+
Vector<char> buffer, int* length, int* decimal_point) {
|
91 |
+
ASSERT(v > 0);
|
92 |
+
ASSERT(!Double(v).IsSpecial());
|
93 |
+
uint64_t significand;
|
94 |
+
int exponent;
|
95 |
+
bool lower_boundary_is_closer;
|
96 |
+
if (mode == BIGNUM_DTOA_SHORTEST_SINGLE) {
|
97 |
+
float f = static_cast<float>(v);
|
98 |
+
ASSERT(f == v);
|
99 |
+
significand = Single(f).Significand();
|
100 |
+
exponent = Single(f).Exponent();
|
101 |
+
lower_boundary_is_closer = Single(f).LowerBoundaryIsCloser();
|
102 |
+
} else {
|
103 |
+
significand = Double(v).Significand();
|
104 |
+
exponent = Double(v).Exponent();
|
105 |
+
lower_boundary_is_closer = Double(v).LowerBoundaryIsCloser();
|
106 |
+
}
|
107 |
+
bool need_boundary_deltas =
|
108 |
+
(mode == BIGNUM_DTOA_SHORTEST || mode == BIGNUM_DTOA_SHORTEST_SINGLE);
|
109 |
+
|
110 |
+
bool is_even = (significand & 1) == 0;
|
111 |
+
int normalized_exponent = NormalizedExponent(significand, exponent);
|
112 |
+
// estimated_power might be too low by 1.
|
113 |
+
int estimated_power = EstimatePower(normalized_exponent);
|
114 |
+
|
115 |
+
// Shortcut for Fixed.
|
116 |
+
// The requested digits correspond to the digits after the point. If the
|
117 |
+
// number is much too small, then there is no need in trying to get any
|
118 |
+
// digits.
|
119 |
+
if (mode == BIGNUM_DTOA_FIXED && -estimated_power - 1 > requested_digits) {
|
120 |
+
buffer[0] = '\0';
|
121 |
+
*length = 0;
|
122 |
+
// Set decimal-point to -requested_digits. This is what Gay does.
|
123 |
+
// Note that it should not have any effect anyways since the string is
|
124 |
+
// empty.
|
125 |
+
*decimal_point = -requested_digits;
|
126 |
+
return;
|
127 |
+
}
|
128 |
+
|
129 |
+
Bignum numerator;
|
130 |
+
Bignum denominator;
|
131 |
+
Bignum delta_minus;
|
132 |
+
Bignum delta_plus;
|
133 |
+
// Make sure the bignum can grow large enough. The smallest double equals
|
134 |
+
// 4e-324. In this case the denominator needs fewer than 324*4 binary digits.
|
135 |
+
// The maximum double is 1.7976931348623157e308 which needs fewer than
|
136 |
+
// 308*4 binary digits.
|
137 |
+
ASSERT(Bignum::kMaxSignificantBits >= 324*4);
|
138 |
+
InitialScaledStartValues(significand, exponent, lower_boundary_is_closer,
|
139 |
+
estimated_power, need_boundary_deltas,
|
140 |
+
&numerator, &denominator,
|
141 |
+
&delta_minus, &delta_plus);
|
142 |
+
// We now have v = (numerator / denominator) * 10^estimated_power.
|
143 |
+
FixupMultiply10(estimated_power, is_even, decimal_point,
|
144 |
+
&numerator, &denominator,
|
145 |
+
&delta_minus, &delta_plus);
|
146 |
+
// We now have v = (numerator / denominator) * 10^(decimal_point-1), and
|
147 |
+
// 1 <= (numerator + delta_plus) / denominator < 10
|
148 |
+
switch (mode) {
|
149 |
+
case BIGNUM_DTOA_SHORTEST:
|
150 |
+
case BIGNUM_DTOA_SHORTEST_SINGLE:
|
151 |
+
GenerateShortestDigits(&numerator, &denominator,
|
152 |
+
&delta_minus, &delta_plus,
|
153 |
+
is_even, buffer, length);
|
154 |
+
break;
|
155 |
+
case BIGNUM_DTOA_FIXED:
|
156 |
+
BignumToFixed(requested_digits, decimal_point,
|
157 |
+
&numerator, &denominator,
|
158 |
+
buffer, length);
|
159 |
+
break;
|
160 |
+
case BIGNUM_DTOA_PRECISION:
|
161 |
+
GenerateCountedDigits(requested_digits, decimal_point,
|
162 |
+
&numerator, &denominator,
|
163 |
+
buffer, length);
|
164 |
+
break;
|
165 |
+
default:
|
166 |
+
UNREACHABLE();
|
167 |
+
}
|
168 |
+
buffer[*length] = '\0';
|
169 |
+
}
|
170 |
+
|
171 |
+
|
172 |
+
// The procedure starts generating digits from the left to the right and stops
|
173 |
+
// when the generated digits yield the shortest decimal representation of v. A
|
174 |
+
// decimal representation of v is a number lying closer to v than to any other
|
175 |
+
// double, so it converts to v when read.
|
176 |
+
//
|
177 |
+
// This is true if d, the decimal representation, is between m- and m+, the
|
178 |
+
// upper and lower boundaries. d must be strictly between them if !is_even.
|
179 |
+
// m- := (numerator - delta_minus) / denominator
|
180 |
+
// m+ := (numerator + delta_plus) / denominator
|
181 |
+
//
|
182 |
+
// Precondition: 0 <= (numerator+delta_plus) / denominator < 10.
|
183 |
+
// If 1 <= (numerator+delta_plus) / denominator < 10 then no leading 0 digit
|
184 |
+
// will be produced. This should be the standard precondition.
|
185 |
+
static void GenerateShortestDigits(Bignum* numerator, Bignum* denominator,
|
186 |
+
Bignum* delta_minus, Bignum* delta_plus,
|
187 |
+
bool is_even,
|
188 |
+
Vector<char> buffer, int* length) {
|
189 |
+
// Small optimization: if delta_minus and delta_plus are the same just reuse
|
190 |
+
// one of the two bignums.
|
191 |
+
if (Bignum::Equal(*delta_minus, *delta_plus)) {
|
192 |
+
delta_plus = delta_minus;
|
193 |
+
}
|
194 |
+
*length = 0;
|
195 |
+
for (;;) {
|
196 |
+
uint16_t digit;
|
197 |
+
digit = numerator->DivideModuloIntBignum(*denominator);
|
198 |
+
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
199 |
+
// digit = numerator / denominator (integer division).
|
200 |
+
// numerator = numerator % denominator.
|
201 |
+
buffer[(*length)++] = static_cast<char>(digit + '0');
|
202 |
+
|
203 |
+
// Can we stop already?
|
204 |
+
// If the remainder of the division is less than the distance to the lower
|
205 |
+
// boundary we can stop. In this case we simply round down (discarding the
|
206 |
+
// remainder).
|
207 |
+
// Similarly we test if we can round up (using the upper boundary).
|
208 |
+
bool in_delta_room_minus;
|
209 |
+
bool in_delta_room_plus;
|
210 |
+
if (is_even) {
|
211 |
+
in_delta_room_minus = Bignum::LessEqual(*numerator, *delta_minus);
|
212 |
+
} else {
|
213 |
+
in_delta_room_minus = Bignum::Less(*numerator, *delta_minus);
|
214 |
+
}
|
215 |
+
if (is_even) {
|
216 |
+
in_delta_room_plus =
|
217 |
+
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
|
218 |
+
} else {
|
219 |
+
in_delta_room_plus =
|
220 |
+
Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
|
221 |
+
}
|
222 |
+
if (!in_delta_room_minus && !in_delta_room_plus) {
|
223 |
+
// Prepare for next iteration.
|
224 |
+
numerator->Times10();
|
225 |
+
delta_minus->Times10();
|
226 |
+
// We optimized delta_plus to be equal to delta_minus (if they share the
|
227 |
+
// same value). So don't multiply delta_plus if they point to the same
|
228 |
+
// object.
|
229 |
+
if (delta_minus != delta_plus) {
|
230 |
+
delta_plus->Times10();
|
231 |
+
}
|
232 |
+
} else if (in_delta_room_minus && in_delta_room_plus) {
|
233 |
+
// Let's see if 2*numerator < denominator.
|
234 |
+
// If yes, then the next digit would be < 5 and we can round down.
|
235 |
+
int compare = Bignum::PlusCompare(*numerator, *numerator, *denominator);
|
236 |
+
if (compare < 0) {
|
237 |
+
// Remaining digits are less than .5. -> Round down (== do nothing).
|
238 |
+
} else if (compare > 0) {
|
239 |
+
// Remaining digits are more than .5 of denominator. -> Round up.
|
240 |
+
// Note that the last digit could not be a '9' as otherwise the whole
|
241 |
+
// loop would have stopped earlier.
|
242 |
+
// We still have an assert here in case the preconditions were not
|
243 |
+
// satisfied.
|
244 |
+
ASSERT(buffer[(*length) - 1] != '9');
|
245 |
+
buffer[(*length) - 1]++;
|
246 |
+
} else {
|
247 |
+
// Halfway case.
|
248 |
+
// TODO(floitsch): need a way to solve half-way cases.
|
249 |
+
// For now let's round towards even (since this is what Gay seems to
|
250 |
+
// do).
|
251 |
+
|
252 |
+
if ((buffer[(*length) - 1] - '0') % 2 == 0) {
|
253 |
+
// Round down => Do nothing.
|
254 |
+
} else {
|
255 |
+
ASSERT(buffer[(*length) - 1] != '9');
|
256 |
+
buffer[(*length) - 1]++;
|
257 |
+
}
|
258 |
+
}
|
259 |
+
return;
|
260 |
+
} else if (in_delta_room_minus) {
|
261 |
+
// Round down (== do nothing).
|
262 |
+
return;
|
263 |
+
} else { // in_delta_room_plus
|
264 |
+
// Round up.
|
265 |
+
// Note again that the last digit could not be '9' since this would have
|
266 |
+
// stopped the loop earlier.
|
267 |
+
// We still have an ASSERT here, in case the preconditions were not
|
268 |
+
// satisfied.
|
269 |
+
ASSERT(buffer[(*length) -1] != '9');
|
270 |
+
buffer[(*length) - 1]++;
|
271 |
+
return;
|
272 |
+
}
|
273 |
+
}
|
274 |
+
}
|
275 |
+
|
276 |
+
|
277 |
+
// Let v = numerator / denominator < 10.
|
278 |
+
// Then we generate 'count' digits of d = x.xxxxx... (without the decimal point)
|
279 |
+
// from left to right. Once 'count' digits have been produced we decide wether
|
280 |
+
// to round up or down. Remainders of exactly .5 round upwards. Numbers such
|
281 |
+
// as 9.999999 propagate a carry all the way, and change the
|
282 |
+
// exponent (decimal_point), when rounding upwards.
|
283 |
+
static void GenerateCountedDigits(int count, int* decimal_point,
|
284 |
+
Bignum* numerator, Bignum* denominator,
|
285 |
+
Vector<char> buffer, int* length) {
|
286 |
+
ASSERT(count >= 0);
|
287 |
+
for (int i = 0; i < count - 1; ++i) {
|
288 |
+
uint16_t digit;
|
289 |
+
digit = numerator->DivideModuloIntBignum(*denominator);
|
290 |
+
ASSERT(digit <= 9); // digit is a uint16_t and therefore always positive.
|
291 |
+
// digit = numerator / denominator (integer division).
|
292 |
+
// numerator = numerator % denominator.
|
293 |
+
buffer[i] = static_cast<char>(digit + '0');
|
294 |
+
// Prepare for next iteration.
|
295 |
+
numerator->Times10();
|
296 |
+
}
|
297 |
+
// Generate the last digit.
|
298 |
+
uint16_t digit;
|
299 |
+
digit = numerator->DivideModuloIntBignum(*denominator);
|
300 |
+
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
301 |
+
digit++;
|
302 |
+
}
|
303 |
+
ASSERT(digit <= 10);
|
304 |
+
buffer[count - 1] = static_cast<char>(digit + '0');
|
305 |
+
// Correct bad digits (in case we had a sequence of '9's). Propagate the
|
306 |
+
// carry until we hat a non-'9' or til we reach the first digit.
|
307 |
+
for (int i = count - 1; i > 0; --i) {
|
308 |
+
if (buffer[i] != '0' + 10) break;
|
309 |
+
buffer[i] = '0';
|
310 |
+
buffer[i - 1]++;
|
311 |
+
}
|
312 |
+
if (buffer[0] == '0' + 10) {
|
313 |
+
// Propagate a carry past the top place.
|
314 |
+
buffer[0] = '1';
|
315 |
+
(*decimal_point)++;
|
316 |
+
}
|
317 |
+
*length = count;
|
318 |
+
}
|
319 |
+
|
320 |
+
|
321 |
+
// Generates 'requested_digits' after the decimal point. It might omit
|
322 |
+
// trailing '0's. If the input number is too small then no digits at all are
|
323 |
+
// generated (ex.: 2 fixed digits for 0.00001).
|
324 |
+
//
|
325 |
+
// Input verifies: 1 <= (numerator + delta) / denominator < 10.
|
326 |
+
static void BignumToFixed(int requested_digits, int* decimal_point,
|
327 |
+
Bignum* numerator, Bignum* denominator,
|
328 |
+
Vector<char>(buffer), int* length) {
|
329 |
+
// Note that we have to look at more than just the requested_digits, since
|
330 |
+
// a number could be rounded up. Example: v=0.5 with requested_digits=0.
|
331 |
+
// Even though the power of v equals 0 we can't just stop here.
|
332 |
+
if (-(*decimal_point) > requested_digits) {
|
333 |
+
// The number is definitively too small.
|
334 |
+
// Ex: 0.001 with requested_digits == 1.
|
335 |
+
// Set decimal-point to -requested_digits. This is what Gay does.
|
336 |
+
// Note that it should not have any effect anyways since the string is
|
337 |
+
// empty.
|
338 |
+
*decimal_point = -requested_digits;
|
339 |
+
*length = 0;
|
340 |
+
return;
|
341 |
+
} else if (-(*decimal_point) == requested_digits) {
|
342 |
+
// We only need to verify if the number rounds down or up.
|
343 |
+
// Ex: 0.04 and 0.06 with requested_digits == 1.
|
344 |
+
ASSERT(*decimal_point == -requested_digits);
|
345 |
+
// Initially the fraction lies in range (1, 10]. Multiply the denominator
|
346 |
+
// by 10 so that we can compare more easily.
|
347 |
+
denominator->Times10();
|
348 |
+
if (Bignum::PlusCompare(*numerator, *numerator, *denominator) >= 0) {
|
349 |
+
// If the fraction is >= 0.5 then we have to include the rounded
|
350 |
+
// digit.
|
351 |
+
buffer[0] = '1';
|
352 |
+
*length = 1;
|
353 |
+
(*decimal_point)++;
|
354 |
+
} else {
|
355 |
+
// Note that we caught most of similar cases earlier.
|
356 |
+
*length = 0;
|
357 |
+
}
|
358 |
+
return;
|
359 |
+
} else {
|
360 |
+
// The requested digits correspond to the digits after the point.
|
361 |
+
// The variable 'needed_digits' includes the digits before the point.
|
362 |
+
int needed_digits = (*decimal_point) + requested_digits;
|
363 |
+
GenerateCountedDigits(needed_digits, decimal_point,
|
364 |
+
numerator, denominator,
|
365 |
+
buffer, length);
|
366 |
+
}
|
367 |
+
}
|
368 |
+
|
369 |
+
|
370 |
+
// Returns an estimation of k such that 10^(k-1) <= v < 10^k where
|
371 |
+
// v = f * 2^exponent and 2^52 <= f < 2^53.
|
372 |
+
// v is hence a normalized double with the given exponent. The output is an
|
373 |
+
// approximation for the exponent of the decimal approimation .digits * 10^k.
|
374 |
+
//
|
375 |
+
// The result might undershoot by 1 in which case 10^k <= v < 10^k+1.
|
376 |
+
// Note: this property holds for v's upper boundary m+ too.
|
377 |
+
// 10^k <= m+ < 10^k+1.
|
378 |
+
// (see explanation below).
|
379 |
+
//
|
380 |
+
// Examples:
|
381 |
+
// EstimatePower(0) => 16
|
382 |
+
// EstimatePower(-52) => 0
|
383 |
+
//
|
384 |
+
// Note: e >= 0 => EstimatedPower(e) > 0. No similar claim can be made for e<0.
|
385 |
+
static int EstimatePower(int exponent) {
|
386 |
+
// This function estimates log10 of v where v = f*2^e (with e == exponent).
|
387 |
+
// Note that 10^floor(log10(v)) <= v, but v <= 10^ceil(log10(v)).
|
388 |
+
// Note that f is bounded by its container size. Let p = 53 (the double's
|
389 |
+
// significand size). Then 2^(p-1) <= f < 2^p.
|
390 |
+
//
|
391 |
+
// Given that log10(v) == log2(v)/log2(10) and e+(len(f)-1) is quite close
|
392 |
+
// to log2(v) the function is simplified to (e+(len(f)-1)/log2(10)).
|
393 |
+
// The computed number undershoots by less than 0.631 (when we compute log3
|
394 |
+
// and not log10).
|
395 |
+
//
|
396 |
+
// Optimization: since we only need an approximated result this computation
|
397 |
+
// can be performed on 64 bit integers. On x86/x64 architecture the speedup is
|
398 |
+
// not really measurable, though.
|
399 |
+
//
|
400 |
+
// Since we want to avoid overshooting we decrement by 1e10 so that
|
401 |
+
// floating-point imprecisions don't affect us.
|
402 |
+
//
|
403 |
+
// Explanation for v's boundary m+: the computation takes advantage of
|
404 |
+
// the fact that 2^(p-1) <= f < 2^p. Boundaries still satisfy this requirement
|
405 |
+
// (even for denormals where the delta can be much more important).
|
406 |
+
|
407 |
+
const double k1Log10 = 0.30102999566398114; // 1/lg(10)
|
408 |
+
|
409 |
+
// For doubles len(f) == 53 (don't forget the hidden bit).
|
410 |
+
const int kSignificandSize = Double::kSignificandSize;
|
411 |
+
double estimate = ceil((exponent + kSignificandSize - 1) * k1Log10 - 1e-10);
|
412 |
+
return static_cast<int>(estimate);
|
413 |
+
}
|
414 |
+
|
415 |
+
|
416 |
+
// See comments for InitialScaledStartValues.
|
417 |
+
static void InitialScaledStartValuesPositiveExponent(
|
418 |
+
uint64_t significand, int exponent,
|
419 |
+
int estimated_power, bool need_boundary_deltas,
|
420 |
+
Bignum* numerator, Bignum* denominator,
|
421 |
+
Bignum* delta_minus, Bignum* delta_plus) {
|
422 |
+
// A positive exponent implies a positive power.
|
423 |
+
ASSERT(estimated_power >= 0);
|
424 |
+
// Since the estimated_power is positive we simply multiply the denominator
|
425 |
+
// by 10^estimated_power.
|
426 |
+
|
427 |
+
// numerator = v.
|
428 |
+
numerator->AssignUInt64(significand);
|
429 |
+
numerator->ShiftLeft(exponent);
|
430 |
+
// denominator = 10^estimated_power.
|
431 |
+
denominator->AssignPowerUInt16(10, estimated_power);
|
432 |
+
|
433 |
+
if (need_boundary_deltas) {
|
434 |
+
// Introduce a common denominator so that the deltas to the boundaries are
|
435 |
+
// integers.
|
436 |
+
denominator->ShiftLeft(1);
|
437 |
+
numerator->ShiftLeft(1);
|
438 |
+
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
|
439 |
+
// denominator (of 2) delta_plus equals 2^e.
|
440 |
+
delta_plus->AssignUInt16(1);
|
441 |
+
delta_plus->ShiftLeft(exponent);
|
442 |
+
// Same for delta_minus. The adjustments if f == 2^p-1 are done later.
|
443 |
+
delta_minus->AssignUInt16(1);
|
444 |
+
delta_minus->ShiftLeft(exponent);
|
445 |
+
}
|
446 |
+
}
|
447 |
+
|
448 |
+
|
449 |
+
// See comments for InitialScaledStartValues
|
450 |
+
static void InitialScaledStartValuesNegativeExponentPositivePower(
|
451 |
+
uint64_t significand, int exponent,
|
452 |
+
int estimated_power, bool need_boundary_deltas,
|
453 |
+
Bignum* numerator, Bignum* denominator,
|
454 |
+
Bignum* delta_minus, Bignum* delta_plus) {
|
455 |
+
// v = f * 2^e with e < 0, and with estimated_power >= 0.
|
456 |
+
// This means that e is close to 0 (have a look at how estimated_power is
|
457 |
+
// computed).
|
458 |
+
|
459 |
+
// numerator = significand
|
460 |
+
// since v = significand * 2^exponent this is equivalent to
|
461 |
+
// numerator = v * / 2^-exponent
|
462 |
+
numerator->AssignUInt64(significand);
|
463 |
+
// denominator = 10^estimated_power * 2^-exponent (with exponent < 0)
|
464 |
+
denominator->AssignPowerUInt16(10, estimated_power);
|
465 |
+
denominator->ShiftLeft(-exponent);
|
466 |
+
|
467 |
+
if (need_boundary_deltas) {
|
468 |
+
// Introduce a common denominator so that the deltas to the boundaries are
|
469 |
+
// integers.
|
470 |
+
denominator->ShiftLeft(1);
|
471 |
+
numerator->ShiftLeft(1);
|
472 |
+
// Let v = f * 2^e, then m+ - v = 1/2 * 2^e; With the common
|
473 |
+
// denominator (of 2) delta_plus equals 2^e.
|
474 |
+
// Given that the denominator already includes v's exponent the distance
|
475 |
+
// to the boundaries is simply 1.
|
476 |
+
delta_plus->AssignUInt16(1);
|
477 |
+
// Same for delta_minus. The adjustments if f == 2^p-1 are done later.
|
478 |
+
delta_minus->AssignUInt16(1);
|
479 |
+
}
|
480 |
+
}
|
481 |
+
|
482 |
+
|
483 |
+
// See comments for InitialScaledStartValues
|
484 |
+
static void InitialScaledStartValuesNegativeExponentNegativePower(
|
485 |
+
uint64_t significand, int exponent,
|
486 |
+
int estimated_power, bool need_boundary_deltas,
|
487 |
+
Bignum* numerator, Bignum* denominator,
|
488 |
+
Bignum* delta_minus, Bignum* delta_plus) {
|
489 |
+
// Instead of multiplying the denominator with 10^estimated_power we
|
490 |
+
// multiply all values (numerator and deltas) by 10^-estimated_power.
|
491 |
+
|
492 |
+
// Use numerator as temporary container for power_ten.
|
493 |
+
Bignum* power_ten = numerator;
|
494 |
+
power_ten->AssignPowerUInt16(10, -estimated_power);
|
495 |
+
|
496 |
+
if (need_boundary_deltas) {
|
497 |
+
// Since power_ten == numerator we must make a copy of 10^estimated_power
|
498 |
+
// before we complete the computation of the numerator.
|
499 |
+
// delta_plus = delta_minus = 10^estimated_power
|
500 |
+
delta_plus->AssignBignum(*power_ten);
|
501 |
+
delta_minus->AssignBignum(*power_ten);
|
502 |
+
}
|
503 |
+
|
504 |
+
// numerator = significand * 2 * 10^-estimated_power
|
505 |
+
// since v = significand * 2^exponent this is equivalent to
|
506 |
+
// numerator = v * 10^-estimated_power * 2 * 2^-exponent.
|
507 |
+
// Remember: numerator has been abused as power_ten. So no need to assign it
|
508 |
+
// to itself.
|
509 |
+
ASSERT(numerator == power_ten);
|
510 |
+
numerator->MultiplyByUInt64(significand);
|
511 |
+
|
512 |
+
// denominator = 2 * 2^-exponent with exponent < 0.
|
513 |
+
denominator->AssignUInt16(1);
|
514 |
+
denominator->ShiftLeft(-exponent);
|
515 |
+
|
516 |
+
if (need_boundary_deltas) {
|
517 |
+
// Introduce a common denominator so that the deltas to the boundaries are
|
518 |
+
// integers.
|
519 |
+
numerator->ShiftLeft(1);
|
520 |
+
denominator->ShiftLeft(1);
|
521 |
+
// With this shift the boundaries have their correct value, since
|
522 |
+
// delta_plus = 10^-estimated_power, and
|
523 |
+
// delta_minus = 10^-estimated_power.
|
524 |
+
// These assignments have been done earlier.
|
525 |
+
// The adjustments if f == 2^p-1 (lower boundary is closer) are done later.
|
526 |
+
}
|
527 |
+
}
|
528 |
+
|
529 |
+
|
530 |
+
// Let v = significand * 2^exponent.
|
531 |
+
// Computes v / 10^estimated_power exactly, as a ratio of two bignums, numerator
|
532 |
+
// and denominator. The functions GenerateShortestDigits and
|
533 |
+
// GenerateCountedDigits will then convert this ratio to its decimal
|
534 |
+
// representation d, with the required accuracy.
|
535 |
+
// Then d * 10^estimated_power is the representation of v.
|
536 |
+
// (Note: the fraction and the estimated_power might get adjusted before
|
537 |
+
// generating the decimal representation.)
|
538 |
+
//
|
539 |
+
// The initial start values consist of:
|
540 |
+
// - a scaled numerator: s.t. numerator/denominator == v / 10^estimated_power.
|
541 |
+
// - a scaled (common) denominator.
|
542 |
+
// optionally (used by GenerateShortestDigits to decide if it has the shortest
|
543 |
+
// decimal converting back to v):
|
544 |
+
// - v - m-: the distance to the lower boundary.
|
545 |
+
// - m+ - v: the distance to the upper boundary.
|
546 |
+
//
|
547 |
+
// v, m+, m-, and therefore v - m- and m+ - v all share the same denominator.
|
548 |
+
//
|
549 |
+
// Let ep == estimated_power, then the returned values will satisfy:
|
550 |
+
// v / 10^ep = numerator / denominator.
|
551 |
+
// v's boundarys m- and m+:
|
552 |
+
// m- / 10^ep == v / 10^ep - delta_minus / denominator
|
553 |
+
// m+ / 10^ep == v / 10^ep + delta_plus / denominator
|
554 |
+
// Or in other words:
|
555 |
+
// m- == v - delta_minus * 10^ep / denominator;
|
556 |
+
// m+ == v + delta_plus * 10^ep / denominator;
|
557 |
+
//
|
558 |
+
// Since 10^(k-1) <= v < 10^k (with k == estimated_power)
|
559 |
+
// or 10^k <= v < 10^(k+1)
|
560 |
+
// we then have 0.1 <= numerator/denominator < 1
|
561 |
+
// or 1 <= numerator/denominator < 10
|
562 |
+
//
|
563 |
+
// It is then easy to kickstart the digit-generation routine.
|
564 |
+
//
|
565 |
+
// The boundary-deltas are only filled if the mode equals BIGNUM_DTOA_SHORTEST
|
566 |
+
// or BIGNUM_DTOA_SHORTEST_SINGLE.
|
567 |
+
|
568 |
+
static void InitialScaledStartValues(uint64_t significand,
|
569 |
+
int exponent,
|
570 |
+
bool lower_boundary_is_closer,
|
571 |
+
int estimated_power,
|
572 |
+
bool need_boundary_deltas,
|
573 |
+
Bignum* numerator,
|
574 |
+
Bignum* denominator,
|
575 |
+
Bignum* delta_minus,
|
576 |
+
Bignum* delta_plus) {
|
577 |
+
if (exponent >= 0) {
|
578 |
+
InitialScaledStartValuesPositiveExponent(
|
579 |
+
significand, exponent, estimated_power, need_boundary_deltas,
|
580 |
+
numerator, denominator, delta_minus, delta_plus);
|
581 |
+
} else if (estimated_power >= 0) {
|
582 |
+
InitialScaledStartValuesNegativeExponentPositivePower(
|
583 |
+
significand, exponent, estimated_power, need_boundary_deltas,
|
584 |
+
numerator, denominator, delta_minus, delta_plus);
|
585 |
+
} else {
|
586 |
+
InitialScaledStartValuesNegativeExponentNegativePower(
|
587 |
+
significand, exponent, estimated_power, need_boundary_deltas,
|
588 |
+
numerator, denominator, delta_minus, delta_plus);
|
589 |
+
}
|
590 |
+
|
591 |
+
if (need_boundary_deltas && lower_boundary_is_closer) {
|
592 |
+
// The lower boundary is closer at half the distance of "normal" numbers.
|
593 |
+
// Increase the common denominator and adapt all but the delta_minus.
|
594 |
+
denominator->ShiftLeft(1); // *2
|
595 |
+
numerator->ShiftLeft(1); // *2
|
596 |
+
delta_plus->ShiftLeft(1); // *2
|
597 |
+
}
|
598 |
+
}
|
599 |
+
|
600 |
+
|
601 |
+
// This routine multiplies numerator/denominator so that its values lies in the
|
602 |
+
// range 1-10. That is after a call to this function we have:
|
603 |
+
// 1 <= (numerator + delta_plus) /denominator < 10.
|
604 |
+
// Let numerator the input before modification and numerator' the argument
|
605 |
+
// after modification, then the output-parameter decimal_point is such that
|
606 |
+
// numerator / denominator * 10^estimated_power ==
|
607 |
+
// numerator' / denominator' * 10^(decimal_point - 1)
|
608 |
+
// In some cases estimated_power was too low, and this is already the case. We
|
609 |
+
// then simply adjust the power so that 10^(k-1) <= v < 10^k (with k ==
|
610 |
+
// estimated_power) but do not touch the numerator or denominator.
|
611 |
+
// Otherwise the routine multiplies the numerator and the deltas by 10.
|
612 |
+
static void FixupMultiply10(int estimated_power, bool is_even,
|
613 |
+
int* decimal_point,
|
614 |
+
Bignum* numerator, Bignum* denominator,
|
615 |
+
Bignum* delta_minus, Bignum* delta_plus) {
|
616 |
+
bool in_range;
|
617 |
+
if (is_even) {
|
618 |
+
// For IEEE doubles half-way cases (in decimal system numbers ending with 5)
|
619 |
+
// are rounded to the closest floating-point number with even significand.
|
620 |
+
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) >= 0;
|
621 |
+
} else {
|
622 |
+
in_range = Bignum::PlusCompare(*numerator, *delta_plus, *denominator) > 0;
|
623 |
+
}
|
624 |
+
if (in_range) {
|
625 |
+
// Since numerator + delta_plus >= denominator we already have
|
626 |
+
// 1 <= numerator/denominator < 10. Simply update the estimated_power.
|
627 |
+
*decimal_point = estimated_power + 1;
|
628 |
+
} else {
|
629 |
+
*decimal_point = estimated_power;
|
630 |
+
numerator->Times10();
|
631 |
+
if (Bignum::Equal(*delta_minus, *delta_plus)) {
|
632 |
+
delta_minus->Times10();
|
633 |
+
delta_plus->AssignBignum(*delta_minus);
|
634 |
+
} else {
|
635 |
+
delta_minus->Times10();
|
636 |
+
delta_plus->Times10();
|
637 |
+
}
|
638 |
+
}
|
639 |
+
}
|
640 |
+
|
641 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum-dtoa.h
ADDED
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
29 |
+
#define DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
enum BignumDtoaMode {
|
36 |
+
// Return the shortest correct representation.
|
37 |
+
// For example the output of 0.299999999999999988897 is (the less accurate but
|
38 |
+
// correct) 0.3.
|
39 |
+
BIGNUM_DTOA_SHORTEST,
|
40 |
+
// Same as BIGNUM_DTOA_SHORTEST but for single-precision floats.
|
41 |
+
BIGNUM_DTOA_SHORTEST_SINGLE,
|
42 |
+
// Return a fixed number of digits after the decimal point.
|
43 |
+
// For instance fixed(0.1, 4) becomes 0.1000
|
44 |
+
// If the input number is big, the output will be big.
|
45 |
+
BIGNUM_DTOA_FIXED,
|
46 |
+
// Return a fixed number of digits, no matter what the exponent is.
|
47 |
+
BIGNUM_DTOA_PRECISION
|
48 |
+
};
|
49 |
+
|
50 |
+
// Converts the given double 'v' to ascii.
|
51 |
+
// The result should be interpreted as buffer * 10^(point-length).
|
52 |
+
// The buffer will be null-terminated.
|
53 |
+
//
|
54 |
+
// The input v must be > 0 and different from NaN, and Infinity.
|
55 |
+
//
|
56 |
+
// The output depends on the given mode:
|
57 |
+
// - SHORTEST: produce the least amount of digits for which the internal
|
58 |
+
// identity requirement is still satisfied. If the digits are printed
|
59 |
+
// (together with the correct exponent) then reading this number will give
|
60 |
+
// 'v' again. The buffer will choose the representation that is closest to
|
61 |
+
// 'v'. If there are two at the same distance, than the number is round up.
|
62 |
+
// In this mode the 'requested_digits' parameter is ignored.
|
63 |
+
// - FIXED: produces digits necessary to print a given number with
|
64 |
+
// 'requested_digits' digits after the decimal point. The produced digits
|
65 |
+
// might be too short in which case the caller has to fill the gaps with '0's.
|
66 |
+
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
67 |
+
// Halfway cases are rounded up. The call toFixed(0.15, 2) thus returns
|
68 |
+
// buffer="2", point=0.
|
69 |
+
// Note: the length of the returned buffer has no meaning wrt the significance
|
70 |
+
// of its digits. That is, just because it contains '0's does not mean that
|
71 |
+
// any other digit would not satisfy the internal identity requirement.
|
72 |
+
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
73 |
+
// Even though the length of produced digits usually equals
|
74 |
+
// 'requested_digits', the function is allowed to return fewer digits, in
|
75 |
+
// which case the caller has to fill the missing digits with '0's.
|
76 |
+
// Halfway cases are again rounded up.
|
77 |
+
// 'BignumDtoa' expects the given buffer to be big enough to hold all digits
|
78 |
+
// and a terminating null-character.
|
79 |
+
void BignumDtoa(double v, BignumDtoaMode mode, int requested_digits,
|
80 |
+
Vector<char> buffer, int* length, int* point);
|
81 |
+
|
82 |
+
} // namespace double_conversion
|
83 |
+
|
84 |
+
#endif // DOUBLE_CONVERSION_BIGNUM_DTOA_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum.cc
ADDED
@@ -0,0 +1,766 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include "bignum.h"
|
29 |
+
#include "utils.h"
|
30 |
+
|
31 |
+
namespace double_conversion {
|
32 |
+
|
33 |
+
Bignum::Bignum()
|
34 |
+
: bigits_(bigits_buffer_, kBigitCapacity), used_digits_(0), exponent_(0) {
|
35 |
+
for (int i = 0; i < kBigitCapacity; ++i) {
|
36 |
+
bigits_[i] = 0;
|
37 |
+
}
|
38 |
+
}
|
39 |
+
|
40 |
+
|
41 |
+
template<typename S>
|
42 |
+
static int BitSize(S value) {
|
43 |
+
(void) value; // Mark variable as used.
|
44 |
+
return 8 * sizeof(value);
|
45 |
+
}
|
46 |
+
|
47 |
+
// Guaranteed to lie in one Bigit.
|
48 |
+
void Bignum::AssignUInt16(uint16_t value) {
|
49 |
+
ASSERT(kBigitSize >= BitSize(value));
|
50 |
+
Zero();
|
51 |
+
if (value == 0) return;
|
52 |
+
|
53 |
+
EnsureCapacity(1);
|
54 |
+
bigits_[0] = value;
|
55 |
+
used_digits_ = 1;
|
56 |
+
}
|
57 |
+
|
58 |
+
|
59 |
+
void Bignum::AssignUInt64(uint64_t value) {
|
60 |
+
const int kUInt64Size = 64;
|
61 |
+
|
62 |
+
Zero();
|
63 |
+
if (value == 0) return;
|
64 |
+
|
65 |
+
int needed_bigits = kUInt64Size / kBigitSize + 1;
|
66 |
+
EnsureCapacity(needed_bigits);
|
67 |
+
for (int i = 0; i < needed_bigits; ++i) {
|
68 |
+
bigits_[i] = value & kBigitMask;
|
69 |
+
value = value >> kBigitSize;
|
70 |
+
}
|
71 |
+
used_digits_ = needed_bigits;
|
72 |
+
Clamp();
|
73 |
+
}
|
74 |
+
|
75 |
+
|
76 |
+
void Bignum::AssignBignum(const Bignum& other) {
|
77 |
+
exponent_ = other.exponent_;
|
78 |
+
for (int i = 0; i < other.used_digits_; ++i) {
|
79 |
+
bigits_[i] = other.bigits_[i];
|
80 |
+
}
|
81 |
+
// Clear the excess digits (if there were any).
|
82 |
+
for (int i = other.used_digits_; i < used_digits_; ++i) {
|
83 |
+
bigits_[i] = 0;
|
84 |
+
}
|
85 |
+
used_digits_ = other.used_digits_;
|
86 |
+
}
|
87 |
+
|
88 |
+
|
89 |
+
static uint64_t ReadUInt64(Vector<const char> buffer,
|
90 |
+
int from,
|
91 |
+
int digits_to_read) {
|
92 |
+
uint64_t result = 0;
|
93 |
+
for (int i = from; i < from + digits_to_read; ++i) {
|
94 |
+
int digit = buffer[i] - '0';
|
95 |
+
ASSERT(0 <= digit && digit <= 9);
|
96 |
+
result = result * 10 + digit;
|
97 |
+
}
|
98 |
+
return result;
|
99 |
+
}
|
100 |
+
|
101 |
+
|
102 |
+
void Bignum::AssignDecimalString(Vector<const char> value) {
|
103 |
+
// 2^64 = 18446744073709551616 > 10^19
|
104 |
+
const int kMaxUint64DecimalDigits = 19;
|
105 |
+
Zero();
|
106 |
+
int length = value.length();
|
107 |
+
unsigned int pos = 0;
|
108 |
+
// Let's just say that each digit needs 4 bits.
|
109 |
+
while (length >= kMaxUint64DecimalDigits) {
|
110 |
+
uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
|
111 |
+
pos += kMaxUint64DecimalDigits;
|
112 |
+
length -= kMaxUint64DecimalDigits;
|
113 |
+
MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
|
114 |
+
AddUInt64(digits);
|
115 |
+
}
|
116 |
+
uint64_t digits = ReadUInt64(value, pos, length);
|
117 |
+
MultiplyByPowerOfTen(length);
|
118 |
+
AddUInt64(digits);
|
119 |
+
Clamp();
|
120 |
+
}
|
121 |
+
|
122 |
+
|
123 |
+
static int HexCharValue(char c) {
|
124 |
+
if ('0' <= c && c <= '9') return c - '0';
|
125 |
+
if ('a' <= c && c <= 'f') return 10 + c - 'a';
|
126 |
+
ASSERT('A' <= c && c <= 'F');
|
127 |
+
return 10 + c - 'A';
|
128 |
+
}
|
129 |
+
|
130 |
+
|
131 |
+
void Bignum::AssignHexString(Vector<const char> value) {
|
132 |
+
Zero();
|
133 |
+
int length = value.length();
|
134 |
+
|
135 |
+
int needed_bigits = length * 4 / kBigitSize + 1;
|
136 |
+
EnsureCapacity(needed_bigits);
|
137 |
+
int string_index = length - 1;
|
138 |
+
for (int i = 0; i < needed_bigits - 1; ++i) {
|
139 |
+
// These bigits are guaranteed to be "full".
|
140 |
+
Chunk current_bigit = 0;
|
141 |
+
for (int j = 0; j < kBigitSize / 4; j++) {
|
142 |
+
current_bigit += HexCharValue(value[string_index--]) << (j * 4);
|
143 |
+
}
|
144 |
+
bigits_[i] = current_bigit;
|
145 |
+
}
|
146 |
+
used_digits_ = needed_bigits - 1;
|
147 |
+
|
148 |
+
Chunk most_significant_bigit = 0; // Could be = 0;
|
149 |
+
for (int j = 0; j <= string_index; ++j) {
|
150 |
+
most_significant_bigit <<= 4;
|
151 |
+
most_significant_bigit += HexCharValue(value[j]);
|
152 |
+
}
|
153 |
+
if (most_significant_bigit != 0) {
|
154 |
+
bigits_[used_digits_] = most_significant_bigit;
|
155 |
+
used_digits_++;
|
156 |
+
}
|
157 |
+
Clamp();
|
158 |
+
}
|
159 |
+
|
160 |
+
|
161 |
+
void Bignum::AddUInt64(uint64_t operand) {
|
162 |
+
if (operand == 0) return;
|
163 |
+
Bignum other;
|
164 |
+
other.AssignUInt64(operand);
|
165 |
+
AddBignum(other);
|
166 |
+
}
|
167 |
+
|
168 |
+
|
169 |
+
void Bignum::AddBignum(const Bignum& other) {
|
170 |
+
ASSERT(IsClamped());
|
171 |
+
ASSERT(other.IsClamped());
|
172 |
+
|
173 |
+
// If this has a greater exponent than other append zero-bigits to this.
|
174 |
+
// After this call exponent_ <= other.exponent_.
|
175 |
+
Align(other);
|
176 |
+
|
177 |
+
// There are two possibilities:
|
178 |
+
// aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
|
179 |
+
// bbbbb 00000000
|
180 |
+
// ----------------
|
181 |
+
// ccccccccccc 0000
|
182 |
+
// or
|
183 |
+
// aaaaaaaaaa 0000
|
184 |
+
// bbbbbbbbb 0000000
|
185 |
+
// -----------------
|
186 |
+
// cccccccccccc 0000
|
187 |
+
// In both cases we might need a carry bigit.
|
188 |
+
|
189 |
+
EnsureCapacity(1 + Max(BigitLength(), other.BigitLength()) - exponent_);
|
190 |
+
Chunk carry = 0;
|
191 |
+
int bigit_pos = other.exponent_ - exponent_;
|
192 |
+
ASSERT(bigit_pos >= 0);
|
193 |
+
for (int i = 0; i < other.used_digits_; ++i) {
|
194 |
+
Chunk sum = bigits_[bigit_pos] + other.bigits_[i] + carry;
|
195 |
+
bigits_[bigit_pos] = sum & kBigitMask;
|
196 |
+
carry = sum >> kBigitSize;
|
197 |
+
bigit_pos++;
|
198 |
+
}
|
199 |
+
|
200 |
+
while (carry != 0) {
|
201 |
+
Chunk sum = bigits_[bigit_pos] + carry;
|
202 |
+
bigits_[bigit_pos] = sum & kBigitMask;
|
203 |
+
carry = sum >> kBigitSize;
|
204 |
+
bigit_pos++;
|
205 |
+
}
|
206 |
+
used_digits_ = Max(bigit_pos, used_digits_);
|
207 |
+
ASSERT(IsClamped());
|
208 |
+
}
|
209 |
+
|
210 |
+
|
211 |
+
void Bignum::SubtractBignum(const Bignum& other) {
|
212 |
+
ASSERT(IsClamped());
|
213 |
+
ASSERT(other.IsClamped());
|
214 |
+
// We require this to be bigger than other.
|
215 |
+
ASSERT(LessEqual(other, *this));
|
216 |
+
|
217 |
+
Align(other);
|
218 |
+
|
219 |
+
int offset = other.exponent_ - exponent_;
|
220 |
+
Chunk borrow = 0;
|
221 |
+
int i;
|
222 |
+
for (i = 0; i < other.used_digits_; ++i) {
|
223 |
+
ASSERT((borrow == 0) || (borrow == 1));
|
224 |
+
Chunk difference = bigits_[i + offset] - other.bigits_[i] - borrow;
|
225 |
+
bigits_[i + offset] = difference & kBigitMask;
|
226 |
+
borrow = difference >> (kChunkSize - 1);
|
227 |
+
}
|
228 |
+
while (borrow != 0) {
|
229 |
+
Chunk difference = bigits_[i + offset] - borrow;
|
230 |
+
bigits_[i + offset] = difference & kBigitMask;
|
231 |
+
borrow = difference >> (kChunkSize - 1);
|
232 |
+
++i;
|
233 |
+
}
|
234 |
+
Clamp();
|
235 |
+
}
|
236 |
+
|
237 |
+
|
238 |
+
void Bignum::ShiftLeft(int shift_amount) {
|
239 |
+
if (used_digits_ == 0) return;
|
240 |
+
exponent_ += shift_amount / kBigitSize;
|
241 |
+
int local_shift = shift_amount % kBigitSize;
|
242 |
+
EnsureCapacity(used_digits_ + 1);
|
243 |
+
BigitsShiftLeft(local_shift);
|
244 |
+
}
|
245 |
+
|
246 |
+
|
247 |
+
void Bignum::MultiplyByUInt32(uint32_t factor) {
|
248 |
+
if (factor == 1) return;
|
249 |
+
if (factor == 0) {
|
250 |
+
Zero();
|
251 |
+
return;
|
252 |
+
}
|
253 |
+
if (used_digits_ == 0) return;
|
254 |
+
|
255 |
+
// The product of a bigit with the factor is of size kBigitSize + 32.
|
256 |
+
// Assert that this number + 1 (for the carry) fits into double chunk.
|
257 |
+
ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
|
258 |
+
DoubleChunk carry = 0;
|
259 |
+
for (int i = 0; i < used_digits_; ++i) {
|
260 |
+
DoubleChunk product = static_cast<DoubleChunk>(factor) * bigits_[i] + carry;
|
261 |
+
bigits_[i] = static_cast<Chunk>(product & kBigitMask);
|
262 |
+
carry = (product >> kBigitSize);
|
263 |
+
}
|
264 |
+
while (carry != 0) {
|
265 |
+
EnsureCapacity(used_digits_ + 1);
|
266 |
+
bigits_[used_digits_] = carry & kBigitMask;
|
267 |
+
used_digits_++;
|
268 |
+
carry >>= kBigitSize;
|
269 |
+
}
|
270 |
+
}
|
271 |
+
|
272 |
+
|
273 |
+
void Bignum::MultiplyByUInt64(uint64_t factor) {
|
274 |
+
if (factor == 1) return;
|
275 |
+
if (factor == 0) {
|
276 |
+
Zero();
|
277 |
+
return;
|
278 |
+
}
|
279 |
+
ASSERT(kBigitSize < 32);
|
280 |
+
uint64_t carry = 0;
|
281 |
+
uint64_t low = factor & 0xFFFFFFFF;
|
282 |
+
uint64_t high = factor >> 32;
|
283 |
+
for (int i = 0; i < used_digits_; ++i) {
|
284 |
+
uint64_t product_low = low * bigits_[i];
|
285 |
+
uint64_t product_high = high * bigits_[i];
|
286 |
+
uint64_t tmp = (carry & kBigitMask) + product_low;
|
287 |
+
bigits_[i] = tmp & kBigitMask;
|
288 |
+
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
|
289 |
+
(product_high << (32 - kBigitSize));
|
290 |
+
}
|
291 |
+
while (carry != 0) {
|
292 |
+
EnsureCapacity(used_digits_ + 1);
|
293 |
+
bigits_[used_digits_] = carry & kBigitMask;
|
294 |
+
used_digits_++;
|
295 |
+
carry >>= kBigitSize;
|
296 |
+
}
|
297 |
+
}
|
298 |
+
|
299 |
+
|
300 |
+
void Bignum::MultiplyByPowerOfTen(int exponent) {
|
301 |
+
const uint64_t kFive27 = UINT64_2PART_C(0x6765c793, fa10079d);
|
302 |
+
const uint16_t kFive1 = 5;
|
303 |
+
const uint16_t kFive2 = kFive1 * 5;
|
304 |
+
const uint16_t kFive3 = kFive2 * 5;
|
305 |
+
const uint16_t kFive4 = kFive3 * 5;
|
306 |
+
const uint16_t kFive5 = kFive4 * 5;
|
307 |
+
const uint16_t kFive6 = kFive5 * 5;
|
308 |
+
const uint32_t kFive7 = kFive6 * 5;
|
309 |
+
const uint32_t kFive8 = kFive7 * 5;
|
310 |
+
const uint32_t kFive9 = kFive8 * 5;
|
311 |
+
const uint32_t kFive10 = kFive9 * 5;
|
312 |
+
const uint32_t kFive11 = kFive10 * 5;
|
313 |
+
const uint32_t kFive12 = kFive11 * 5;
|
314 |
+
const uint32_t kFive13 = kFive12 * 5;
|
315 |
+
const uint32_t kFive1_to_12[] =
|
316 |
+
{ kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
|
317 |
+
kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
|
318 |
+
|
319 |
+
ASSERT(exponent >= 0);
|
320 |
+
if (exponent == 0) return;
|
321 |
+
if (used_digits_ == 0) return;
|
322 |
+
|
323 |
+
// We shift by exponent at the end just before returning.
|
324 |
+
int remaining_exponent = exponent;
|
325 |
+
while (remaining_exponent >= 27) {
|
326 |
+
MultiplyByUInt64(kFive27);
|
327 |
+
remaining_exponent -= 27;
|
328 |
+
}
|
329 |
+
while (remaining_exponent >= 13) {
|
330 |
+
MultiplyByUInt32(kFive13);
|
331 |
+
remaining_exponent -= 13;
|
332 |
+
}
|
333 |
+
if (remaining_exponent > 0) {
|
334 |
+
MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
|
335 |
+
}
|
336 |
+
ShiftLeft(exponent);
|
337 |
+
}
|
338 |
+
|
339 |
+
|
340 |
+
void Bignum::Square() {
|
341 |
+
ASSERT(IsClamped());
|
342 |
+
int product_length = 2 * used_digits_;
|
343 |
+
EnsureCapacity(product_length);
|
344 |
+
|
345 |
+
// Comba multiplication: compute each column separately.
|
346 |
+
// Example: r = a2a1a0 * b2b1b0.
|
347 |
+
// r = 1 * a0b0 +
|
348 |
+
// 10 * (a1b0 + a0b1) +
|
349 |
+
// 100 * (a2b0 + a1b1 + a0b2) +
|
350 |
+
// 1000 * (a2b1 + a1b2) +
|
351 |
+
// 10000 * a2b2
|
352 |
+
//
|
353 |
+
// In the worst case we have to accumulate nb-digits products of digit*digit.
|
354 |
+
//
|
355 |
+
// Assert that the additional number of bits in a DoubleChunk are enough to
|
356 |
+
// sum up used_digits of Bigit*Bigit.
|
357 |
+
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_) {
|
358 |
+
UNIMPLEMENTED();
|
359 |
+
}
|
360 |
+
DoubleChunk accumulator = 0;
|
361 |
+
// First shift the digits so we don't overwrite them.
|
362 |
+
int copy_offset = used_digits_;
|
363 |
+
for (int i = 0; i < used_digits_; ++i) {
|
364 |
+
bigits_[copy_offset + i] = bigits_[i];
|
365 |
+
}
|
366 |
+
// We have two loops to avoid some 'if's in the loop.
|
367 |
+
for (int i = 0; i < used_digits_; ++i) {
|
368 |
+
// Process temporary digit i with power i.
|
369 |
+
// The sum of the two indices must be equal to i.
|
370 |
+
int bigit_index1 = i;
|
371 |
+
int bigit_index2 = 0;
|
372 |
+
// Sum all of the sub-products.
|
373 |
+
while (bigit_index1 >= 0) {
|
374 |
+
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
375 |
+
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
376 |
+
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
377 |
+
bigit_index1--;
|
378 |
+
bigit_index2++;
|
379 |
+
}
|
380 |
+
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
381 |
+
accumulator >>= kBigitSize;
|
382 |
+
}
|
383 |
+
for (int i = used_digits_; i < product_length; ++i) {
|
384 |
+
int bigit_index1 = used_digits_ - 1;
|
385 |
+
int bigit_index2 = i - bigit_index1;
|
386 |
+
// Invariant: sum of both indices is again equal to i.
|
387 |
+
// Inner loop runs 0 times on last iteration, emptying accumulator.
|
388 |
+
while (bigit_index2 < used_digits_) {
|
389 |
+
Chunk chunk1 = bigits_[copy_offset + bigit_index1];
|
390 |
+
Chunk chunk2 = bigits_[copy_offset + bigit_index2];
|
391 |
+
accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
|
392 |
+
bigit_index1--;
|
393 |
+
bigit_index2++;
|
394 |
+
}
|
395 |
+
// The overwritten bigits_[i] will never be read in further loop iterations,
|
396 |
+
// because bigit_index1 and bigit_index2 are always greater
|
397 |
+
// than i - used_digits_.
|
398 |
+
bigits_[i] = static_cast<Chunk>(accumulator) & kBigitMask;
|
399 |
+
accumulator >>= kBigitSize;
|
400 |
+
}
|
401 |
+
// Since the result was guaranteed to lie inside the number the
|
402 |
+
// accumulator must be 0 now.
|
403 |
+
ASSERT(accumulator == 0);
|
404 |
+
|
405 |
+
// Don't forget to update the used_digits and the exponent.
|
406 |
+
used_digits_ = product_length;
|
407 |
+
exponent_ *= 2;
|
408 |
+
Clamp();
|
409 |
+
}
|
410 |
+
|
411 |
+
|
412 |
+
void Bignum::AssignPowerUInt16(uint16_t base, int power_exponent) {
|
413 |
+
ASSERT(base != 0);
|
414 |
+
ASSERT(power_exponent >= 0);
|
415 |
+
if (power_exponent == 0) {
|
416 |
+
AssignUInt16(1);
|
417 |
+
return;
|
418 |
+
}
|
419 |
+
Zero();
|
420 |
+
int shifts = 0;
|
421 |
+
// We expect base to be in range 2-32, and most often to be 10.
|
422 |
+
// It does not make much sense to implement different algorithms for counting
|
423 |
+
// the bits.
|
424 |
+
while ((base & 1) == 0) {
|
425 |
+
base >>= 1;
|
426 |
+
shifts++;
|
427 |
+
}
|
428 |
+
int bit_size = 0;
|
429 |
+
int tmp_base = base;
|
430 |
+
while (tmp_base != 0) {
|
431 |
+
tmp_base >>= 1;
|
432 |
+
bit_size++;
|
433 |
+
}
|
434 |
+
int final_size = bit_size * power_exponent;
|
435 |
+
// 1 extra bigit for the shifting, and one for rounded final_size.
|
436 |
+
EnsureCapacity(final_size / kBigitSize + 2);
|
437 |
+
|
438 |
+
// Left to Right exponentiation.
|
439 |
+
int mask = 1;
|
440 |
+
while (power_exponent >= mask) mask <<= 1;
|
441 |
+
|
442 |
+
// The mask is now pointing to the bit above the most significant 1-bit of
|
443 |
+
// power_exponent.
|
444 |
+
// Get rid of first 1-bit;
|
445 |
+
mask >>= 2;
|
446 |
+
uint64_t this_value = base;
|
447 |
+
|
448 |
+
bool delayed_multipliciation = false;
|
449 |
+
const uint64_t max_32bits = 0xFFFFFFFF;
|
450 |
+
while (mask != 0 && this_value <= max_32bits) {
|
451 |
+
this_value = this_value * this_value;
|
452 |
+
// Verify that there is enough space in this_value to perform the
|
453 |
+
// multiplication. The first bit_size bits must be 0.
|
454 |
+
if ((power_exponent & mask) != 0) {
|
455 |
+
uint64_t base_bits_mask =
|
456 |
+
~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
|
457 |
+
bool high_bits_zero = (this_value & base_bits_mask) == 0;
|
458 |
+
if (high_bits_zero) {
|
459 |
+
this_value *= base;
|
460 |
+
} else {
|
461 |
+
delayed_multipliciation = true;
|
462 |
+
}
|
463 |
+
}
|
464 |
+
mask >>= 1;
|
465 |
+
}
|
466 |
+
AssignUInt64(this_value);
|
467 |
+
if (delayed_multipliciation) {
|
468 |
+
MultiplyByUInt32(base);
|
469 |
+
}
|
470 |
+
|
471 |
+
// Now do the same thing as a bignum.
|
472 |
+
while (mask != 0) {
|
473 |
+
Square();
|
474 |
+
if ((power_exponent & mask) != 0) {
|
475 |
+
MultiplyByUInt32(base);
|
476 |
+
}
|
477 |
+
mask >>= 1;
|
478 |
+
}
|
479 |
+
|
480 |
+
// And finally add the saved shifts.
|
481 |
+
ShiftLeft(shifts * power_exponent);
|
482 |
+
}
|
483 |
+
|
484 |
+
|
485 |
+
// Precondition: this/other < 16bit.
|
486 |
+
uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
|
487 |
+
ASSERT(IsClamped());
|
488 |
+
ASSERT(other.IsClamped());
|
489 |
+
ASSERT(other.used_digits_ > 0);
|
490 |
+
|
491 |
+
// Easy case: if we have less digits than the divisor than the result is 0.
|
492 |
+
// Note: this handles the case where this == 0, too.
|
493 |
+
if (BigitLength() < other.BigitLength()) {
|
494 |
+
return 0;
|
495 |
+
}
|
496 |
+
|
497 |
+
Align(other);
|
498 |
+
|
499 |
+
uint16_t result = 0;
|
500 |
+
|
501 |
+
// Start by removing multiples of 'other' until both numbers have the same
|
502 |
+
// number of digits.
|
503 |
+
while (BigitLength() > other.BigitLength()) {
|
504 |
+
// This naive approach is extremely inefficient if `this` divided by other
|
505 |
+
// is big. This function is implemented for doubleToString where
|
506 |
+
// the result should be small (less than 10).
|
507 |
+
ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
|
508 |
+
ASSERT(bigits_[used_digits_ - 1] < 0x10000);
|
509 |
+
// Remove the multiples of the first digit.
|
510 |
+
// Example this = 23 and other equals 9. -> Remove 2 multiples.
|
511 |
+
result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
|
512 |
+
SubtractTimes(other, bigits_[used_digits_ - 1]);
|
513 |
+
}
|
514 |
+
|
515 |
+
ASSERT(BigitLength() == other.BigitLength());
|
516 |
+
|
517 |
+
// Both bignums are at the same length now.
|
518 |
+
// Since other has more than 0 digits we know that the access to
|
519 |
+
// bigits_[used_digits_ - 1] is safe.
|
520 |
+
Chunk this_bigit = bigits_[used_digits_ - 1];
|
521 |
+
Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
|
522 |
+
|
523 |
+
if (other.used_digits_ == 1) {
|
524 |
+
// Shortcut for easy (and common) case.
|
525 |
+
int quotient = this_bigit / other_bigit;
|
526 |
+
bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
|
527 |
+
ASSERT(quotient < 0x10000);
|
528 |
+
result += static_cast<uint16_t>(quotient);
|
529 |
+
Clamp();
|
530 |
+
return result;
|
531 |
+
}
|
532 |
+
|
533 |
+
int division_estimate = this_bigit / (other_bigit + 1);
|
534 |
+
ASSERT(division_estimate < 0x10000);
|
535 |
+
result += static_cast<uint16_t>(division_estimate);
|
536 |
+
SubtractTimes(other, division_estimate);
|
537 |
+
|
538 |
+
if (other_bigit * (division_estimate + 1) > this_bigit) {
|
539 |
+
// No need to even try to subtract. Even if other's remaining digits were 0
|
540 |
+
// another subtraction would be too much.
|
541 |
+
return result;
|
542 |
+
}
|
543 |
+
|
544 |
+
while (LessEqual(other, *this)) {
|
545 |
+
SubtractBignum(other);
|
546 |
+
result++;
|
547 |
+
}
|
548 |
+
return result;
|
549 |
+
}
|
550 |
+
|
551 |
+
|
552 |
+
template<typename S>
|
553 |
+
static int SizeInHexChars(S number) {
|
554 |
+
ASSERT(number > 0);
|
555 |
+
int result = 0;
|
556 |
+
while (number != 0) {
|
557 |
+
number >>= 4;
|
558 |
+
result++;
|
559 |
+
}
|
560 |
+
return result;
|
561 |
+
}
|
562 |
+
|
563 |
+
|
564 |
+
static char HexCharOfValue(int value) {
|
565 |
+
ASSERT(0 <= value && value <= 16);
|
566 |
+
if (value < 10) return static_cast<char>(value + '0');
|
567 |
+
return static_cast<char>(value - 10 + 'A');
|
568 |
+
}
|
569 |
+
|
570 |
+
|
571 |
+
bool Bignum::ToHexString(char* buffer, int buffer_size) const {
|
572 |
+
ASSERT(IsClamped());
|
573 |
+
// Each bigit must be printable as separate hex-character.
|
574 |
+
ASSERT(kBigitSize % 4 == 0);
|
575 |
+
const int kHexCharsPerBigit = kBigitSize / 4;
|
576 |
+
|
577 |
+
if (used_digits_ == 0) {
|
578 |
+
if (buffer_size < 2) return false;
|
579 |
+
buffer[0] = '0';
|
580 |
+
buffer[1] = '\0';
|
581 |
+
return true;
|
582 |
+
}
|
583 |
+
// We add 1 for the terminating '\0' character.
|
584 |
+
int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
|
585 |
+
SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
|
586 |
+
if (needed_chars > buffer_size) return false;
|
587 |
+
int string_index = needed_chars - 1;
|
588 |
+
buffer[string_index--] = '\0';
|
589 |
+
for (int i = 0; i < exponent_; ++i) {
|
590 |
+
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
591 |
+
buffer[string_index--] = '0';
|
592 |
+
}
|
593 |
+
}
|
594 |
+
for (int i = 0; i < used_digits_ - 1; ++i) {
|
595 |
+
Chunk current_bigit = bigits_[i];
|
596 |
+
for (int j = 0; j < kHexCharsPerBigit; ++j) {
|
597 |
+
buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
|
598 |
+
current_bigit >>= 4;
|
599 |
+
}
|
600 |
+
}
|
601 |
+
// And finally the last bigit.
|
602 |
+
Chunk most_significant_bigit = bigits_[used_digits_ - 1];
|
603 |
+
while (most_significant_bigit != 0) {
|
604 |
+
buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
|
605 |
+
most_significant_bigit >>= 4;
|
606 |
+
}
|
607 |
+
return true;
|
608 |
+
}
|
609 |
+
|
610 |
+
|
611 |
+
Bignum::Chunk Bignum::BigitAt(int index) const {
|
612 |
+
if (index >= BigitLength()) return 0;
|
613 |
+
if (index < exponent_) return 0;
|
614 |
+
return bigits_[index - exponent_];
|
615 |
+
}
|
616 |
+
|
617 |
+
|
618 |
+
int Bignum::Compare(const Bignum& a, const Bignum& b) {
|
619 |
+
ASSERT(a.IsClamped());
|
620 |
+
ASSERT(b.IsClamped());
|
621 |
+
int bigit_length_a = a.BigitLength();
|
622 |
+
int bigit_length_b = b.BigitLength();
|
623 |
+
if (bigit_length_a < bigit_length_b) return -1;
|
624 |
+
if (bigit_length_a > bigit_length_b) return +1;
|
625 |
+
for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
|
626 |
+
Chunk bigit_a = a.BigitAt(i);
|
627 |
+
Chunk bigit_b = b.BigitAt(i);
|
628 |
+
if (bigit_a < bigit_b) return -1;
|
629 |
+
if (bigit_a > bigit_b) return +1;
|
630 |
+
// Otherwise they are equal up to this digit. Try the next digit.
|
631 |
+
}
|
632 |
+
return 0;
|
633 |
+
}
|
634 |
+
|
635 |
+
|
636 |
+
int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
|
637 |
+
ASSERT(a.IsClamped());
|
638 |
+
ASSERT(b.IsClamped());
|
639 |
+
ASSERT(c.IsClamped());
|
640 |
+
if (a.BigitLength() < b.BigitLength()) {
|
641 |
+
return PlusCompare(b, a, c);
|
642 |
+
}
|
643 |
+
if (a.BigitLength() + 1 < c.BigitLength()) return -1;
|
644 |
+
if (a.BigitLength() > c.BigitLength()) return +1;
|
645 |
+
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
|
646 |
+
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
|
647 |
+
// of 'a'.
|
648 |
+
if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
|
649 |
+
return -1;
|
650 |
+
}
|
651 |
+
|
652 |
+
Chunk borrow = 0;
|
653 |
+
// Starting at min_exponent all digits are == 0. So no need to compare them.
|
654 |
+
int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
|
655 |
+
for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
|
656 |
+
Chunk chunk_a = a.BigitAt(i);
|
657 |
+
Chunk chunk_b = b.BigitAt(i);
|
658 |
+
Chunk chunk_c = c.BigitAt(i);
|
659 |
+
Chunk sum = chunk_a + chunk_b;
|
660 |
+
if (sum > chunk_c + borrow) {
|
661 |
+
return +1;
|
662 |
+
} else {
|
663 |
+
borrow = chunk_c + borrow - sum;
|
664 |
+
if (borrow > 1) return -1;
|
665 |
+
borrow <<= kBigitSize;
|
666 |
+
}
|
667 |
+
}
|
668 |
+
if (borrow == 0) return 0;
|
669 |
+
return -1;
|
670 |
+
}
|
671 |
+
|
672 |
+
|
673 |
+
void Bignum::Clamp() {
|
674 |
+
while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
|
675 |
+
used_digits_--;
|
676 |
+
}
|
677 |
+
if (used_digits_ == 0) {
|
678 |
+
// Zero.
|
679 |
+
exponent_ = 0;
|
680 |
+
}
|
681 |
+
}
|
682 |
+
|
683 |
+
|
684 |
+
bool Bignum::IsClamped() const {
|
685 |
+
return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
|
686 |
+
}
|
687 |
+
|
688 |
+
|
689 |
+
void Bignum::Zero() {
|
690 |
+
for (int i = 0; i < used_digits_; ++i) {
|
691 |
+
bigits_[i] = 0;
|
692 |
+
}
|
693 |
+
used_digits_ = 0;
|
694 |
+
exponent_ = 0;
|
695 |
+
}
|
696 |
+
|
697 |
+
|
698 |
+
void Bignum::Align(const Bignum& other) {
|
699 |
+
if (exponent_ > other.exponent_) {
|
700 |
+
// If "X" represents a "hidden" digit (by the exponent) then we are in the
|
701 |
+
// following case (a == this, b == other):
|
702 |
+
// a: aaaaaaXXXX or a: aaaaaXXX
|
703 |
+
// b: bbbbbbX b: bbbbbbbbXX
|
704 |
+
// We replace some of the hidden digits (X) of a with 0 digits.
|
705 |
+
// a: aaaaaa000X or a: aaaaa0XX
|
706 |
+
int zero_digits = exponent_ - other.exponent_;
|
707 |
+
EnsureCapacity(used_digits_ + zero_digits);
|
708 |
+
for (int i = used_digits_ - 1; i >= 0; --i) {
|
709 |
+
bigits_[i + zero_digits] = bigits_[i];
|
710 |
+
}
|
711 |
+
for (int i = 0; i < zero_digits; ++i) {
|
712 |
+
bigits_[i] = 0;
|
713 |
+
}
|
714 |
+
used_digits_ += zero_digits;
|
715 |
+
exponent_ -= zero_digits;
|
716 |
+
ASSERT(used_digits_ >= 0);
|
717 |
+
ASSERT(exponent_ >= 0);
|
718 |
+
}
|
719 |
+
}
|
720 |
+
|
721 |
+
|
722 |
+
void Bignum::BigitsShiftLeft(int shift_amount) {
|
723 |
+
ASSERT(shift_amount < kBigitSize);
|
724 |
+
ASSERT(shift_amount >= 0);
|
725 |
+
Chunk carry = 0;
|
726 |
+
for (int i = 0; i < used_digits_; ++i) {
|
727 |
+
Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
|
728 |
+
bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
|
729 |
+
carry = new_carry;
|
730 |
+
}
|
731 |
+
if (carry != 0) {
|
732 |
+
bigits_[used_digits_] = carry;
|
733 |
+
used_digits_++;
|
734 |
+
}
|
735 |
+
}
|
736 |
+
|
737 |
+
|
738 |
+
void Bignum::SubtractTimes(const Bignum& other, int factor) {
|
739 |
+
ASSERT(exponent_ <= other.exponent_);
|
740 |
+
if (factor < 3) {
|
741 |
+
for (int i = 0; i < factor; ++i) {
|
742 |
+
SubtractBignum(other);
|
743 |
+
}
|
744 |
+
return;
|
745 |
+
}
|
746 |
+
Chunk borrow = 0;
|
747 |
+
int exponent_diff = other.exponent_ - exponent_;
|
748 |
+
for (int i = 0; i < other.used_digits_; ++i) {
|
749 |
+
DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
|
750 |
+
DoubleChunk remove = borrow + product;
|
751 |
+
Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
|
752 |
+
bigits_[i + exponent_diff] = difference & kBigitMask;
|
753 |
+
borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
|
754 |
+
(remove >> kBigitSize));
|
755 |
+
}
|
756 |
+
for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
|
757 |
+
if (borrow == 0) return;
|
758 |
+
Chunk difference = bigits_[i] - borrow;
|
759 |
+
bigits_[i] = difference & kBigitMask;
|
760 |
+
borrow = difference >> (kChunkSize - 1);
|
761 |
+
}
|
762 |
+
Clamp();
|
763 |
+
}
|
764 |
+
|
765 |
+
|
766 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/bignum.h
ADDED
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_BIGNUM_H_
|
29 |
+
#define DOUBLE_CONVERSION_BIGNUM_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
class Bignum {
|
36 |
+
public:
|
37 |
+
// 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
|
38 |
+
// This bignum can encode much bigger numbers, since it contains an
|
39 |
+
// exponent.
|
40 |
+
static const int kMaxSignificantBits = 3584;
|
41 |
+
|
42 |
+
Bignum();
|
43 |
+
void AssignUInt16(uint16_t value);
|
44 |
+
void AssignUInt64(uint64_t value);
|
45 |
+
void AssignBignum(const Bignum& other);
|
46 |
+
|
47 |
+
void AssignDecimalString(Vector<const char> value);
|
48 |
+
void AssignHexString(Vector<const char> value);
|
49 |
+
|
50 |
+
void AssignPowerUInt16(uint16_t base, int exponent);
|
51 |
+
|
52 |
+
void AddUInt64(uint64_t operand);
|
53 |
+
void AddBignum(const Bignum& other);
|
54 |
+
// Precondition: this >= other.
|
55 |
+
void SubtractBignum(const Bignum& other);
|
56 |
+
|
57 |
+
void Square();
|
58 |
+
void ShiftLeft(int shift_amount);
|
59 |
+
void MultiplyByUInt32(uint32_t factor);
|
60 |
+
void MultiplyByUInt64(uint64_t factor);
|
61 |
+
void MultiplyByPowerOfTen(int exponent);
|
62 |
+
void Times10() { return MultiplyByUInt32(10); }
|
63 |
+
// Pseudocode:
|
64 |
+
// int result = this / other;
|
65 |
+
// this = this % other;
|
66 |
+
// In the worst case this function is in O(this/other).
|
67 |
+
uint16_t DivideModuloIntBignum(const Bignum& other);
|
68 |
+
|
69 |
+
bool ToHexString(char* buffer, int buffer_size) const;
|
70 |
+
|
71 |
+
// Returns
|
72 |
+
// -1 if a < b,
|
73 |
+
// 0 if a == b, and
|
74 |
+
// +1 if a > b.
|
75 |
+
static int Compare(const Bignum& a, const Bignum& b);
|
76 |
+
static bool Equal(const Bignum& a, const Bignum& b) {
|
77 |
+
return Compare(a, b) == 0;
|
78 |
+
}
|
79 |
+
static bool LessEqual(const Bignum& a, const Bignum& b) {
|
80 |
+
return Compare(a, b) <= 0;
|
81 |
+
}
|
82 |
+
static bool Less(const Bignum& a, const Bignum& b) {
|
83 |
+
return Compare(a, b) < 0;
|
84 |
+
}
|
85 |
+
// Returns Compare(a + b, c);
|
86 |
+
static int PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c);
|
87 |
+
// Returns a + b == c
|
88 |
+
static bool PlusEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
|
89 |
+
return PlusCompare(a, b, c) == 0;
|
90 |
+
}
|
91 |
+
// Returns a + b <= c
|
92 |
+
static bool PlusLessEqual(const Bignum& a, const Bignum& b, const Bignum& c) {
|
93 |
+
return PlusCompare(a, b, c) <= 0;
|
94 |
+
}
|
95 |
+
// Returns a + b < c
|
96 |
+
static bool PlusLess(const Bignum& a, const Bignum& b, const Bignum& c) {
|
97 |
+
return PlusCompare(a, b, c) < 0;
|
98 |
+
}
|
99 |
+
private:
|
100 |
+
typedef uint32_t Chunk;
|
101 |
+
typedef uint64_t DoubleChunk;
|
102 |
+
|
103 |
+
static const int kChunkSize = sizeof(Chunk) * 8;
|
104 |
+
static const int kDoubleChunkSize = sizeof(DoubleChunk) * 8;
|
105 |
+
// With bigit size of 28 we loose some bits, but a double still fits easily
|
106 |
+
// into two chunks, and more importantly we can use the Comba multiplication.
|
107 |
+
static const int kBigitSize = 28;
|
108 |
+
static const Chunk kBigitMask = (1 << kBigitSize) - 1;
|
109 |
+
// Every instance allocates kBigitLength chunks on the stack. Bignums cannot
|
110 |
+
// grow. There are no checks if the stack-allocated space is sufficient.
|
111 |
+
static const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
|
112 |
+
|
113 |
+
void EnsureCapacity(int size) {
|
114 |
+
if (size > kBigitCapacity) {
|
115 |
+
UNREACHABLE();
|
116 |
+
}
|
117 |
+
}
|
118 |
+
void Align(const Bignum& other);
|
119 |
+
void Clamp();
|
120 |
+
bool IsClamped() const;
|
121 |
+
void Zero();
|
122 |
+
// Requires this to have enough capacity (no tests done).
|
123 |
+
// Updates used_digits_ if necessary.
|
124 |
+
// shift_amount must be < kBigitSize.
|
125 |
+
void BigitsShiftLeft(int shift_amount);
|
126 |
+
// BigitLength includes the "hidden" digits encoded in the exponent.
|
127 |
+
int BigitLength() const { return used_digits_ + exponent_; }
|
128 |
+
Chunk BigitAt(int index) const;
|
129 |
+
void SubtractTimes(const Bignum& other, int factor);
|
130 |
+
|
131 |
+
Chunk bigits_buffer_[kBigitCapacity];
|
132 |
+
// A vector backed by bigits_buffer_. This way accesses to the array are
|
133 |
+
// checked for out-of-bounds errors.
|
134 |
+
Vector<Chunk> bigits_;
|
135 |
+
int used_digits_;
|
136 |
+
// The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
|
137 |
+
int exponent_;
|
138 |
+
|
139 |
+
DISALLOW_COPY_AND_ASSIGN(Bignum);
|
140 |
+
};
|
141 |
+
|
142 |
+
} // namespace double_conversion
|
143 |
+
|
144 |
+
#endif // DOUBLE_CONVERSION_BIGNUM_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/cached-powers.cc
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2006-2008 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include <stdarg.h>
|
29 |
+
#include <limits.h>
|
30 |
+
#include <math.h>
|
31 |
+
|
32 |
+
#include "utils.h"
|
33 |
+
|
34 |
+
#include "cached-powers.h"
|
35 |
+
|
36 |
+
namespace double_conversion {
|
37 |
+
|
38 |
+
struct CachedPower {
|
39 |
+
uint64_t significand;
|
40 |
+
int16_t binary_exponent;
|
41 |
+
int16_t decimal_exponent;
|
42 |
+
};
|
43 |
+
|
44 |
+
static const CachedPower kCachedPowers[] = {
|
45 |
+
{UINT64_2PART_C(0xfa8fd5a0, 081c0288), -1220, -348},
|
46 |
+
{UINT64_2PART_C(0xbaaee17f, a23ebf76), -1193, -340},
|
47 |
+
{UINT64_2PART_C(0x8b16fb20, 3055ac76), -1166, -332},
|
48 |
+
{UINT64_2PART_C(0xcf42894a, 5dce35ea), -1140, -324},
|
49 |
+
{UINT64_2PART_C(0x9a6bb0aa, 55653b2d), -1113, -316},
|
50 |
+
{UINT64_2PART_C(0xe61acf03, 3d1a45df), -1087, -308},
|
51 |
+
{UINT64_2PART_C(0xab70fe17, c79ac6ca), -1060, -300},
|
52 |
+
{UINT64_2PART_C(0xff77b1fc, bebcdc4f), -1034, -292},
|
53 |
+
{UINT64_2PART_C(0xbe5691ef, 416bd60c), -1007, -284},
|
54 |
+
{UINT64_2PART_C(0x8dd01fad, 907ffc3c), -980, -276},
|
55 |
+
{UINT64_2PART_C(0xd3515c28, 31559a83), -954, -268},
|
56 |
+
{UINT64_2PART_C(0x9d71ac8f, ada6c9b5), -927, -260},
|
57 |
+
{UINT64_2PART_C(0xea9c2277, 23ee8bcb), -901, -252},
|
58 |
+
{UINT64_2PART_C(0xaecc4991, 4078536d), -874, -244},
|
59 |
+
{UINT64_2PART_C(0x823c1279, 5db6ce57), -847, -236},
|
60 |
+
{UINT64_2PART_C(0xc2109436, 4dfb5637), -821, -228},
|
61 |
+
{UINT64_2PART_C(0x9096ea6f, 3848984f), -794, -220},
|
62 |
+
{UINT64_2PART_C(0xd77485cb, 25823ac7), -768, -212},
|
63 |
+
{UINT64_2PART_C(0xa086cfcd, 97bf97f4), -741, -204},
|
64 |
+
{UINT64_2PART_C(0xef340a98, 172aace5), -715, -196},
|
65 |
+
{UINT64_2PART_C(0xb23867fb, 2a35b28e), -688, -188},
|
66 |
+
{UINT64_2PART_C(0x84c8d4df, d2c63f3b), -661, -180},
|
67 |
+
{UINT64_2PART_C(0xc5dd4427, 1ad3cdba), -635, -172},
|
68 |
+
{UINT64_2PART_C(0x936b9fce, bb25c996), -608, -164},
|
69 |
+
{UINT64_2PART_C(0xdbac6c24, 7d62a584), -582, -156},
|
70 |
+
{UINT64_2PART_C(0xa3ab6658, 0d5fdaf6), -555, -148},
|
71 |
+
{UINT64_2PART_C(0xf3e2f893, dec3f126), -529, -140},
|
72 |
+
{UINT64_2PART_C(0xb5b5ada8, aaff80b8), -502, -132},
|
73 |
+
{UINT64_2PART_C(0x87625f05, 6c7c4a8b), -475, -124},
|
74 |
+
{UINT64_2PART_C(0xc9bcff60, 34c13053), -449, -116},
|
75 |
+
{UINT64_2PART_C(0x964e858c, 91ba2655), -422, -108},
|
76 |
+
{UINT64_2PART_C(0xdff97724, 70297ebd), -396, -100},
|
77 |
+
{UINT64_2PART_C(0xa6dfbd9f, b8e5b88f), -369, -92},
|
78 |
+
{UINT64_2PART_C(0xf8a95fcf, 88747d94), -343, -84},
|
79 |
+
{UINT64_2PART_C(0xb9447093, 8fa89bcf), -316, -76},
|
80 |
+
{UINT64_2PART_C(0x8a08f0f8, bf0f156b), -289, -68},
|
81 |
+
{UINT64_2PART_C(0xcdb02555, 653131b6), -263, -60},
|
82 |
+
{UINT64_2PART_C(0x993fe2c6, d07b7fac), -236, -52},
|
83 |
+
{UINT64_2PART_C(0xe45c10c4, 2a2b3b06), -210, -44},
|
84 |
+
{UINT64_2PART_C(0xaa242499, 697392d3), -183, -36},
|
85 |
+
{UINT64_2PART_C(0xfd87b5f2, 8300ca0e), -157, -28},
|
86 |
+
{UINT64_2PART_C(0xbce50864, 92111aeb), -130, -20},
|
87 |
+
{UINT64_2PART_C(0x8cbccc09, 6f5088cc), -103, -12},
|
88 |
+
{UINT64_2PART_C(0xd1b71758, e219652c), -77, -4},
|
89 |
+
{UINT64_2PART_C(0x9c400000, 00000000), -50, 4},
|
90 |
+
{UINT64_2PART_C(0xe8d4a510, 00000000), -24, 12},
|
91 |
+
{UINT64_2PART_C(0xad78ebc5, ac620000), 3, 20},
|
92 |
+
{UINT64_2PART_C(0x813f3978, f8940984), 30, 28},
|
93 |
+
{UINT64_2PART_C(0xc097ce7b, c90715b3), 56, 36},
|
94 |
+
{UINT64_2PART_C(0x8f7e32ce, 7bea5c70), 83, 44},
|
95 |
+
{UINT64_2PART_C(0xd5d238a4, abe98068), 109, 52},
|
96 |
+
{UINT64_2PART_C(0x9f4f2726, 179a2245), 136, 60},
|
97 |
+
{UINT64_2PART_C(0xed63a231, d4c4fb27), 162, 68},
|
98 |
+
{UINT64_2PART_C(0xb0de6538, 8cc8ada8), 189, 76},
|
99 |
+
{UINT64_2PART_C(0x83c7088e, 1aab65db), 216, 84},
|
100 |
+
{UINT64_2PART_C(0xc45d1df9, 42711d9a), 242, 92},
|
101 |
+
{UINT64_2PART_C(0x924d692c, a61be758), 269, 100},
|
102 |
+
{UINT64_2PART_C(0xda01ee64, 1a708dea), 295, 108},
|
103 |
+
{UINT64_2PART_C(0xa26da399, 9aef774a), 322, 116},
|
104 |
+
{UINT64_2PART_C(0xf209787b, b47d6b85), 348, 124},
|
105 |
+
{UINT64_2PART_C(0xb454e4a1, 79dd1877), 375, 132},
|
106 |
+
{UINT64_2PART_C(0x865b8692, 5b9bc5c2), 402, 140},
|
107 |
+
{UINT64_2PART_C(0xc83553c5, c8965d3d), 428, 148},
|
108 |
+
{UINT64_2PART_C(0x952ab45c, fa97a0b3), 455, 156},
|
109 |
+
{UINT64_2PART_C(0xde469fbd, 99a05fe3), 481, 164},
|
110 |
+
{UINT64_2PART_C(0xa59bc234, db398c25), 508, 172},
|
111 |
+
{UINT64_2PART_C(0xf6c69a72, a3989f5c), 534, 180},
|
112 |
+
{UINT64_2PART_C(0xb7dcbf53, 54e9bece), 561, 188},
|
113 |
+
{UINT64_2PART_C(0x88fcf317, f22241e2), 588, 196},
|
114 |
+
{UINT64_2PART_C(0xcc20ce9b, d35c78a5), 614, 204},
|
115 |
+
{UINT64_2PART_C(0x98165af3, 7b2153df), 641, 212},
|
116 |
+
{UINT64_2PART_C(0xe2a0b5dc, 971f303a), 667, 220},
|
117 |
+
{UINT64_2PART_C(0xa8d9d153, 5ce3b396), 694, 228},
|
118 |
+
{UINT64_2PART_C(0xfb9b7cd9, a4a7443c), 720, 236},
|
119 |
+
{UINT64_2PART_C(0xbb764c4c, a7a44410), 747, 244},
|
120 |
+
{UINT64_2PART_C(0x8bab8eef, b6409c1a), 774, 252},
|
121 |
+
{UINT64_2PART_C(0xd01fef10, a657842c), 800, 260},
|
122 |
+
{UINT64_2PART_C(0x9b10a4e5, e9913129), 827, 268},
|
123 |
+
{UINT64_2PART_C(0xe7109bfb, a19c0c9d), 853, 276},
|
124 |
+
{UINT64_2PART_C(0xac2820d9, 623bf429), 880, 284},
|
125 |
+
{UINT64_2PART_C(0x80444b5e, 7aa7cf85), 907, 292},
|
126 |
+
{UINT64_2PART_C(0xbf21e440, 03acdd2d), 933, 300},
|
127 |
+
{UINT64_2PART_C(0x8e679c2f, 5e44ff8f), 960, 308},
|
128 |
+
{UINT64_2PART_C(0xd433179d, 9c8cb841), 986, 316},
|
129 |
+
{UINT64_2PART_C(0x9e19db92, b4e31ba9), 1013, 324},
|
130 |
+
{UINT64_2PART_C(0xeb96bf6e, badf77d9), 1039, 332},
|
131 |
+
{UINT64_2PART_C(0xaf87023b, 9bf0ee6b), 1066, 340},
|
132 |
+
};
|
133 |
+
|
134 |
+
static const int kCachedPowersOffset = 348; // -1 * the first decimal_exponent.
|
135 |
+
static const double kD_1_LOG2_10 = 0.30102999566398114; // 1 / lg(10)
|
136 |
+
// Difference between the decimal exponents in the table above.
|
137 |
+
const int PowersOfTenCache::kDecimalExponentDistance = 8;
|
138 |
+
const int PowersOfTenCache::kMinDecimalExponent = -348;
|
139 |
+
const int PowersOfTenCache::kMaxDecimalExponent = 340;
|
140 |
+
|
141 |
+
void PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
142 |
+
int min_exponent,
|
143 |
+
int max_exponent,
|
144 |
+
DiyFp* power,
|
145 |
+
int* decimal_exponent) {
|
146 |
+
int kQ = DiyFp::kSignificandSize;
|
147 |
+
double k = ceil((min_exponent + kQ - 1) * kD_1_LOG2_10);
|
148 |
+
int foo = kCachedPowersOffset;
|
149 |
+
int index =
|
150 |
+
(foo + static_cast<int>(k) - 1) / kDecimalExponentDistance + 1;
|
151 |
+
ASSERT(0 <= index && index < static_cast<int>(ARRAY_SIZE(kCachedPowers)));
|
152 |
+
CachedPower cached_power = kCachedPowers[index];
|
153 |
+
ASSERT(min_exponent <= cached_power.binary_exponent);
|
154 |
+
(void) max_exponent; // Mark variable as used.
|
155 |
+
ASSERT(cached_power.binary_exponent <= max_exponent);
|
156 |
+
*decimal_exponent = cached_power.decimal_exponent;
|
157 |
+
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
158 |
+
}
|
159 |
+
|
160 |
+
|
161 |
+
void PowersOfTenCache::GetCachedPowerForDecimalExponent(int requested_exponent,
|
162 |
+
DiyFp* power,
|
163 |
+
int* found_exponent) {
|
164 |
+
ASSERT(kMinDecimalExponent <= requested_exponent);
|
165 |
+
ASSERT(requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance);
|
166 |
+
int index =
|
167 |
+
(requested_exponent + kCachedPowersOffset) / kDecimalExponentDistance;
|
168 |
+
CachedPower cached_power = kCachedPowers[index];
|
169 |
+
*power = DiyFp(cached_power.significand, cached_power.binary_exponent);
|
170 |
+
*found_exponent = cached_power.decimal_exponent;
|
171 |
+
ASSERT(*found_exponent <= requested_exponent);
|
172 |
+
ASSERT(requested_exponent < *found_exponent + kDecimalExponentDistance);
|
173 |
+
}
|
174 |
+
|
175 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/cached-powers.h
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_CACHED_POWERS_H_
|
29 |
+
#define DOUBLE_CONVERSION_CACHED_POWERS_H_
|
30 |
+
|
31 |
+
#include "diy-fp.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
class PowersOfTenCache {
|
36 |
+
public:
|
37 |
+
|
38 |
+
// Not all powers of ten are cached. The decimal exponent of two neighboring
|
39 |
+
// cached numbers will differ by kDecimalExponentDistance.
|
40 |
+
static const int kDecimalExponentDistance;
|
41 |
+
|
42 |
+
static const int kMinDecimalExponent;
|
43 |
+
static const int kMaxDecimalExponent;
|
44 |
+
|
45 |
+
// Returns a cached power-of-ten with a binary exponent in the range
|
46 |
+
// [min_exponent; max_exponent] (boundaries included).
|
47 |
+
static void GetCachedPowerForBinaryExponentRange(int min_exponent,
|
48 |
+
int max_exponent,
|
49 |
+
DiyFp* power,
|
50 |
+
int* decimal_exponent);
|
51 |
+
|
52 |
+
// Returns a cached power of ten x ~= 10^k such that
|
53 |
+
// k <= decimal_exponent < k + kCachedPowersDecimalDistance.
|
54 |
+
// The given decimal_exponent must satisfy
|
55 |
+
// kMinDecimalExponent <= requested_exponent, and
|
56 |
+
// requested_exponent < kMaxDecimalExponent + kDecimalExponentDistance.
|
57 |
+
static void GetCachedPowerForDecimalExponent(int requested_exponent,
|
58 |
+
DiyFp* power,
|
59 |
+
int* found_exponent);
|
60 |
+
};
|
61 |
+
|
62 |
+
} // namespace double_conversion
|
63 |
+
|
64 |
+
#endif // DOUBLE_CONVERSION_CACHED_POWERS_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/diy-fp.cc
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
|
29 |
+
#include "diy-fp.h"
|
30 |
+
#include "utils.h"
|
31 |
+
|
32 |
+
namespace double_conversion {
|
33 |
+
|
34 |
+
void DiyFp::Multiply(const DiyFp& other) {
|
35 |
+
// Simply "emulates" a 128 bit multiplication.
|
36 |
+
// However: the resulting number only contains 64 bits. The least
|
37 |
+
// significant 64 bits are only used for rounding the most significant 64
|
38 |
+
// bits.
|
39 |
+
const uint64_t kM32 = 0xFFFFFFFFU;
|
40 |
+
uint64_t a = f_ >> 32;
|
41 |
+
uint64_t b = f_ & kM32;
|
42 |
+
uint64_t c = other.f_ >> 32;
|
43 |
+
uint64_t d = other.f_ & kM32;
|
44 |
+
uint64_t ac = a * c;
|
45 |
+
uint64_t bc = b * c;
|
46 |
+
uint64_t ad = a * d;
|
47 |
+
uint64_t bd = b * d;
|
48 |
+
uint64_t tmp = (bd >> 32) + (ad & kM32) + (bc & kM32);
|
49 |
+
// By adding 1U << 31 to tmp we round the final result.
|
50 |
+
// Halfway cases will be round up.
|
51 |
+
tmp += 1U << 31;
|
52 |
+
uint64_t result_f = ac + (ad >> 32) + (bc >> 32) + (tmp >> 32);
|
53 |
+
e_ += other.e_ + 64;
|
54 |
+
f_ = result_f;
|
55 |
+
}
|
56 |
+
|
57 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/diy-fp.h
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_DIY_FP_H_
|
29 |
+
#define DOUBLE_CONVERSION_DIY_FP_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
// This "Do It Yourself Floating Point" class implements a floating-point number
|
36 |
+
// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
|
37 |
+
// have the most significant bit of the significand set.
|
38 |
+
// Multiplication and Subtraction do not normalize their results.
|
39 |
+
// DiyFp are not designed to contain special doubles (NaN and Infinity).
|
40 |
+
class DiyFp {
|
41 |
+
public:
|
42 |
+
static const int kSignificandSize = 64;
|
43 |
+
|
44 |
+
DiyFp() : f_(0), e_(0) {}
|
45 |
+
DiyFp(uint64_t significand, int exponent) : f_(significand), e_(exponent) {}
|
46 |
+
|
47 |
+
// this = this - other.
|
48 |
+
// The exponents of both numbers must be the same and the significand of this
|
49 |
+
// must be bigger than the significand of other.
|
50 |
+
// The result will not be normalized.
|
51 |
+
void Subtract(const DiyFp& other) {
|
52 |
+
ASSERT(e_ == other.e_);
|
53 |
+
ASSERT(f_ >= other.f_);
|
54 |
+
f_ -= other.f_;
|
55 |
+
}
|
56 |
+
|
57 |
+
// Returns a - b.
|
58 |
+
// The exponents of both numbers must be the same and this must be bigger
|
59 |
+
// than other. The result will not be normalized.
|
60 |
+
static DiyFp Minus(const DiyFp& a, const DiyFp& b) {
|
61 |
+
DiyFp result = a;
|
62 |
+
result.Subtract(b);
|
63 |
+
return result;
|
64 |
+
}
|
65 |
+
|
66 |
+
|
67 |
+
// this = this * other.
|
68 |
+
void Multiply(const DiyFp& other);
|
69 |
+
|
70 |
+
// returns a * b;
|
71 |
+
static DiyFp Times(const DiyFp& a, const DiyFp& b) {
|
72 |
+
DiyFp result = a;
|
73 |
+
result.Multiply(b);
|
74 |
+
return result;
|
75 |
+
}
|
76 |
+
|
77 |
+
void Normalize() {
|
78 |
+
ASSERT(f_ != 0);
|
79 |
+
uint64_t significand = f_;
|
80 |
+
int exponent = e_;
|
81 |
+
|
82 |
+
// This method is mainly called for normalizing boundaries. In general
|
83 |
+
// boundaries need to be shifted by 10 bits. We thus optimize for this case.
|
84 |
+
const uint64_t k10MSBits = UINT64_2PART_C(0xFFC00000, 00000000);
|
85 |
+
while ((significand & k10MSBits) == 0) {
|
86 |
+
significand <<= 10;
|
87 |
+
exponent -= 10;
|
88 |
+
}
|
89 |
+
while ((significand & kUint64MSB) == 0) {
|
90 |
+
significand <<= 1;
|
91 |
+
exponent--;
|
92 |
+
}
|
93 |
+
f_ = significand;
|
94 |
+
e_ = exponent;
|
95 |
+
}
|
96 |
+
|
97 |
+
static DiyFp Normalize(const DiyFp& a) {
|
98 |
+
DiyFp result = a;
|
99 |
+
result.Normalize();
|
100 |
+
return result;
|
101 |
+
}
|
102 |
+
|
103 |
+
uint64_t f() const { return f_; }
|
104 |
+
int e() const { return e_; }
|
105 |
+
|
106 |
+
void set_f(uint64_t new_value) { f_ = new_value; }
|
107 |
+
void set_e(int new_value) { e_ = new_value; }
|
108 |
+
|
109 |
+
private:
|
110 |
+
static const uint64_t kUint64MSB = UINT64_2PART_C(0x80000000, 00000000);
|
111 |
+
|
112 |
+
uint64_t f_;
|
113 |
+
int e_;
|
114 |
+
};
|
115 |
+
|
116 |
+
} // namespace double_conversion
|
117 |
+
|
118 |
+
#endif // DOUBLE_CONVERSION_DIY_FP_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/double-conversion.cc
ADDED
@@ -0,0 +1,982 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include <limits.h>
|
29 |
+
#include <math.h>
|
30 |
+
|
31 |
+
#include "double-conversion.h"
|
32 |
+
|
33 |
+
#include "bignum-dtoa.h"
|
34 |
+
#include "fast-dtoa.h"
|
35 |
+
#include "fixed-dtoa.h"
|
36 |
+
#include "ieee.h"
|
37 |
+
#include "strtod.h"
|
38 |
+
#include "utils.h"
|
39 |
+
|
40 |
+
namespace double_conversion {
|
41 |
+
|
42 |
+
const DoubleToStringConverter& DoubleToStringConverter::EcmaScriptConverter() {
|
43 |
+
int flags = UNIQUE_ZERO | EMIT_POSITIVE_EXPONENT_SIGN;
|
44 |
+
static DoubleToStringConverter converter(flags,
|
45 |
+
"Infinity",
|
46 |
+
"NaN",
|
47 |
+
'e',
|
48 |
+
-6, 21,
|
49 |
+
6, 0);
|
50 |
+
return converter;
|
51 |
+
}
|
52 |
+
|
53 |
+
|
54 |
+
bool DoubleToStringConverter::HandleSpecialValues(
|
55 |
+
double value,
|
56 |
+
StringBuilder* result_builder) const {
|
57 |
+
Double double_inspect(value);
|
58 |
+
if (double_inspect.IsInfinite()) {
|
59 |
+
if (infinity_symbol_ == NULL) return false;
|
60 |
+
if (value < 0) {
|
61 |
+
result_builder->AddCharacter('-');
|
62 |
+
}
|
63 |
+
result_builder->AddString(infinity_symbol_);
|
64 |
+
return true;
|
65 |
+
}
|
66 |
+
if (double_inspect.IsNan()) {
|
67 |
+
if (nan_symbol_ == NULL) return false;
|
68 |
+
result_builder->AddString(nan_symbol_);
|
69 |
+
return true;
|
70 |
+
}
|
71 |
+
return false;
|
72 |
+
}
|
73 |
+
|
74 |
+
|
75 |
+
void DoubleToStringConverter::CreateExponentialRepresentation(
|
76 |
+
const char* decimal_digits,
|
77 |
+
int length,
|
78 |
+
int exponent,
|
79 |
+
StringBuilder* result_builder) const {
|
80 |
+
ASSERT(length != 0);
|
81 |
+
result_builder->AddCharacter(decimal_digits[0]);
|
82 |
+
if (length != 1) {
|
83 |
+
result_builder->AddCharacter('.');
|
84 |
+
result_builder->AddSubstring(&decimal_digits[1], length-1);
|
85 |
+
}
|
86 |
+
result_builder->AddCharacter(exponent_character_);
|
87 |
+
if (exponent < 0) {
|
88 |
+
result_builder->AddCharacter('-');
|
89 |
+
exponent = -exponent;
|
90 |
+
} else {
|
91 |
+
if ((flags_ & EMIT_POSITIVE_EXPONENT_SIGN) != 0) {
|
92 |
+
result_builder->AddCharacter('+');
|
93 |
+
}
|
94 |
+
}
|
95 |
+
if (exponent == 0) {
|
96 |
+
result_builder->AddCharacter('0');
|
97 |
+
return;
|
98 |
+
}
|
99 |
+
ASSERT(exponent < 1e4);
|
100 |
+
const int kMaxExponentLength = 5;
|
101 |
+
char buffer[kMaxExponentLength + 1];
|
102 |
+
buffer[kMaxExponentLength] = '\0';
|
103 |
+
int first_char_pos = kMaxExponentLength;
|
104 |
+
while (exponent > 0) {
|
105 |
+
buffer[--first_char_pos] = '0' + (exponent % 10);
|
106 |
+
exponent /= 10;
|
107 |
+
}
|
108 |
+
result_builder->AddSubstring(&buffer[first_char_pos],
|
109 |
+
kMaxExponentLength - first_char_pos);
|
110 |
+
}
|
111 |
+
|
112 |
+
|
113 |
+
void DoubleToStringConverter::CreateDecimalRepresentation(
|
114 |
+
const char* decimal_digits,
|
115 |
+
int length,
|
116 |
+
int decimal_point,
|
117 |
+
int digits_after_point,
|
118 |
+
StringBuilder* result_builder) const {
|
119 |
+
// Create a representation that is padded with zeros if needed.
|
120 |
+
if (decimal_point <= 0) {
|
121 |
+
// "0.00000decimal_rep" or "0.000decimal_rep00".
|
122 |
+
result_builder->AddCharacter('0');
|
123 |
+
if (digits_after_point > 0) {
|
124 |
+
result_builder->AddCharacter('.');
|
125 |
+
result_builder->AddPadding('0', -decimal_point);
|
126 |
+
ASSERT(length <= digits_after_point - (-decimal_point));
|
127 |
+
result_builder->AddSubstring(decimal_digits, length);
|
128 |
+
int remaining_digits = digits_after_point - (-decimal_point) - length;
|
129 |
+
result_builder->AddPadding('0', remaining_digits);
|
130 |
+
}
|
131 |
+
} else if (decimal_point >= length) {
|
132 |
+
// "decimal_rep0000.00000" or "decimal_rep.0000".
|
133 |
+
result_builder->AddSubstring(decimal_digits, length);
|
134 |
+
result_builder->AddPadding('0', decimal_point - length);
|
135 |
+
if (digits_after_point > 0) {
|
136 |
+
result_builder->AddCharacter('.');
|
137 |
+
result_builder->AddPadding('0', digits_after_point);
|
138 |
+
}
|
139 |
+
} else {
|
140 |
+
// "decima.l_rep000".
|
141 |
+
ASSERT(digits_after_point > 0);
|
142 |
+
result_builder->AddSubstring(decimal_digits, decimal_point);
|
143 |
+
result_builder->AddCharacter('.');
|
144 |
+
ASSERT(length - decimal_point <= digits_after_point);
|
145 |
+
result_builder->AddSubstring(&decimal_digits[decimal_point],
|
146 |
+
length - decimal_point);
|
147 |
+
int remaining_digits = digits_after_point - (length - decimal_point);
|
148 |
+
result_builder->AddPadding('0', remaining_digits);
|
149 |
+
}
|
150 |
+
if (digits_after_point == 0) {
|
151 |
+
if ((flags_ & EMIT_TRAILING_DECIMAL_POINT) != 0) {
|
152 |
+
result_builder->AddCharacter('.');
|
153 |
+
}
|
154 |
+
if ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) {
|
155 |
+
result_builder->AddCharacter('0');
|
156 |
+
}
|
157 |
+
}
|
158 |
+
}
|
159 |
+
|
160 |
+
|
161 |
+
bool DoubleToStringConverter::ToShortestIeeeNumber(
|
162 |
+
double value,
|
163 |
+
StringBuilder* result_builder,
|
164 |
+
DoubleToStringConverter::DtoaMode mode) const {
|
165 |
+
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE);
|
166 |
+
if (Double(value).IsSpecial()) {
|
167 |
+
return HandleSpecialValues(value, result_builder);
|
168 |
+
}
|
169 |
+
|
170 |
+
int decimal_point;
|
171 |
+
bool sign;
|
172 |
+
const int kDecimalRepCapacity = kBase10MaximalLength + 1;
|
173 |
+
char decimal_rep[kDecimalRepCapacity];
|
174 |
+
int decimal_rep_length;
|
175 |
+
|
176 |
+
DoubleToAscii(value, mode, 0, decimal_rep, kDecimalRepCapacity,
|
177 |
+
&sign, &decimal_rep_length, &decimal_point);
|
178 |
+
|
179 |
+
bool unique_zero = (flags_ & UNIQUE_ZERO) != 0;
|
180 |
+
if (sign && (value != 0.0 || !unique_zero)) {
|
181 |
+
result_builder->AddCharacter('-');
|
182 |
+
}
|
183 |
+
|
184 |
+
int exponent = decimal_point - 1;
|
185 |
+
if ((decimal_in_shortest_low_ <= exponent) &&
|
186 |
+
(exponent < decimal_in_shortest_high_)) {
|
187 |
+
CreateDecimalRepresentation(decimal_rep, decimal_rep_length,
|
188 |
+
decimal_point,
|
189 |
+
Max(0, decimal_rep_length - decimal_point),
|
190 |
+
result_builder);
|
191 |
+
} else {
|
192 |
+
CreateExponentialRepresentation(decimal_rep, decimal_rep_length, exponent,
|
193 |
+
result_builder);
|
194 |
+
}
|
195 |
+
return true;
|
196 |
+
}
|
197 |
+
|
198 |
+
|
199 |
+
bool DoubleToStringConverter::ToFixed(double value,
|
200 |
+
int requested_digits,
|
201 |
+
StringBuilder* result_builder) const {
|
202 |
+
ASSERT(kMaxFixedDigitsBeforePoint == 60);
|
203 |
+
const double kFirstNonFixed = 1e60;
|
204 |
+
|
205 |
+
if (Double(value).IsSpecial()) {
|
206 |
+
return HandleSpecialValues(value, result_builder);
|
207 |
+
}
|
208 |
+
|
209 |
+
if (requested_digits > kMaxFixedDigitsAfterPoint) return false;
|
210 |
+
if (value >= kFirstNonFixed || value <= -kFirstNonFixed) return false;
|
211 |
+
|
212 |
+
// Find a sufficiently precise decimal representation of n.
|
213 |
+
int decimal_point;
|
214 |
+
bool sign;
|
215 |
+
// Add space for the '\0' byte.
|
216 |
+
const int kDecimalRepCapacity =
|
217 |
+
kMaxFixedDigitsBeforePoint + kMaxFixedDigitsAfterPoint + 1;
|
218 |
+
char decimal_rep[kDecimalRepCapacity];
|
219 |
+
int decimal_rep_length;
|
220 |
+
DoubleToAscii(value, FIXED, requested_digits,
|
221 |
+
decimal_rep, kDecimalRepCapacity,
|
222 |
+
&sign, &decimal_rep_length, &decimal_point);
|
223 |
+
|
224 |
+
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
225 |
+
if (sign && (value != 0.0 || !unique_zero)) {
|
226 |
+
result_builder->AddCharacter('-');
|
227 |
+
}
|
228 |
+
|
229 |
+
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
230 |
+
requested_digits, result_builder);
|
231 |
+
return true;
|
232 |
+
}
|
233 |
+
|
234 |
+
|
235 |
+
bool DoubleToStringConverter::ToExponential(
|
236 |
+
double value,
|
237 |
+
int requested_digits,
|
238 |
+
StringBuilder* result_builder) const {
|
239 |
+
if (Double(value).IsSpecial()) {
|
240 |
+
return HandleSpecialValues(value, result_builder);
|
241 |
+
}
|
242 |
+
|
243 |
+
if (requested_digits < -1) return false;
|
244 |
+
if (requested_digits > kMaxExponentialDigits) return false;
|
245 |
+
|
246 |
+
int decimal_point;
|
247 |
+
bool sign;
|
248 |
+
// Add space for digit before the decimal point and the '\0' character.
|
249 |
+
const int kDecimalRepCapacity = kMaxExponentialDigits + 2;
|
250 |
+
ASSERT(kDecimalRepCapacity > kBase10MaximalLength);
|
251 |
+
char decimal_rep[kDecimalRepCapacity];
|
252 |
+
int decimal_rep_length;
|
253 |
+
|
254 |
+
if (requested_digits == -1) {
|
255 |
+
DoubleToAscii(value, SHORTEST, 0,
|
256 |
+
decimal_rep, kDecimalRepCapacity,
|
257 |
+
&sign, &decimal_rep_length, &decimal_point);
|
258 |
+
} else {
|
259 |
+
DoubleToAscii(value, PRECISION, requested_digits + 1,
|
260 |
+
decimal_rep, kDecimalRepCapacity,
|
261 |
+
&sign, &decimal_rep_length, &decimal_point);
|
262 |
+
ASSERT(decimal_rep_length <= requested_digits + 1);
|
263 |
+
|
264 |
+
for (int i = decimal_rep_length; i < requested_digits + 1; ++i) {
|
265 |
+
decimal_rep[i] = '0';
|
266 |
+
}
|
267 |
+
decimal_rep_length = requested_digits + 1;
|
268 |
+
}
|
269 |
+
|
270 |
+
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
271 |
+
if (sign && (value != 0.0 || !unique_zero)) {
|
272 |
+
result_builder->AddCharacter('-');
|
273 |
+
}
|
274 |
+
|
275 |
+
int exponent = decimal_point - 1;
|
276 |
+
CreateExponentialRepresentation(decimal_rep,
|
277 |
+
decimal_rep_length,
|
278 |
+
exponent,
|
279 |
+
result_builder);
|
280 |
+
return true;
|
281 |
+
}
|
282 |
+
|
283 |
+
|
284 |
+
bool DoubleToStringConverter::ToPrecision(double value,
|
285 |
+
int precision,
|
286 |
+
StringBuilder* result_builder) const {
|
287 |
+
if (Double(value).IsSpecial()) {
|
288 |
+
return HandleSpecialValues(value, result_builder);
|
289 |
+
}
|
290 |
+
|
291 |
+
if (precision < kMinPrecisionDigits || precision > kMaxPrecisionDigits) {
|
292 |
+
return false;
|
293 |
+
}
|
294 |
+
|
295 |
+
// Find a sufficiently precise decimal representation of n.
|
296 |
+
int decimal_point;
|
297 |
+
bool sign;
|
298 |
+
// Add one for the terminating null character.
|
299 |
+
const int kDecimalRepCapacity = kMaxPrecisionDigits + 1;
|
300 |
+
char decimal_rep[kDecimalRepCapacity];
|
301 |
+
int decimal_rep_length;
|
302 |
+
|
303 |
+
DoubleToAscii(value, PRECISION, precision,
|
304 |
+
decimal_rep, kDecimalRepCapacity,
|
305 |
+
&sign, &decimal_rep_length, &decimal_point);
|
306 |
+
ASSERT(decimal_rep_length <= precision);
|
307 |
+
|
308 |
+
bool unique_zero = ((flags_ & UNIQUE_ZERO) != 0);
|
309 |
+
if (sign && (value != 0.0 || !unique_zero)) {
|
310 |
+
result_builder->AddCharacter('-');
|
311 |
+
}
|
312 |
+
|
313 |
+
// The exponent if we print the number as x.xxeyyy. That is with the
|
314 |
+
// decimal point after the first digit.
|
315 |
+
int exponent = decimal_point - 1;
|
316 |
+
|
317 |
+
int extra_zero = ((flags_ & EMIT_TRAILING_ZERO_AFTER_POINT) != 0) ? 1 : 0;
|
318 |
+
if ((-decimal_point + 1 > max_leading_padding_zeroes_in_precision_mode_) ||
|
319 |
+
(decimal_point - precision + extra_zero >
|
320 |
+
max_trailing_padding_zeroes_in_precision_mode_)) {
|
321 |
+
// Fill buffer to contain 'precision' digits.
|
322 |
+
// Usually the buffer is already at the correct length, but 'DoubleToAscii'
|
323 |
+
// is allowed to return less characters.
|
324 |
+
for (int i = decimal_rep_length; i < precision; ++i) {
|
325 |
+
decimal_rep[i] = '0';
|
326 |
+
}
|
327 |
+
|
328 |
+
CreateExponentialRepresentation(decimal_rep,
|
329 |
+
precision,
|
330 |
+
exponent,
|
331 |
+
result_builder);
|
332 |
+
} else {
|
333 |
+
CreateDecimalRepresentation(decimal_rep, decimal_rep_length, decimal_point,
|
334 |
+
Max(0, precision - decimal_point),
|
335 |
+
result_builder);
|
336 |
+
}
|
337 |
+
return true;
|
338 |
+
}
|
339 |
+
|
340 |
+
|
341 |
+
static BignumDtoaMode DtoaToBignumDtoaMode(
|
342 |
+
DoubleToStringConverter::DtoaMode dtoa_mode) {
|
343 |
+
switch (dtoa_mode) {
|
344 |
+
case DoubleToStringConverter::SHORTEST: return BIGNUM_DTOA_SHORTEST;
|
345 |
+
case DoubleToStringConverter::SHORTEST_SINGLE:
|
346 |
+
return BIGNUM_DTOA_SHORTEST_SINGLE;
|
347 |
+
case DoubleToStringConverter::FIXED: return BIGNUM_DTOA_FIXED;
|
348 |
+
case DoubleToStringConverter::PRECISION: return BIGNUM_DTOA_PRECISION;
|
349 |
+
default:
|
350 |
+
UNREACHABLE();
|
351 |
+
}
|
352 |
+
}
|
353 |
+
|
354 |
+
|
355 |
+
void DoubleToStringConverter::DoubleToAscii(double v,
|
356 |
+
DtoaMode mode,
|
357 |
+
int requested_digits,
|
358 |
+
char* buffer,
|
359 |
+
int buffer_length,
|
360 |
+
bool* sign,
|
361 |
+
int* length,
|
362 |
+
int* point) {
|
363 |
+
Vector<char> vector(buffer, buffer_length);
|
364 |
+
ASSERT(!Double(v).IsSpecial());
|
365 |
+
ASSERT(mode == SHORTEST || mode == SHORTEST_SINGLE || requested_digits >= 0);
|
366 |
+
|
367 |
+
if (Double(v).Sign() < 0) {
|
368 |
+
*sign = true;
|
369 |
+
v = -v;
|
370 |
+
} else {
|
371 |
+
*sign = false;
|
372 |
+
}
|
373 |
+
|
374 |
+
if (mode == PRECISION && requested_digits == 0) {
|
375 |
+
vector[0] = '\0';
|
376 |
+
*length = 0;
|
377 |
+
return;
|
378 |
+
}
|
379 |
+
|
380 |
+
if (v == 0) {
|
381 |
+
vector[0] = '0';
|
382 |
+
vector[1] = '\0';
|
383 |
+
*length = 1;
|
384 |
+
*point = 1;
|
385 |
+
return;
|
386 |
+
}
|
387 |
+
|
388 |
+
bool fast_worked;
|
389 |
+
switch (mode) {
|
390 |
+
case SHORTEST:
|
391 |
+
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST, 0, vector, length, point);
|
392 |
+
break;
|
393 |
+
case SHORTEST_SINGLE:
|
394 |
+
fast_worked = FastDtoa(v, FAST_DTOA_SHORTEST_SINGLE, 0,
|
395 |
+
vector, length, point);
|
396 |
+
break;
|
397 |
+
case FIXED:
|
398 |
+
fast_worked = FastFixedDtoa(v, requested_digits, vector, length, point);
|
399 |
+
break;
|
400 |
+
case PRECISION:
|
401 |
+
fast_worked = FastDtoa(v, FAST_DTOA_PRECISION, requested_digits,
|
402 |
+
vector, length, point);
|
403 |
+
break;
|
404 |
+
default:
|
405 |
+
fast_worked = false;
|
406 |
+
UNREACHABLE();
|
407 |
+
}
|
408 |
+
if (fast_worked) return;
|
409 |
+
|
410 |
+
// If the fast dtoa didn't succeed use the slower bignum version.
|
411 |
+
BignumDtoaMode bignum_mode = DtoaToBignumDtoaMode(mode);
|
412 |
+
BignumDtoa(v, bignum_mode, requested_digits, vector, length, point);
|
413 |
+
vector[*length] = '\0';
|
414 |
+
}
|
415 |
+
|
416 |
+
|
417 |
+
// Consumes the given substring from the iterator.
|
418 |
+
// Returns false, if the substring does not match.
|
419 |
+
template <class Iterator>
|
420 |
+
static bool ConsumeSubString(Iterator* current,
|
421 |
+
Iterator end,
|
422 |
+
const char* substring) {
|
423 |
+
ASSERT(**current == *substring);
|
424 |
+
for (substring++; *substring != '\0'; substring++) {
|
425 |
+
++*current;
|
426 |
+
if (*current == end || **current != *substring) return false;
|
427 |
+
}
|
428 |
+
++*current;
|
429 |
+
return true;
|
430 |
+
}
|
431 |
+
|
432 |
+
|
433 |
+
// Maximum number of significant digits in decimal representation.
|
434 |
+
// The longest possible double in decimal representation is
|
435 |
+
// (2^53 - 1) * 2 ^ -1074 that is (2 ^ 53 - 1) * 5 ^ 1074 / 10 ^ 1074
|
436 |
+
// (768 digits). If we parse a number whose first digits are equal to a
|
437 |
+
// mean of 2 adjacent doubles (that could have up to 769 digits) the result
|
438 |
+
// must be rounded to the bigger one unless the tail consists of zeros, so
|
439 |
+
// we don't need to preserve all the digits.
|
440 |
+
const int kMaxSignificantDigits = 772;
|
441 |
+
|
442 |
+
|
443 |
+
static const char kWhitespaceTable7[] = { 32, 13, 10, 9, 11, 12 };
|
444 |
+
static const int kWhitespaceTable7Length = ARRAY_SIZE(kWhitespaceTable7);
|
445 |
+
|
446 |
+
|
447 |
+
static const uc16 kWhitespaceTable16[] = {
|
448 |
+
160, 8232, 8233, 5760, 6158, 8192, 8193, 8194, 8195,
|
449 |
+
8196, 8197, 8198, 8199, 8200, 8201, 8202, 8239, 8287, 12288, 65279
|
450 |
+
};
|
451 |
+
static const int kWhitespaceTable16Length = ARRAY_SIZE(kWhitespaceTable16);
|
452 |
+
|
453 |
+
|
454 |
+
static bool isWhitespace(int x) {
|
455 |
+
if (x < 128) {
|
456 |
+
for (int i = 0; i < kWhitespaceTable7Length; i++) {
|
457 |
+
if (kWhitespaceTable7[i] == x) return true;
|
458 |
+
}
|
459 |
+
} else {
|
460 |
+
for (int i = 0; i < kWhitespaceTable16Length; i++) {
|
461 |
+
if (kWhitespaceTable16[i] == x) return true;
|
462 |
+
}
|
463 |
+
}
|
464 |
+
return false;
|
465 |
+
}
|
466 |
+
|
467 |
+
|
468 |
+
// Returns true if a nonspace found and false if the end has reached.
|
469 |
+
template <class Iterator>
|
470 |
+
static inline bool AdvanceToNonspace(Iterator* current, Iterator end) {
|
471 |
+
while (*current != end) {
|
472 |
+
if (!isWhitespace(**current)) return true;
|
473 |
+
++*current;
|
474 |
+
}
|
475 |
+
return false;
|
476 |
+
}
|
477 |
+
|
478 |
+
|
479 |
+
static bool isDigit(int x, int radix) {
|
480 |
+
return (x >= '0' && x <= '9' && x < '0' + radix)
|
481 |
+
|| (radix > 10 && x >= 'a' && x < 'a' + radix - 10)
|
482 |
+
|| (radix > 10 && x >= 'A' && x < 'A' + radix - 10);
|
483 |
+
}
|
484 |
+
|
485 |
+
|
486 |
+
static double SignedZero(bool sign) {
|
487 |
+
return sign ? -0.0 : 0.0;
|
488 |
+
}
|
489 |
+
|
490 |
+
|
491 |
+
// Returns true if 'c' is a decimal digit that is valid for the given radix.
|
492 |
+
//
|
493 |
+
// The function is small and could be inlined, but VS2012 emitted a warning
|
494 |
+
// because it constant-propagated the radix and concluded that the last
|
495 |
+
// condition was always true. By moving it into a separate function the
|
496 |
+
// compiler wouldn't warn anymore.
|
497 |
+
#if _MSC_VER
|
498 |
+
#pragma optimize("",off)
|
499 |
+
static bool IsDecimalDigitForRadix(int c, int radix) {
|
500 |
+
return '0' <= c && c <= '9' && (c - '0') < radix;
|
501 |
+
}
|
502 |
+
#pragma optimize("",on)
|
503 |
+
#else
|
504 |
+
static bool inline IsDecimalDigitForRadix(int c, int radix) {
|
505 |
+
return '0' <= c && c <= '9' && (c - '0') < radix;
|
506 |
+
}
|
507 |
+
#endif
|
508 |
+
// Returns true if 'c' is a character digit that is valid for the given radix.
|
509 |
+
// The 'a_character' should be 'a' or 'A'.
|
510 |
+
//
|
511 |
+
// The function is small and could be inlined, but VS2012 emitted a warning
|
512 |
+
// because it constant-propagated the radix and concluded that the first
|
513 |
+
// condition was always false. By moving it into a separate function the
|
514 |
+
// compiler wouldn't warn anymore.
|
515 |
+
static bool IsCharacterDigitForRadix(int c, int radix, char a_character) {
|
516 |
+
return radix > 10 && c >= a_character && c < a_character + radix - 10;
|
517 |
+
}
|
518 |
+
|
519 |
+
|
520 |
+
// Parsing integers with radix 2, 4, 8, 16, 32. Assumes current != end.
|
521 |
+
template <int radix_log_2, class Iterator>
|
522 |
+
static double RadixStringToIeee(Iterator* current,
|
523 |
+
Iterator end,
|
524 |
+
bool sign,
|
525 |
+
bool allow_trailing_junk,
|
526 |
+
double junk_string_value,
|
527 |
+
bool read_as_double,
|
528 |
+
bool* result_is_junk) {
|
529 |
+
ASSERT(*current != end);
|
530 |
+
|
531 |
+
const int kDoubleSize = Double::kSignificandSize;
|
532 |
+
const int kSingleSize = Single::kSignificandSize;
|
533 |
+
const int kSignificandSize = read_as_double? kDoubleSize: kSingleSize;
|
534 |
+
|
535 |
+
*result_is_junk = true;
|
536 |
+
|
537 |
+
// Skip leading 0s.
|
538 |
+
while (**current == '0') {
|
539 |
+
++(*current);
|
540 |
+
if (*current == end) {
|
541 |
+
*result_is_junk = false;
|
542 |
+
return SignedZero(sign);
|
543 |
+
}
|
544 |
+
}
|
545 |
+
|
546 |
+
int64_t number = 0;
|
547 |
+
int exponent = 0;
|
548 |
+
const int radix = (1 << radix_log_2);
|
549 |
+
|
550 |
+
do {
|
551 |
+
int digit;
|
552 |
+
if (IsDecimalDigitForRadix(**current, radix)) {
|
553 |
+
digit = static_cast<char>(**current) - '0';
|
554 |
+
} else if (IsCharacterDigitForRadix(**current, radix, 'a')) {
|
555 |
+
digit = static_cast<char>(**current) - 'a' + 10;
|
556 |
+
} else if (IsCharacterDigitForRadix(**current, radix, 'A')) {
|
557 |
+
digit = static_cast<char>(**current) - 'A' + 10;
|
558 |
+
} else {
|
559 |
+
if (allow_trailing_junk || !AdvanceToNonspace(current, end)) {
|
560 |
+
break;
|
561 |
+
} else {
|
562 |
+
return junk_string_value;
|
563 |
+
}
|
564 |
+
}
|
565 |
+
|
566 |
+
number = number * radix + digit;
|
567 |
+
int overflow = static_cast<int>(number >> kSignificandSize);
|
568 |
+
if (overflow != 0) {
|
569 |
+
// Overflow occurred. Need to determine which direction to round the
|
570 |
+
// result.
|
571 |
+
int overflow_bits_count = 1;
|
572 |
+
while (overflow > 1) {
|
573 |
+
overflow_bits_count++;
|
574 |
+
overflow >>= 1;
|
575 |
+
}
|
576 |
+
|
577 |
+
int dropped_bits_mask = ((1 << overflow_bits_count) - 1);
|
578 |
+
int dropped_bits = static_cast<int>(number) & dropped_bits_mask;
|
579 |
+
number >>= overflow_bits_count;
|
580 |
+
exponent = overflow_bits_count;
|
581 |
+
|
582 |
+
bool zero_tail = true;
|
583 |
+
for (;;) {
|
584 |
+
++(*current);
|
585 |
+
if (*current == end || !isDigit(**current, radix)) break;
|
586 |
+
zero_tail = zero_tail && **current == '0';
|
587 |
+
exponent += radix_log_2;
|
588 |
+
}
|
589 |
+
|
590 |
+
if (!allow_trailing_junk && AdvanceToNonspace(current, end)) {
|
591 |
+
return junk_string_value;
|
592 |
+
}
|
593 |
+
|
594 |
+
int middle_value = (1 << (overflow_bits_count - 1));
|
595 |
+
if (dropped_bits > middle_value) {
|
596 |
+
number++; // Rounding up.
|
597 |
+
} else if (dropped_bits == middle_value) {
|
598 |
+
// Rounding to even to consistency with decimals: half-way case rounds
|
599 |
+
// up if significant part is odd and down otherwise.
|
600 |
+
if ((number & 1) != 0 || !zero_tail) {
|
601 |
+
number++; // Rounding up.
|
602 |
+
}
|
603 |
+
}
|
604 |
+
|
605 |
+
// Rounding up may cause overflow.
|
606 |
+
if ((number & ((int64_t)1 << kSignificandSize)) != 0) {
|
607 |
+
exponent++;
|
608 |
+
number >>= 1;
|
609 |
+
}
|
610 |
+
break;
|
611 |
+
}
|
612 |
+
++(*current);
|
613 |
+
} while (*current != end);
|
614 |
+
|
615 |
+
ASSERT(number < ((int64_t)1 << kSignificandSize));
|
616 |
+
ASSERT(static_cast<int64_t>(static_cast<double>(number)) == number);
|
617 |
+
|
618 |
+
*result_is_junk = false;
|
619 |
+
|
620 |
+
if (exponent == 0) {
|
621 |
+
if (sign) {
|
622 |
+
if (number == 0) return -0.0;
|
623 |
+
number = -number;
|
624 |
+
}
|
625 |
+
return static_cast<double>(number);
|
626 |
+
}
|
627 |
+
|
628 |
+
ASSERT(number != 0);
|
629 |
+
return Double(DiyFp(number, exponent)).value();
|
630 |
+
}
|
631 |
+
|
632 |
+
|
633 |
+
template <class Iterator>
|
634 |
+
double StringToDoubleConverter::StringToIeee(
|
635 |
+
Iterator input,
|
636 |
+
int length,
|
637 |
+
bool read_as_double,
|
638 |
+
int* processed_characters_count) const {
|
639 |
+
Iterator current = input;
|
640 |
+
Iterator end = input + length;
|
641 |
+
|
642 |
+
*processed_characters_count = 0;
|
643 |
+
|
644 |
+
const bool allow_trailing_junk = (flags_ & ALLOW_TRAILING_JUNK) != 0;
|
645 |
+
const bool allow_leading_spaces = (flags_ & ALLOW_LEADING_SPACES) != 0;
|
646 |
+
const bool allow_trailing_spaces = (flags_ & ALLOW_TRAILING_SPACES) != 0;
|
647 |
+
const bool allow_spaces_after_sign = (flags_ & ALLOW_SPACES_AFTER_SIGN) != 0;
|
648 |
+
|
649 |
+
// To make sure that iterator dereferencing is valid the following
|
650 |
+
// convention is used:
|
651 |
+
// 1. Each '++current' statement is followed by check for equality to 'end'.
|
652 |
+
// 2. If AdvanceToNonspace returned false then current == end.
|
653 |
+
// 3. If 'current' becomes equal to 'end' the function returns or goes to
|
654 |
+
// 'parsing_done'.
|
655 |
+
// 4. 'current' is not dereferenced after the 'parsing_done' label.
|
656 |
+
// 5. Code before 'parsing_done' may rely on 'current != end'.
|
657 |
+
if (current == end) return empty_string_value_;
|
658 |
+
|
659 |
+
if (allow_leading_spaces || allow_trailing_spaces) {
|
660 |
+
if (!AdvanceToNonspace(¤t, end)) {
|
661 |
+
*processed_characters_count = static_cast<int>(current - input);
|
662 |
+
return empty_string_value_;
|
663 |
+
}
|
664 |
+
if (!allow_leading_spaces && (input != current)) {
|
665 |
+
// No leading spaces allowed, but AdvanceToNonspace moved forward.
|
666 |
+
return junk_string_value_;
|
667 |
+
}
|
668 |
+
}
|
669 |
+
|
670 |
+
// The longest form of simplified number is: "-<significant digits>.1eXXX\0".
|
671 |
+
const int kBufferSize = kMaxSignificantDigits + 10;
|
672 |
+
char buffer[kBufferSize]; // NOLINT: size is known at compile time.
|
673 |
+
int buffer_pos = 0;
|
674 |
+
|
675 |
+
// Exponent will be adjusted if insignificant digits of the integer part
|
676 |
+
// or insignificant leading zeros of the fractional part are dropped.
|
677 |
+
int exponent = 0;
|
678 |
+
int significant_digits = 0;
|
679 |
+
int insignificant_digits = 0;
|
680 |
+
bool nonzero_digit_dropped = false;
|
681 |
+
|
682 |
+
bool sign = false;
|
683 |
+
|
684 |
+
if (*current == '+' || *current == '-') {
|
685 |
+
sign = (*current == '-');
|
686 |
+
++current;
|
687 |
+
Iterator next_non_space = current;
|
688 |
+
// Skip following spaces (if allowed).
|
689 |
+
if (!AdvanceToNonspace(&next_non_space, end)) return junk_string_value_;
|
690 |
+
if (!allow_spaces_after_sign && (current != next_non_space)) {
|
691 |
+
return junk_string_value_;
|
692 |
+
}
|
693 |
+
current = next_non_space;
|
694 |
+
}
|
695 |
+
|
696 |
+
if (infinity_symbol_ != NULL) {
|
697 |
+
if (*current == infinity_symbol_[0]) {
|
698 |
+
if (!ConsumeSubString(¤t, end, infinity_symbol_)) {
|
699 |
+
return junk_string_value_;
|
700 |
+
}
|
701 |
+
|
702 |
+
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
703 |
+
return junk_string_value_;
|
704 |
+
}
|
705 |
+
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
706 |
+
return junk_string_value_;
|
707 |
+
}
|
708 |
+
|
709 |
+
ASSERT(buffer_pos == 0);
|
710 |
+
*processed_characters_count = static_cast<int>(current - input);
|
711 |
+
return sign ? -Double::Infinity() : Double::Infinity();
|
712 |
+
}
|
713 |
+
}
|
714 |
+
|
715 |
+
if (nan_symbol_ != NULL) {
|
716 |
+
if (*current == nan_symbol_[0]) {
|
717 |
+
if (!ConsumeSubString(¤t, end, nan_symbol_)) {
|
718 |
+
return junk_string_value_;
|
719 |
+
}
|
720 |
+
|
721 |
+
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
722 |
+
return junk_string_value_;
|
723 |
+
}
|
724 |
+
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
725 |
+
return junk_string_value_;
|
726 |
+
}
|
727 |
+
|
728 |
+
ASSERT(buffer_pos == 0);
|
729 |
+
*processed_characters_count = static_cast<int>(current - input);
|
730 |
+
return sign ? -Double::NaN() : Double::NaN();
|
731 |
+
}
|
732 |
+
}
|
733 |
+
|
734 |
+
bool leading_zero = false;
|
735 |
+
if (*current == '0') {
|
736 |
+
++current;
|
737 |
+
if (current == end) {
|
738 |
+
*processed_characters_count = static_cast<int>(current - input);
|
739 |
+
return SignedZero(sign);
|
740 |
+
}
|
741 |
+
|
742 |
+
leading_zero = true;
|
743 |
+
|
744 |
+
// It could be hexadecimal value.
|
745 |
+
if ((flags_ & ALLOW_HEX) && (*current == 'x' || *current == 'X')) {
|
746 |
+
++current;
|
747 |
+
if (current == end || !isDigit(*current, 16)) {
|
748 |
+
return junk_string_value_; // "0x".
|
749 |
+
}
|
750 |
+
|
751 |
+
bool result_is_junk;
|
752 |
+
double result = RadixStringToIeee<4>(¤t,
|
753 |
+
end,
|
754 |
+
sign,
|
755 |
+
allow_trailing_junk,
|
756 |
+
junk_string_value_,
|
757 |
+
read_as_double,
|
758 |
+
&result_is_junk);
|
759 |
+
if (!result_is_junk) {
|
760 |
+
if (allow_trailing_spaces) AdvanceToNonspace(¤t, end);
|
761 |
+
*processed_characters_count = static_cast<int>(current - input);
|
762 |
+
}
|
763 |
+
return result;
|
764 |
+
}
|
765 |
+
|
766 |
+
// Ignore leading zeros in the integer part.
|
767 |
+
while (*current == '0') {
|
768 |
+
++current;
|
769 |
+
if (current == end) {
|
770 |
+
*processed_characters_count = static_cast<int>(current - input);
|
771 |
+
return SignedZero(sign);
|
772 |
+
}
|
773 |
+
}
|
774 |
+
}
|
775 |
+
|
776 |
+
bool octal = leading_zero && (flags_ & ALLOW_OCTALS) != 0;
|
777 |
+
|
778 |
+
// Copy significant digits of the integer part (if any) to the buffer.
|
779 |
+
while (*current >= '0' && *current <= '9') {
|
780 |
+
if (significant_digits < kMaxSignificantDigits) {
|
781 |
+
ASSERT(buffer_pos < kBufferSize);
|
782 |
+
buffer[buffer_pos++] = static_cast<char>(*current);
|
783 |
+
significant_digits++;
|
784 |
+
// Will later check if it's an octal in the buffer.
|
785 |
+
} else {
|
786 |
+
insignificant_digits++; // Move the digit into the exponential part.
|
787 |
+
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
|
788 |
+
}
|
789 |
+
octal = octal && *current < '8';
|
790 |
+
++current;
|
791 |
+
if (current == end) goto parsing_done;
|
792 |
+
}
|
793 |
+
|
794 |
+
if (significant_digits == 0) {
|
795 |
+
octal = false;
|
796 |
+
}
|
797 |
+
|
798 |
+
if (*current == '.') {
|
799 |
+
if (octal && !allow_trailing_junk) return junk_string_value_;
|
800 |
+
if (octal) goto parsing_done;
|
801 |
+
|
802 |
+
++current;
|
803 |
+
if (current == end) {
|
804 |
+
if (significant_digits == 0 && !leading_zero) {
|
805 |
+
return junk_string_value_;
|
806 |
+
} else {
|
807 |
+
goto parsing_done;
|
808 |
+
}
|
809 |
+
}
|
810 |
+
|
811 |
+
if (significant_digits == 0) {
|
812 |
+
// octal = false;
|
813 |
+
// Integer part consists of 0 or is absent. Significant digits start after
|
814 |
+
// leading zeros (if any).
|
815 |
+
while (*current == '0') {
|
816 |
+
++current;
|
817 |
+
if (current == end) {
|
818 |
+
*processed_characters_count = static_cast<int>(current - input);
|
819 |
+
return SignedZero(sign);
|
820 |
+
}
|
821 |
+
exponent--; // Move this 0 into the exponent.
|
822 |
+
}
|
823 |
+
}
|
824 |
+
|
825 |
+
// There is a fractional part.
|
826 |
+
// We don't emit a '.', but adjust the exponent instead.
|
827 |
+
while (*current >= '0' && *current <= '9') {
|
828 |
+
if (significant_digits < kMaxSignificantDigits) {
|
829 |
+
ASSERT(buffer_pos < kBufferSize);
|
830 |
+
buffer[buffer_pos++] = static_cast<char>(*current);
|
831 |
+
significant_digits++;
|
832 |
+
exponent--;
|
833 |
+
} else {
|
834 |
+
// Ignore insignificant digits in the fractional part.
|
835 |
+
nonzero_digit_dropped = nonzero_digit_dropped || *current != '0';
|
836 |
+
}
|
837 |
+
++current;
|
838 |
+
if (current == end) goto parsing_done;
|
839 |
+
}
|
840 |
+
}
|
841 |
+
|
842 |
+
if (!leading_zero && exponent == 0 && significant_digits == 0) {
|
843 |
+
// If leading_zeros is true then the string contains zeros.
|
844 |
+
// If exponent < 0 then string was [+-]\.0*...
|
845 |
+
// If significant_digits != 0 the string is not equal to 0.
|
846 |
+
// Otherwise there are no digits in the string.
|
847 |
+
return junk_string_value_;
|
848 |
+
}
|
849 |
+
|
850 |
+
// Parse exponential part.
|
851 |
+
if (*current == 'e' || *current == 'E') {
|
852 |
+
if (octal && !allow_trailing_junk) return junk_string_value_;
|
853 |
+
if (octal) goto parsing_done;
|
854 |
+
++current;
|
855 |
+
if (current == end) {
|
856 |
+
if (allow_trailing_junk) {
|
857 |
+
goto parsing_done;
|
858 |
+
} else {
|
859 |
+
return junk_string_value_;
|
860 |
+
}
|
861 |
+
}
|
862 |
+
char exponen_sign = '+';
|
863 |
+
if (*current == '+' || *current == '-') {
|
864 |
+
exponen_sign = static_cast<char>(*current);
|
865 |
+
++current;
|
866 |
+
if (current == end) {
|
867 |
+
if (allow_trailing_junk) {
|
868 |
+
goto parsing_done;
|
869 |
+
} else {
|
870 |
+
return junk_string_value_;
|
871 |
+
}
|
872 |
+
}
|
873 |
+
}
|
874 |
+
|
875 |
+
if (current == end || *current < '0' || *current > '9') {
|
876 |
+
if (allow_trailing_junk) {
|
877 |
+
goto parsing_done;
|
878 |
+
} else {
|
879 |
+
return junk_string_value_;
|
880 |
+
}
|
881 |
+
}
|
882 |
+
|
883 |
+
const int max_exponent = INT_MAX / 2;
|
884 |
+
ASSERT(-max_exponent / 2 <= exponent && exponent <= max_exponent / 2);
|
885 |
+
int num = 0;
|
886 |
+
do {
|
887 |
+
// Check overflow.
|
888 |
+
int digit = *current - '0';
|
889 |
+
if (num >= max_exponent / 10
|
890 |
+
&& !(num == max_exponent / 10 && digit <= max_exponent % 10)) {
|
891 |
+
num = max_exponent;
|
892 |
+
} else {
|
893 |
+
num = num * 10 + digit;
|
894 |
+
}
|
895 |
+
++current;
|
896 |
+
} while (current != end && *current >= '0' && *current <= '9');
|
897 |
+
|
898 |
+
exponent += (exponen_sign == '-' ? -num : num);
|
899 |
+
}
|
900 |
+
|
901 |
+
if (!(allow_trailing_spaces || allow_trailing_junk) && (current != end)) {
|
902 |
+
return junk_string_value_;
|
903 |
+
}
|
904 |
+
if (!allow_trailing_junk && AdvanceToNonspace(¤t, end)) {
|
905 |
+
return junk_string_value_;
|
906 |
+
}
|
907 |
+
if (allow_trailing_spaces) {
|
908 |
+
AdvanceToNonspace(¤t, end);
|
909 |
+
}
|
910 |
+
|
911 |
+
parsing_done:
|
912 |
+
exponent += insignificant_digits;
|
913 |
+
|
914 |
+
if (octal) {
|
915 |
+
double result;
|
916 |
+
bool result_is_junk;
|
917 |
+
char* start = buffer;
|
918 |
+
result = RadixStringToIeee<3>(&start,
|
919 |
+
buffer + buffer_pos,
|
920 |
+
sign,
|
921 |
+
allow_trailing_junk,
|
922 |
+
junk_string_value_,
|
923 |
+
read_as_double,
|
924 |
+
&result_is_junk);
|
925 |
+
ASSERT(!result_is_junk);
|
926 |
+
*processed_characters_count = static_cast<int>(current - input);
|
927 |
+
return result;
|
928 |
+
}
|
929 |
+
|
930 |
+
if (nonzero_digit_dropped) {
|
931 |
+
buffer[buffer_pos++] = '1';
|
932 |
+
exponent--;
|
933 |
+
}
|
934 |
+
|
935 |
+
ASSERT(buffer_pos < kBufferSize);
|
936 |
+
buffer[buffer_pos] = '\0';
|
937 |
+
|
938 |
+
double converted;
|
939 |
+
if (read_as_double) {
|
940 |
+
converted = Strtod(Vector<const char>(buffer, buffer_pos), exponent);
|
941 |
+
} else {
|
942 |
+
converted = Strtof(Vector<const char>(buffer, buffer_pos), exponent);
|
943 |
+
}
|
944 |
+
*processed_characters_count = static_cast<int>(current - input);
|
945 |
+
return sign? -converted: converted;
|
946 |
+
}
|
947 |
+
|
948 |
+
|
949 |
+
double StringToDoubleConverter::StringToDouble(
|
950 |
+
const char* buffer,
|
951 |
+
int length,
|
952 |
+
int* processed_characters_count) const {
|
953 |
+
return StringToIeee(buffer, length, true, processed_characters_count);
|
954 |
+
}
|
955 |
+
|
956 |
+
|
957 |
+
double StringToDoubleConverter::StringToDouble(
|
958 |
+
const uc16* buffer,
|
959 |
+
int length,
|
960 |
+
int* processed_characters_count) const {
|
961 |
+
return StringToIeee(buffer, length, true, processed_characters_count);
|
962 |
+
}
|
963 |
+
|
964 |
+
|
965 |
+
float StringToDoubleConverter::StringToFloat(
|
966 |
+
const char* buffer,
|
967 |
+
int length,
|
968 |
+
int* processed_characters_count) const {
|
969 |
+
return static_cast<float>(StringToIeee(buffer, length, false,
|
970 |
+
processed_characters_count));
|
971 |
+
}
|
972 |
+
|
973 |
+
|
974 |
+
float StringToDoubleConverter::StringToFloat(
|
975 |
+
const uc16* buffer,
|
976 |
+
int length,
|
977 |
+
int* processed_characters_count) const {
|
978 |
+
return static_cast<float>(StringToIeee(buffer, length, false,
|
979 |
+
processed_characters_count));
|
980 |
+
}
|
981 |
+
|
982 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/double-conversion.h
ADDED
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2012 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
29 |
+
#define DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
class DoubleToStringConverter {
|
36 |
+
public:
|
37 |
+
// When calling ToFixed with a double > 10^kMaxFixedDigitsBeforePoint
|
38 |
+
// or a requested_digits parameter > kMaxFixedDigitsAfterPoint then the
|
39 |
+
// function returns false.
|
40 |
+
static const int kMaxFixedDigitsBeforePoint = 60;
|
41 |
+
static const int kMaxFixedDigitsAfterPoint = 60;
|
42 |
+
|
43 |
+
// When calling ToExponential with a requested_digits
|
44 |
+
// parameter > kMaxExponentialDigits then the function returns false.
|
45 |
+
static const int kMaxExponentialDigits = 120;
|
46 |
+
|
47 |
+
// When calling ToPrecision with a requested_digits
|
48 |
+
// parameter < kMinPrecisionDigits or requested_digits > kMaxPrecisionDigits
|
49 |
+
// then the function returns false.
|
50 |
+
static const int kMinPrecisionDigits = 1;
|
51 |
+
static const int kMaxPrecisionDigits = 120;
|
52 |
+
|
53 |
+
enum Flags {
|
54 |
+
NO_FLAGS = 0,
|
55 |
+
EMIT_POSITIVE_EXPONENT_SIGN = 1,
|
56 |
+
EMIT_TRAILING_DECIMAL_POINT = 2,
|
57 |
+
EMIT_TRAILING_ZERO_AFTER_POINT = 4,
|
58 |
+
UNIQUE_ZERO = 8
|
59 |
+
};
|
60 |
+
|
61 |
+
// Flags should be a bit-or combination of the possible Flags-enum.
|
62 |
+
// - NO_FLAGS: no special flags.
|
63 |
+
// - EMIT_POSITIVE_EXPONENT_SIGN: when the number is converted into exponent
|
64 |
+
// form, emits a '+' for positive exponents. Example: 1.2e+2.
|
65 |
+
// - EMIT_TRAILING_DECIMAL_POINT: when the input number is an integer and is
|
66 |
+
// converted into decimal format then a trailing decimal point is appended.
|
67 |
+
// Example: 2345.0 is converted to "2345.".
|
68 |
+
// - EMIT_TRAILING_ZERO_AFTER_POINT: in addition to a trailing decimal point
|
69 |
+
// emits a trailing '0'-character. This flag requires the
|
70 |
+
// EXMIT_TRAILING_DECIMAL_POINT flag.
|
71 |
+
// Example: 2345.0 is converted to "2345.0".
|
72 |
+
// - UNIQUE_ZERO: "-0.0" is converted to "0.0".
|
73 |
+
//
|
74 |
+
// Infinity symbol and nan_symbol provide the string representation for these
|
75 |
+
// special values. If the string is NULL and the special value is encountered
|
76 |
+
// then the conversion functions return false.
|
77 |
+
//
|
78 |
+
// The exponent_character is used in exponential representations. It is
|
79 |
+
// usually 'e' or 'E'.
|
80 |
+
//
|
81 |
+
// When converting to the shortest representation the converter will
|
82 |
+
// represent input numbers in decimal format if they are in the interval
|
83 |
+
// [10^decimal_in_shortest_low; 10^decimal_in_shortest_high[
|
84 |
+
// (lower boundary included, greater boundary excluded).
|
85 |
+
// Example: with decimal_in_shortest_low = -6 and
|
86 |
+
// decimal_in_shortest_high = 21:
|
87 |
+
// ToShortest(0.000001) -> "0.000001"
|
88 |
+
// ToShortest(0.0000001) -> "1e-7"
|
89 |
+
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
90 |
+
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
91 |
+
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
92 |
+
//
|
93 |
+
// When converting to precision mode the converter may add
|
94 |
+
// max_leading_padding_zeroes before returning the number in exponential
|
95 |
+
// format.
|
96 |
+
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
97 |
+
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
98 |
+
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
99 |
+
// Similarily the converter may add up to
|
100 |
+
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
101 |
+
// returning an exponential representation. A zero added by the
|
102 |
+
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
103 |
+
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
104 |
+
// ToPrecision(230.0, 2) -> "230"
|
105 |
+
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
106 |
+
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
107 |
+
DoubleToStringConverter(int flags,
|
108 |
+
const char* infinity_symbol,
|
109 |
+
const char* nan_symbol,
|
110 |
+
char exponent_character,
|
111 |
+
int decimal_in_shortest_low,
|
112 |
+
int decimal_in_shortest_high,
|
113 |
+
int max_leading_padding_zeroes_in_precision_mode,
|
114 |
+
int max_trailing_padding_zeroes_in_precision_mode)
|
115 |
+
: flags_(flags),
|
116 |
+
infinity_symbol_(infinity_symbol),
|
117 |
+
nan_symbol_(nan_symbol),
|
118 |
+
exponent_character_(exponent_character),
|
119 |
+
decimal_in_shortest_low_(decimal_in_shortest_low),
|
120 |
+
decimal_in_shortest_high_(decimal_in_shortest_high),
|
121 |
+
max_leading_padding_zeroes_in_precision_mode_(
|
122 |
+
max_leading_padding_zeroes_in_precision_mode),
|
123 |
+
max_trailing_padding_zeroes_in_precision_mode_(
|
124 |
+
max_trailing_padding_zeroes_in_precision_mode) {
|
125 |
+
// When 'trailing zero after the point' is set, then 'trailing point'
|
126 |
+
// must be set too.
|
127 |
+
ASSERT(((flags & EMIT_TRAILING_DECIMAL_POINT) != 0) ||
|
128 |
+
!((flags & EMIT_TRAILING_ZERO_AFTER_POINT) != 0));
|
129 |
+
}
|
130 |
+
|
131 |
+
// Returns a converter following the EcmaScript specification.
|
132 |
+
static const DoubleToStringConverter& EcmaScriptConverter();
|
133 |
+
|
134 |
+
// Computes the shortest string of digits that correctly represent the input
|
135 |
+
// number. Depending on decimal_in_shortest_low and decimal_in_shortest_high
|
136 |
+
// (see constructor) it then either returns a decimal representation, or an
|
137 |
+
// exponential representation.
|
138 |
+
// Example with decimal_in_shortest_low = -6,
|
139 |
+
// decimal_in_shortest_high = 21,
|
140 |
+
// EMIT_POSITIVE_EXPONENT_SIGN activated, and
|
141 |
+
// EMIT_TRAILING_DECIMAL_POINT deactived:
|
142 |
+
// ToShortest(0.000001) -> "0.000001"
|
143 |
+
// ToShortest(0.0000001) -> "1e-7"
|
144 |
+
// ToShortest(111111111111111111111.0) -> "111111111111111110000"
|
145 |
+
// ToShortest(100000000000000000000.0) -> "100000000000000000000"
|
146 |
+
// ToShortest(1111111111111111111111.0) -> "1.1111111111111111e+21"
|
147 |
+
//
|
148 |
+
// Note: the conversion may round the output if the returned string
|
149 |
+
// is accurate enough to uniquely identify the input-number.
|
150 |
+
// For example the most precise representation of the double 9e59 equals
|
151 |
+
// "899999999999999918767229449717619953810131273674690656206848", but
|
152 |
+
// the converter will return the shorter (but still correct) "9e59".
|
153 |
+
//
|
154 |
+
// Returns true if the conversion succeeds. The conversion always succeeds
|
155 |
+
// except when the input value is special and no infinity_symbol or
|
156 |
+
// nan_symbol has been given to the constructor.
|
157 |
+
bool ToShortest(double value, StringBuilder* result_builder) const {
|
158 |
+
return ToShortestIeeeNumber(value, result_builder, SHORTEST);
|
159 |
+
}
|
160 |
+
|
161 |
+
// Same as ToShortest, but for single-precision floats.
|
162 |
+
bool ToShortestSingle(float value, StringBuilder* result_builder) const {
|
163 |
+
return ToShortestIeeeNumber(value, result_builder, SHORTEST_SINGLE);
|
164 |
+
}
|
165 |
+
|
166 |
+
|
167 |
+
// Computes a decimal representation with a fixed number of digits after the
|
168 |
+
// decimal point. The last emitted digit is rounded.
|
169 |
+
//
|
170 |
+
// Examples:
|
171 |
+
// ToFixed(3.12, 1) -> "3.1"
|
172 |
+
// ToFixed(3.1415, 3) -> "3.142"
|
173 |
+
// ToFixed(1234.56789, 4) -> "1234.5679"
|
174 |
+
// ToFixed(1.23, 5) -> "1.23000"
|
175 |
+
// ToFixed(0.1, 4) -> "0.1000"
|
176 |
+
// ToFixed(1e30, 2) -> "1000000000000000019884624838656.00"
|
177 |
+
// ToFixed(0.1, 30) -> "0.100000000000000005551115123126"
|
178 |
+
// ToFixed(0.1, 17) -> "0.10000000000000001"
|
179 |
+
//
|
180 |
+
// If requested_digits equals 0, then the tail of the result depends on
|
181 |
+
// the EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT.
|
182 |
+
// Examples, for requested_digits == 0,
|
183 |
+
// let EMIT_TRAILING_DECIMAL_POINT and EMIT_TRAILING_ZERO_AFTER_POINT be
|
184 |
+
// - false and false: then 123.45 -> 123
|
185 |
+
// 0.678 -> 1
|
186 |
+
// - true and false: then 123.45 -> 123.
|
187 |
+
// 0.678 -> 1.
|
188 |
+
// - true and true: then 123.45 -> 123.0
|
189 |
+
// 0.678 -> 1.0
|
190 |
+
//
|
191 |
+
// Returns true if the conversion succeeds. The conversion always succeeds
|
192 |
+
// except for the following cases:
|
193 |
+
// - the input value is special and no infinity_symbol or nan_symbol has
|
194 |
+
// been provided to the constructor,
|
195 |
+
// - 'value' > 10^kMaxFixedDigitsBeforePoint, or
|
196 |
+
// - 'requested_digits' > kMaxFixedDigitsAfterPoint.
|
197 |
+
// The last two conditions imply that the result will never contain more than
|
198 |
+
// 1 + kMaxFixedDigitsBeforePoint + 1 + kMaxFixedDigitsAfterPoint characters
|
199 |
+
// (one additional character for the sign, and one for the decimal point).
|
200 |
+
bool ToFixed(double value,
|
201 |
+
int requested_digits,
|
202 |
+
StringBuilder* result_builder) const;
|
203 |
+
|
204 |
+
// Computes a representation in exponential format with requested_digits
|
205 |
+
// after the decimal point. The last emitted digit is rounded.
|
206 |
+
// If requested_digits equals -1, then the shortest exponential representation
|
207 |
+
// is computed.
|
208 |
+
//
|
209 |
+
// Examples with EMIT_POSITIVE_EXPONENT_SIGN deactivated, and
|
210 |
+
// exponent_character set to 'e'.
|
211 |
+
// ToExponential(3.12, 1) -> "3.1e0"
|
212 |
+
// ToExponential(5.0, 3) -> "5.000e0"
|
213 |
+
// ToExponential(0.001, 2) -> "1.00e-3"
|
214 |
+
// ToExponential(3.1415, -1) -> "3.1415e0"
|
215 |
+
// ToExponential(3.1415, 4) -> "3.1415e0"
|
216 |
+
// ToExponential(3.1415, 3) -> "3.142e0"
|
217 |
+
// ToExponential(123456789000000, 3) -> "1.235e14"
|
218 |
+
// ToExponential(1000000000000000019884624838656.0, -1) -> "1e30"
|
219 |
+
// ToExponential(1000000000000000019884624838656.0, 32) ->
|
220 |
+
// "1.00000000000000001988462483865600e30"
|
221 |
+
// ToExponential(1234, 0) -> "1e3"
|
222 |
+
//
|
223 |
+
// Returns true if the conversion succeeds. The conversion always succeeds
|
224 |
+
// except for the following cases:
|
225 |
+
// - the input value is special and no infinity_symbol or nan_symbol has
|
226 |
+
// been provided to the constructor,
|
227 |
+
// - 'requested_digits' > kMaxExponentialDigits.
|
228 |
+
// The last condition implies that the result will never contain more than
|
229 |
+
// kMaxExponentialDigits + 8 characters (the sign, the digit before the
|
230 |
+
// decimal point, the decimal point, the exponent character, the
|
231 |
+
// exponent's sign, and at most 3 exponent digits).
|
232 |
+
bool ToExponential(double value,
|
233 |
+
int requested_digits,
|
234 |
+
StringBuilder* result_builder) const;
|
235 |
+
|
236 |
+
// Computes 'precision' leading digits of the given 'value' and returns them
|
237 |
+
// either in exponential or decimal format, depending on
|
238 |
+
// max_{leading|trailing}_padding_zeroes_in_precision_mode (given to the
|
239 |
+
// constructor).
|
240 |
+
// The last computed digit is rounded.
|
241 |
+
//
|
242 |
+
// Example with max_leading_padding_zeroes_in_precision_mode = 6.
|
243 |
+
// ToPrecision(0.0000012345, 2) -> "0.0000012"
|
244 |
+
// ToPrecision(0.00000012345, 2) -> "1.2e-7"
|
245 |
+
// Similarily the converter may add up to
|
246 |
+
// max_trailing_padding_zeroes_in_precision_mode in precision mode to avoid
|
247 |
+
// returning an exponential representation. A zero added by the
|
248 |
+
// EMIT_TRAILING_ZERO_AFTER_POINT flag is counted for this limit.
|
249 |
+
// Examples for max_trailing_padding_zeroes_in_precision_mode = 1:
|
250 |
+
// ToPrecision(230.0, 2) -> "230"
|
251 |
+
// ToPrecision(230.0, 2) -> "230." with EMIT_TRAILING_DECIMAL_POINT.
|
252 |
+
// ToPrecision(230.0, 2) -> "2.3e2" with EMIT_TRAILING_ZERO_AFTER_POINT.
|
253 |
+
// Examples for max_trailing_padding_zeroes_in_precision_mode = 3, and no
|
254 |
+
// EMIT_TRAILING_ZERO_AFTER_POINT:
|
255 |
+
// ToPrecision(123450.0, 6) -> "123450"
|
256 |
+
// ToPrecision(123450.0, 5) -> "123450"
|
257 |
+
// ToPrecision(123450.0, 4) -> "123500"
|
258 |
+
// ToPrecision(123450.0, 3) -> "123000"
|
259 |
+
// ToPrecision(123450.0, 2) -> "1.2e5"
|
260 |
+
//
|
261 |
+
// Returns true if the conversion succeeds. The conversion always succeeds
|
262 |
+
// except for the following cases:
|
263 |
+
// - the input value is special and no infinity_symbol or nan_symbol has
|
264 |
+
// been provided to the constructor,
|
265 |
+
// - precision < kMinPericisionDigits
|
266 |
+
// - precision > kMaxPrecisionDigits
|
267 |
+
// The last condition implies that the result will never contain more than
|
268 |
+
// kMaxPrecisionDigits + 7 characters (the sign, the decimal point, the
|
269 |
+
// exponent character, the exponent's sign, and at most 3 exponent digits).
|
270 |
+
bool ToPrecision(double value,
|
271 |
+
int precision,
|
272 |
+
StringBuilder* result_builder) const;
|
273 |
+
|
274 |
+
enum DtoaMode {
|
275 |
+
// Produce the shortest correct representation.
|
276 |
+
// For example the output of 0.299999999999999988897 is (the less accurate
|
277 |
+
// but correct) 0.3.
|
278 |
+
SHORTEST,
|
279 |
+
// Same as SHORTEST, but for single-precision floats.
|
280 |
+
SHORTEST_SINGLE,
|
281 |
+
// Produce a fixed number of digits after the decimal point.
|
282 |
+
// For instance fixed(0.1, 4) becomes 0.1000
|
283 |
+
// If the input number is big, the output will be big.
|
284 |
+
FIXED,
|
285 |
+
// Fixed number of digits (independent of the decimal point).
|
286 |
+
PRECISION
|
287 |
+
};
|
288 |
+
|
289 |
+
// The maximal number of digits that are needed to emit a double in base 10.
|
290 |
+
// A higher precision can be achieved by using more digits, but the shortest
|
291 |
+
// accurate representation of any double will never use more digits than
|
292 |
+
// kBase10MaximalLength.
|
293 |
+
// Note that DoubleToAscii null-terminates its input. So the given buffer
|
294 |
+
// should be at least kBase10MaximalLength + 1 characters long.
|
295 |
+
static const int kBase10MaximalLength = 17;
|
296 |
+
|
297 |
+
// Converts the given double 'v' to ascii. 'v' must not be NaN, +Infinity, or
|
298 |
+
// -Infinity. In SHORTEST_SINGLE-mode this restriction also applies to 'v'
|
299 |
+
// after it has been casted to a single-precision float. That is, in this
|
300 |
+
// mode static_cast<float>(v) must not be NaN, +Infinity or -Infinity.
|
301 |
+
//
|
302 |
+
// The result should be interpreted as buffer * 10^(point-length).
|
303 |
+
//
|
304 |
+
// The output depends on the given mode:
|
305 |
+
// - SHORTEST: produce the least amount of digits for which the internal
|
306 |
+
// identity requirement is still satisfied. If the digits are printed
|
307 |
+
// (together with the correct exponent) then reading this number will give
|
308 |
+
// 'v' again. The buffer will choose the representation that is closest to
|
309 |
+
// 'v'. If there are two at the same distance, than the one farther away
|
310 |
+
// from 0 is chosen (halfway cases - ending with 5 - are rounded up).
|
311 |
+
// In this mode the 'requested_digits' parameter is ignored.
|
312 |
+
// - SHORTEST_SINGLE: same as SHORTEST but with single-precision.
|
313 |
+
// - FIXED: produces digits necessary to print a given number with
|
314 |
+
// 'requested_digits' digits after the decimal point. The produced digits
|
315 |
+
// might be too short in which case the caller has to fill the remainder
|
316 |
+
// with '0's.
|
317 |
+
// Example: toFixed(0.001, 5) is allowed to return buffer="1", point=-2.
|
318 |
+
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
319 |
+
// toFixed(0.15, 2) thus returns buffer="2", point=0.
|
320 |
+
// The returned buffer may contain digits that would be truncated from the
|
321 |
+
// shortest representation of the input.
|
322 |
+
// - PRECISION: produces 'requested_digits' where the first digit is not '0'.
|
323 |
+
// Even though the length of produced digits usually equals
|
324 |
+
// 'requested_digits', the function is allowed to return fewer digits, in
|
325 |
+
// which case the caller has to fill the missing digits with '0's.
|
326 |
+
// Halfway cases are again rounded away from 0.
|
327 |
+
// DoubleToAscii expects the given buffer to be big enough to hold all
|
328 |
+
// digits and a terminating null-character. In SHORTEST-mode it expects a
|
329 |
+
// buffer of at least kBase10MaximalLength + 1. In all other modes the
|
330 |
+
// requested_digits parameter and the padding-zeroes limit the size of the
|
331 |
+
// output. Don't forget the decimal point, the exponent character and the
|
332 |
+
// terminating null-character when computing the maximal output size.
|
333 |
+
// The given length is only used in debug mode to ensure the buffer is big
|
334 |
+
// enough.
|
335 |
+
static void DoubleToAscii(double v,
|
336 |
+
DtoaMode mode,
|
337 |
+
int requested_digits,
|
338 |
+
char* buffer,
|
339 |
+
int buffer_length,
|
340 |
+
bool* sign,
|
341 |
+
int* length,
|
342 |
+
int* point);
|
343 |
+
|
344 |
+
private:
|
345 |
+
// Implementation for ToShortest and ToShortestSingle.
|
346 |
+
bool ToShortestIeeeNumber(double value,
|
347 |
+
StringBuilder* result_builder,
|
348 |
+
DtoaMode mode) const;
|
349 |
+
|
350 |
+
// If the value is a special value (NaN or Infinity) constructs the
|
351 |
+
// corresponding string using the configured infinity/nan-symbol.
|
352 |
+
// If either of them is NULL or the value is not special then the
|
353 |
+
// function returns false.
|
354 |
+
bool HandleSpecialValues(double value, StringBuilder* result_builder) const;
|
355 |
+
// Constructs an exponential representation (i.e. 1.234e56).
|
356 |
+
// The given exponent assumes a decimal point after the first decimal digit.
|
357 |
+
void CreateExponentialRepresentation(const char* decimal_digits,
|
358 |
+
int length,
|
359 |
+
int exponent,
|
360 |
+
StringBuilder* result_builder) const;
|
361 |
+
// Creates a decimal representation (i.e 1234.5678).
|
362 |
+
void CreateDecimalRepresentation(const char* decimal_digits,
|
363 |
+
int length,
|
364 |
+
int decimal_point,
|
365 |
+
int digits_after_point,
|
366 |
+
StringBuilder* result_builder) const;
|
367 |
+
|
368 |
+
const int flags_;
|
369 |
+
const char* const infinity_symbol_;
|
370 |
+
const char* const nan_symbol_;
|
371 |
+
const char exponent_character_;
|
372 |
+
const int decimal_in_shortest_low_;
|
373 |
+
const int decimal_in_shortest_high_;
|
374 |
+
const int max_leading_padding_zeroes_in_precision_mode_;
|
375 |
+
const int max_trailing_padding_zeroes_in_precision_mode_;
|
376 |
+
|
377 |
+
DISALLOW_IMPLICIT_CONSTRUCTORS(DoubleToStringConverter);
|
378 |
+
};
|
379 |
+
|
380 |
+
|
381 |
+
class StringToDoubleConverter {
|
382 |
+
public:
|
383 |
+
// Enumeration for allowing octals and ignoring junk when converting
|
384 |
+
// strings to numbers.
|
385 |
+
enum Flags {
|
386 |
+
NO_FLAGS = 0,
|
387 |
+
ALLOW_HEX = 1,
|
388 |
+
ALLOW_OCTALS = 2,
|
389 |
+
ALLOW_TRAILING_JUNK = 4,
|
390 |
+
ALLOW_LEADING_SPACES = 8,
|
391 |
+
ALLOW_TRAILING_SPACES = 16,
|
392 |
+
ALLOW_SPACES_AFTER_SIGN = 32
|
393 |
+
};
|
394 |
+
|
395 |
+
// Flags should be a bit-or combination of the possible Flags-enum.
|
396 |
+
// - NO_FLAGS: no special flags.
|
397 |
+
// - ALLOW_HEX: recognizes the prefix "0x". Hex numbers may only be integers.
|
398 |
+
// Ex: StringToDouble("0x1234") -> 4660.0
|
399 |
+
// In StringToDouble("0x1234.56") the characters ".56" are trailing
|
400 |
+
// junk. The result of the call is hence dependent on
|
401 |
+
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
402 |
+
// With this flag "0x" is a junk-string. Even with ALLOW_TRAILING_JUNK,
|
403 |
+
// the string will not be parsed as "0" followed by junk.
|
404 |
+
//
|
405 |
+
// - ALLOW_OCTALS: recognizes the prefix "0" for octals:
|
406 |
+
// If a sequence of octal digits starts with '0', then the number is
|
407 |
+
// read as octal integer. Octal numbers may only be integers.
|
408 |
+
// Ex: StringToDouble("01234") -> 668.0
|
409 |
+
// StringToDouble("012349") -> 12349.0 // Not a sequence of octal
|
410 |
+
// // digits.
|
411 |
+
// In StringToDouble("01234.56") the characters ".56" are trailing
|
412 |
+
// junk. The result of the call is hence dependent on
|
413 |
+
// the ALLOW_TRAILING_JUNK flag and/or the junk value.
|
414 |
+
// In StringToDouble("01234e56") the characters "e56" are trailing
|
415 |
+
// junk, too.
|
416 |
+
// - ALLOW_TRAILING_JUNK: ignore trailing characters that are not part of
|
417 |
+
// a double literal.
|
418 |
+
// - ALLOW_LEADING_SPACES: skip over leading whitespace, including spaces,
|
419 |
+
// new-lines, and tabs.
|
420 |
+
// - ALLOW_TRAILING_SPACES: ignore trailing whitespace.
|
421 |
+
// - ALLOW_SPACES_AFTER_SIGN: ignore whitespace after the sign.
|
422 |
+
// Ex: StringToDouble("- 123.2") -> -123.2.
|
423 |
+
// StringToDouble("+ 123.2") -> 123.2
|
424 |
+
//
|
425 |
+
// empty_string_value is returned when an empty string is given as input.
|
426 |
+
// If ALLOW_LEADING_SPACES or ALLOW_TRAILING_SPACES are set, then a string
|
427 |
+
// containing only spaces is converted to the 'empty_string_value', too.
|
428 |
+
//
|
429 |
+
// junk_string_value is returned when
|
430 |
+
// a) ALLOW_TRAILING_JUNK is not set, and a junk character (a character not
|
431 |
+
// part of a double-literal) is found.
|
432 |
+
// b) ALLOW_TRAILING_JUNK is set, but the string does not start with a
|
433 |
+
// double literal.
|
434 |
+
//
|
435 |
+
// infinity_symbol and nan_symbol are strings that are used to detect
|
436 |
+
// inputs that represent infinity and NaN. They can be null, in which case
|
437 |
+
// they are ignored.
|
438 |
+
// The conversion routine first reads any possible signs. Then it compares the
|
439 |
+
// following character of the input-string with the first character of
|
440 |
+
// the infinity, and nan-symbol. If either matches, the function assumes, that
|
441 |
+
// a match has been found, and expects the following input characters to match
|
442 |
+
// the remaining characters of the special-value symbol.
|
443 |
+
// This means that the following restrictions apply to special-value symbols:
|
444 |
+
// - they must not start with signs ('+', or '-'),
|
445 |
+
// - they must not have the same first character.
|
446 |
+
// - they must not start with digits.
|
447 |
+
//
|
448 |
+
// Examples:
|
449 |
+
// flags = ALLOW_HEX | ALLOW_TRAILING_JUNK,
|
450 |
+
// empty_string_value = 0.0,
|
451 |
+
// junk_string_value = NaN,
|
452 |
+
// infinity_symbol = "infinity",
|
453 |
+
// nan_symbol = "nan":
|
454 |
+
// StringToDouble("0x1234") -> 4660.0.
|
455 |
+
// StringToDouble("0x1234K") -> 4660.0.
|
456 |
+
// StringToDouble("") -> 0.0 // empty_string_value.
|
457 |
+
// StringToDouble(" ") -> NaN // junk_string_value.
|
458 |
+
// StringToDouble(" 1") -> NaN // junk_string_value.
|
459 |
+
// StringToDouble("0x") -> NaN // junk_string_value.
|
460 |
+
// StringToDouble("-123.45") -> -123.45.
|
461 |
+
// StringToDouble("--123.45") -> NaN // junk_string_value.
|
462 |
+
// StringToDouble("123e45") -> 123e45.
|
463 |
+
// StringToDouble("123E45") -> 123e45.
|
464 |
+
// StringToDouble("123e+45") -> 123e45.
|
465 |
+
// StringToDouble("123E-45") -> 123e-45.
|
466 |
+
// StringToDouble("123e") -> 123.0 // trailing junk ignored.
|
467 |
+
// StringToDouble("123e-") -> 123.0 // trailing junk ignored.
|
468 |
+
// StringToDouble("+NaN") -> NaN // NaN string literal.
|
469 |
+
// StringToDouble("-infinity") -> -inf. // infinity literal.
|
470 |
+
// StringToDouble("Infinity") -> NaN // junk_string_value.
|
471 |
+
//
|
472 |
+
// flags = ALLOW_OCTAL | ALLOW_LEADING_SPACES,
|
473 |
+
// empty_string_value = 0.0,
|
474 |
+
// junk_string_value = NaN,
|
475 |
+
// infinity_symbol = NULL,
|
476 |
+
// nan_symbol = NULL:
|
477 |
+
// StringToDouble("0x1234") -> NaN // junk_string_value.
|
478 |
+
// StringToDouble("01234") -> 668.0.
|
479 |
+
// StringToDouble("") -> 0.0 // empty_string_value.
|
480 |
+
// StringToDouble(" ") -> 0.0 // empty_string_value.
|
481 |
+
// StringToDouble(" 1") -> 1.0
|
482 |
+
// StringToDouble("0x") -> NaN // junk_string_value.
|
483 |
+
// StringToDouble("0123e45") -> NaN // junk_string_value.
|
484 |
+
// StringToDouble("01239E45") -> 1239e45.
|
485 |
+
// StringToDouble("-infinity") -> NaN // junk_string_value.
|
486 |
+
// StringToDouble("NaN") -> NaN // junk_string_value.
|
487 |
+
StringToDoubleConverter(int flags,
|
488 |
+
double empty_string_value,
|
489 |
+
double junk_string_value,
|
490 |
+
const char* infinity_symbol,
|
491 |
+
const char* nan_symbol)
|
492 |
+
: flags_(flags),
|
493 |
+
empty_string_value_(empty_string_value),
|
494 |
+
junk_string_value_(junk_string_value),
|
495 |
+
infinity_symbol_(infinity_symbol),
|
496 |
+
nan_symbol_(nan_symbol) {
|
497 |
+
}
|
498 |
+
|
499 |
+
// Performs the conversion.
|
500 |
+
// The output parameter 'processed_characters_count' is set to the number
|
501 |
+
// of characters that have been processed to read the number.
|
502 |
+
// Spaces than are processed with ALLOW_{LEADING|TRAILING}_SPACES are included
|
503 |
+
// in the 'processed_characters_count'. Trailing junk is never included.
|
504 |
+
double StringToDouble(const char* buffer,
|
505 |
+
int length,
|
506 |
+
int* processed_characters_count) const;
|
507 |
+
|
508 |
+
// Same as StringToDouble above but for 16 bit characters.
|
509 |
+
double StringToDouble(const uc16* buffer,
|
510 |
+
int length,
|
511 |
+
int* processed_characters_count) const;
|
512 |
+
|
513 |
+
// Same as StringToDouble but reads a float.
|
514 |
+
// Note that this is not equivalent to static_cast<float>(StringToDouble(...))
|
515 |
+
// due to potential double-rounding.
|
516 |
+
float StringToFloat(const char* buffer,
|
517 |
+
int length,
|
518 |
+
int* processed_characters_count) const;
|
519 |
+
|
520 |
+
// Same as StringToFloat above but for 16 bit characters.
|
521 |
+
float StringToFloat(const uc16* buffer,
|
522 |
+
int length,
|
523 |
+
int* processed_characters_count) const;
|
524 |
+
|
525 |
+
private:
|
526 |
+
const int flags_;
|
527 |
+
const double empty_string_value_;
|
528 |
+
const double junk_string_value_;
|
529 |
+
const char* const infinity_symbol_;
|
530 |
+
const char* const nan_symbol_;
|
531 |
+
|
532 |
+
template <class Iterator>
|
533 |
+
double StringToIeee(Iterator start_pointer,
|
534 |
+
int length,
|
535 |
+
bool read_as_double,
|
536 |
+
int* processed_characters_count) const;
|
537 |
+
|
538 |
+
DISALLOW_IMPLICIT_CONSTRUCTORS(StringToDoubleConverter);
|
539 |
+
};
|
540 |
+
|
541 |
+
} // namespace double_conversion
|
542 |
+
|
543 |
+
#endif // DOUBLE_CONVERSION_DOUBLE_CONVERSION_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fast-dtoa.cc
ADDED
@@ -0,0 +1,665 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2012 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include "fast-dtoa.h"
|
29 |
+
|
30 |
+
#include "cached-powers.h"
|
31 |
+
#include "diy-fp.h"
|
32 |
+
#include "ieee.h"
|
33 |
+
|
34 |
+
namespace double_conversion {
|
35 |
+
|
36 |
+
// The minimal and maximal target exponent define the range of w's binary
|
37 |
+
// exponent, where 'w' is the result of multiplying the input by a cached power
|
38 |
+
// of ten.
|
39 |
+
//
|
40 |
+
// A different range might be chosen on a different platform, to optimize digit
|
41 |
+
// generation, but a smaller range requires more powers of ten to be cached.
|
42 |
+
static const int kMinimalTargetExponent = -60;
|
43 |
+
static const int kMaximalTargetExponent = -32;
|
44 |
+
|
45 |
+
|
46 |
+
// Adjusts the last digit of the generated number, and screens out generated
|
47 |
+
// solutions that may be inaccurate. A solution may be inaccurate if it is
|
48 |
+
// outside the safe interval, or if we cannot prove that it is closer to the
|
49 |
+
// input than a neighboring representation of the same length.
|
50 |
+
//
|
51 |
+
// Input: * buffer containing the digits of too_high / 10^kappa
|
52 |
+
// * the buffer's length
|
53 |
+
// * distance_too_high_w == (too_high - w).f() * unit
|
54 |
+
// * unsafe_interval == (too_high - too_low).f() * unit
|
55 |
+
// * rest = (too_high - buffer * 10^kappa).f() * unit
|
56 |
+
// * ten_kappa = 10^kappa * unit
|
57 |
+
// * unit = the common multiplier
|
58 |
+
// Output: returns true if the buffer is guaranteed to contain the closest
|
59 |
+
// representable number to the input.
|
60 |
+
// Modifies the generated digits in the buffer to approach (round towards) w.
|
61 |
+
static bool RoundWeed(Vector<char> buffer,
|
62 |
+
int length,
|
63 |
+
uint64_t distance_too_high_w,
|
64 |
+
uint64_t unsafe_interval,
|
65 |
+
uint64_t rest,
|
66 |
+
uint64_t ten_kappa,
|
67 |
+
uint64_t unit) {
|
68 |
+
uint64_t small_distance = distance_too_high_w - unit;
|
69 |
+
uint64_t big_distance = distance_too_high_w + unit;
|
70 |
+
// Let w_low = too_high - big_distance, and
|
71 |
+
// w_high = too_high - small_distance.
|
72 |
+
// Note: w_low < w < w_high
|
73 |
+
//
|
74 |
+
// The real w (* unit) must lie somewhere inside the interval
|
75 |
+
// ]w_low; w_high[ (often written as "(w_low; w_high)")
|
76 |
+
|
77 |
+
// Basically the buffer currently contains a number in the unsafe interval
|
78 |
+
// ]too_low; too_high[ with too_low < w < too_high
|
79 |
+
//
|
80 |
+
// too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
81 |
+
// ^v 1 unit ^ ^ ^ ^
|
82 |
+
// boundary_high --------------------- . . . .
|
83 |
+
// ^v 1 unit . . . .
|
84 |
+
// - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
|
85 |
+
// . . ^ . .
|
86 |
+
// . big_distance . . .
|
87 |
+
// . . . . rest
|
88 |
+
// small_distance . . . .
|
89 |
+
// v . . . .
|
90 |
+
// w_high - - - - - - - - - - - - - - - - - - . . . .
|
91 |
+
// ^v 1 unit . . . .
|
92 |
+
// w ---------------------------------------- . . . .
|
93 |
+
// ^v 1 unit v . . .
|
94 |
+
// w_low - - - - - - - - - - - - - - - - - - - - - . . .
|
95 |
+
// . . v
|
96 |
+
// buffer --------------------------------------------------+-------+--------
|
97 |
+
// . .
|
98 |
+
// safe_interval .
|
99 |
+
// v .
|
100 |
+
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
|
101 |
+
// ^v 1 unit .
|
102 |
+
// boundary_low ------------------------- unsafe_interval
|
103 |
+
// ^v 1 unit v
|
104 |
+
// too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
105 |
+
//
|
106 |
+
//
|
107 |
+
// Note that the value of buffer could lie anywhere inside the range too_low
|
108 |
+
// to too_high.
|
109 |
+
//
|
110 |
+
// boundary_low, boundary_high and w are approximations of the real boundaries
|
111 |
+
// and v (the input number). They are guaranteed to be precise up to one unit.
|
112 |
+
// In fact the error is guaranteed to be strictly less than one unit.
|
113 |
+
//
|
114 |
+
// Anything that lies outside the unsafe interval is guaranteed not to round
|
115 |
+
// to v when read again.
|
116 |
+
// Anything that lies inside the safe interval is guaranteed to round to v
|
117 |
+
// when read again.
|
118 |
+
// If the number inside the buffer lies inside the unsafe interval but not
|
119 |
+
// inside the safe interval then we simply do not know and bail out (returning
|
120 |
+
// false).
|
121 |
+
//
|
122 |
+
// Similarly we have to take into account the imprecision of 'w' when finding
|
123 |
+
// the closest representation of 'w'. If we have two potential
|
124 |
+
// representations, and one is closer to both w_low and w_high, then we know
|
125 |
+
// it is closer to the actual value v.
|
126 |
+
//
|
127 |
+
// By generating the digits of too_high we got the largest (closest to
|
128 |
+
// too_high) buffer that is still in the unsafe interval. In the case where
|
129 |
+
// w_high < buffer < too_high we try to decrement the buffer.
|
130 |
+
// This way the buffer approaches (rounds towards) w.
|
131 |
+
// There are 3 conditions that stop the decrementation process:
|
132 |
+
// 1) the buffer is already below w_high
|
133 |
+
// 2) decrementing the buffer would make it leave the unsafe interval
|
134 |
+
// 3) decrementing the buffer would yield a number below w_high and farther
|
135 |
+
// away than the current number. In other words:
|
136 |
+
// (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
|
137 |
+
// Instead of using the buffer directly we use its distance to too_high.
|
138 |
+
// Conceptually rest ~= too_high - buffer
|
139 |
+
// We need to do the following tests in this order to avoid over- and
|
140 |
+
// underflows.
|
141 |
+
ASSERT(rest <= unsafe_interval);
|
142 |
+
while (rest < small_distance && // Negated condition 1
|
143 |
+
unsafe_interval - rest >= ten_kappa && // Negated condition 2
|
144 |
+
(rest + ten_kappa < small_distance || // buffer{-1} > w_high
|
145 |
+
small_distance - rest >= rest + ten_kappa - small_distance)) {
|
146 |
+
buffer[length - 1]--;
|
147 |
+
rest += ten_kappa;
|
148 |
+
}
|
149 |
+
|
150 |
+
// We have approached w+ as much as possible. We now test if approaching w-
|
151 |
+
// would require changing the buffer. If yes, then we have two possible
|
152 |
+
// representations close to w, but we cannot decide which one is closer.
|
153 |
+
if (rest < big_distance &&
|
154 |
+
unsafe_interval - rest >= ten_kappa &&
|
155 |
+
(rest + ten_kappa < big_distance ||
|
156 |
+
big_distance - rest > rest + ten_kappa - big_distance)) {
|
157 |
+
return false;
|
158 |
+
}
|
159 |
+
|
160 |
+
// Weeding test.
|
161 |
+
// The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
|
162 |
+
// Since too_low = too_high - unsafe_interval this is equivalent to
|
163 |
+
// [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
|
164 |
+
// Conceptually we have: rest ~= too_high - buffer
|
165 |
+
return (2 * unit <= rest) && (rest <= unsafe_interval - 4 * unit);
|
166 |
+
}
|
167 |
+
|
168 |
+
|
169 |
+
// Rounds the buffer upwards if the result is closer to v by possibly adding
|
170 |
+
// 1 to the buffer. If the precision of the calculation is not sufficient to
|
171 |
+
// round correctly, return false.
|
172 |
+
// The rounding might shift the whole buffer in which case the kappa is
|
173 |
+
// adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
|
174 |
+
//
|
175 |
+
// If 2*rest > ten_kappa then the buffer needs to be round up.
|
176 |
+
// rest can have an error of +/- 1 unit. This function accounts for the
|
177 |
+
// imprecision and returns false, if the rounding direction cannot be
|
178 |
+
// unambiguously determined.
|
179 |
+
//
|
180 |
+
// Precondition: rest < ten_kappa.
|
181 |
+
static bool RoundWeedCounted(Vector<char> buffer,
|
182 |
+
int length,
|
183 |
+
uint64_t rest,
|
184 |
+
uint64_t ten_kappa,
|
185 |
+
uint64_t unit,
|
186 |
+
int* kappa) {
|
187 |
+
ASSERT(rest < ten_kappa);
|
188 |
+
// The following tests are done in a specific order to avoid overflows. They
|
189 |
+
// will work correctly with any uint64 values of rest < ten_kappa and unit.
|
190 |
+
//
|
191 |
+
// If the unit is too big, then we don't know which way to round. For example
|
192 |
+
// a unit of 50 means that the real number lies within rest +/- 50. If
|
193 |
+
// 10^kappa == 40 then there is no way to tell which way to round.
|
194 |
+
if (unit >= ten_kappa) return false;
|
195 |
+
// Even if unit is just half the size of 10^kappa we are already completely
|
196 |
+
// lost. (And after the previous test we know that the expression will not
|
197 |
+
// over/underflow.)
|
198 |
+
if (ten_kappa - unit <= unit) return false;
|
199 |
+
// If 2 * (rest + unit) <= 10^kappa we can safely round down.
|
200 |
+
if ((ten_kappa - rest > rest) && (ten_kappa - 2 * rest >= 2 * unit)) {
|
201 |
+
return true;
|
202 |
+
}
|
203 |
+
// If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
|
204 |
+
if ((rest > unit) && (ten_kappa - (rest - unit) <= (rest - unit))) {
|
205 |
+
// Increment the last digit recursively until we find a non '9' digit.
|
206 |
+
buffer[length - 1]++;
|
207 |
+
for (int i = length - 1; i > 0; --i) {
|
208 |
+
if (buffer[i] != '0' + 10) break;
|
209 |
+
buffer[i] = '0';
|
210 |
+
buffer[i - 1]++;
|
211 |
+
}
|
212 |
+
// If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
|
213 |
+
// exception of the first digit all digits are now '0'. Simply switch the
|
214 |
+
// first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
|
215 |
+
// the power (the kappa) is increased.
|
216 |
+
if (buffer[0] == '0' + 10) {
|
217 |
+
buffer[0] = '1';
|
218 |
+
(*kappa) += 1;
|
219 |
+
}
|
220 |
+
return true;
|
221 |
+
}
|
222 |
+
return false;
|
223 |
+
}
|
224 |
+
|
225 |
+
// Returns the biggest power of ten that is less than or equal to the given
|
226 |
+
// number. We furthermore receive the maximum number of bits 'number' has.
|
227 |
+
//
|
228 |
+
// Returns power == 10^(exponent_plus_one-1) such that
|
229 |
+
// power <= number < power * 10.
|
230 |
+
// If number_bits == 0 then 0^(0-1) is returned.
|
231 |
+
// The number of bits must be <= 32.
|
232 |
+
// Precondition: number < (1 << (number_bits + 1)).
|
233 |
+
|
234 |
+
// Inspired by the method for finding an integer log base 10 from here:
|
235 |
+
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog10
|
236 |
+
static unsigned int const kSmallPowersOfTen[] =
|
237 |
+
{0, 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
|
238 |
+
1000000000};
|
239 |
+
|
240 |
+
static void BiggestPowerTen(uint32_t number,
|
241 |
+
int number_bits,
|
242 |
+
uint32_t* power,
|
243 |
+
int* exponent_plus_one) {
|
244 |
+
ASSERT(number < (1u << (number_bits + 1)));
|
245 |
+
// 1233/4096 is approximately 1/lg(10).
|
246 |
+
int exponent_plus_one_guess = ((number_bits + 1) * 1233 >> 12);
|
247 |
+
// We increment to skip over the first entry in the kPowersOf10 table.
|
248 |
+
// Note: kPowersOf10[i] == 10^(i-1).
|
249 |
+
exponent_plus_one_guess++;
|
250 |
+
// We don't have any guarantees that 2^number_bits <= number.
|
251 |
+
if (number < kSmallPowersOfTen[exponent_plus_one_guess]) {
|
252 |
+
exponent_plus_one_guess--;
|
253 |
+
}
|
254 |
+
*power = kSmallPowersOfTen[exponent_plus_one_guess];
|
255 |
+
*exponent_plus_one = exponent_plus_one_guess;
|
256 |
+
}
|
257 |
+
|
258 |
+
// Generates the digits of input number w.
|
259 |
+
// w is a floating-point number (DiyFp), consisting of a significand and an
|
260 |
+
// exponent. Its exponent is bounded by kMinimalTargetExponent and
|
261 |
+
// kMaximalTargetExponent.
|
262 |
+
// Hence -60 <= w.e() <= -32.
|
263 |
+
//
|
264 |
+
// Returns false if it fails, in which case the generated digits in the buffer
|
265 |
+
// should not be used.
|
266 |
+
// Preconditions:
|
267 |
+
// * low, w and high are correct up to 1 ulp (unit in the last place). That
|
268 |
+
// is, their error must be less than a unit of their last digits.
|
269 |
+
// * low.e() == w.e() == high.e()
|
270 |
+
// * low < w < high, and taking into account their error: low~ <= high~
|
271 |
+
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
|
272 |
+
// Postconditions: returns false if procedure fails.
|
273 |
+
// otherwise:
|
274 |
+
// * buffer is not null-terminated, but len contains the number of digits.
|
275 |
+
// * buffer contains the shortest possible decimal digit-sequence
|
276 |
+
// such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
|
277 |
+
// correct values of low and high (without their error).
|
278 |
+
// * if more than one decimal representation gives the minimal number of
|
279 |
+
// decimal digits then the one closest to W (where W is the correct value
|
280 |
+
// of w) is chosen.
|
281 |
+
// Remark: this procedure takes into account the imprecision of its input
|
282 |
+
// numbers. If the precision is not enough to guarantee all the postconditions
|
283 |
+
// then false is returned. This usually happens rarely (~0.5%).
|
284 |
+
//
|
285 |
+
// Say, for the sake of example, that
|
286 |
+
// w.e() == -48, and w.f() == 0x1234567890abcdef
|
287 |
+
// w's value can be computed by w.f() * 2^w.e()
|
288 |
+
// We can obtain w's integral digits by simply shifting w.f() by -w.e().
|
289 |
+
// -> w's integral part is 0x1234
|
290 |
+
// w's fractional part is therefore 0x567890abcdef.
|
291 |
+
// Printing w's integral part is easy (simply print 0x1234 in decimal).
|
292 |
+
// In order to print its fraction we repeatedly multiply the fraction by 10 and
|
293 |
+
// get each digit. Example the first digit after the point would be computed by
|
294 |
+
// (0x567890abcdef * 10) >> 48. -> 3
|
295 |
+
// The whole thing becomes slightly more complicated because we want to stop
|
296 |
+
// once we have enough digits. That is, once the digits inside the buffer
|
297 |
+
// represent 'w' we can stop. Everything inside the interval low - high
|
298 |
+
// represents w. However we have to pay attention to low, high and w's
|
299 |
+
// imprecision.
|
300 |
+
static bool DigitGen(DiyFp low,
|
301 |
+
DiyFp w,
|
302 |
+
DiyFp high,
|
303 |
+
Vector<char> buffer,
|
304 |
+
int* length,
|
305 |
+
int* kappa) {
|
306 |
+
ASSERT(low.e() == w.e() && w.e() == high.e());
|
307 |
+
ASSERT(low.f() + 1 <= high.f() - 1);
|
308 |
+
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
309 |
+
// low, w and high are imprecise, but by less than one ulp (unit in the last
|
310 |
+
// place).
|
311 |
+
// If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
|
312 |
+
// the new numbers are outside of the interval we want the final
|
313 |
+
// representation to lie in.
|
314 |
+
// Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
|
315 |
+
// numbers that are certain to lie in the interval. We will use this fact
|
316 |
+
// later on.
|
317 |
+
// We will now start by generating the digits within the uncertain
|
318 |
+
// interval. Later we will weed out representations that lie outside the safe
|
319 |
+
// interval and thus _might_ lie outside the correct interval.
|
320 |
+
uint64_t unit = 1;
|
321 |
+
DiyFp too_low = DiyFp(low.f() - unit, low.e());
|
322 |
+
DiyFp too_high = DiyFp(high.f() + unit, high.e());
|
323 |
+
// too_low and too_high are guaranteed to lie outside the interval we want the
|
324 |
+
// generated number in.
|
325 |
+
DiyFp unsafe_interval = DiyFp::Minus(too_high, too_low);
|
326 |
+
// We now cut the input number into two parts: the integral digits and the
|
327 |
+
// fractionals. We will not write any decimal separator though, but adapt
|
328 |
+
// kappa instead.
|
329 |
+
// Reminder: we are currently computing the digits (stored inside the buffer)
|
330 |
+
// such that: too_low < buffer * 10^kappa < too_high
|
331 |
+
// We use too_high for the digit_generation and stop as soon as possible.
|
332 |
+
// If we stop early we effectively round down.
|
333 |
+
DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
|
334 |
+
// Division by one is a shift.
|
335 |
+
uint32_t integrals = static_cast<uint32_t>(too_high.f() >> -one.e());
|
336 |
+
// Modulo by one is an and.
|
337 |
+
uint64_t fractionals = too_high.f() & (one.f() - 1);
|
338 |
+
uint32_t divisor;
|
339 |
+
int divisor_exponent_plus_one;
|
340 |
+
BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
|
341 |
+
&divisor, &divisor_exponent_plus_one);
|
342 |
+
*kappa = divisor_exponent_plus_one;
|
343 |
+
*length = 0;
|
344 |
+
// Loop invariant: buffer = too_high / 10^kappa (integer division)
|
345 |
+
// The invariant holds for the first iteration: kappa has been initialized
|
346 |
+
// with the divisor exponent + 1. And the divisor is the biggest power of ten
|
347 |
+
// that is smaller than integrals.
|
348 |
+
while (*kappa > 0) {
|
349 |
+
int digit = integrals / divisor;
|
350 |
+
ASSERT(digit <= 9);
|
351 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
352 |
+
(*length)++;
|
353 |
+
integrals %= divisor;
|
354 |
+
(*kappa)--;
|
355 |
+
// Note that kappa now equals the exponent of the divisor and that the
|
356 |
+
// invariant thus holds again.
|
357 |
+
uint64_t rest =
|
358 |
+
(static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
|
359 |
+
// Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e())
|
360 |
+
// Reminder: unsafe_interval.e() == one.e()
|
361 |
+
if (rest < unsafe_interval.f()) {
|
362 |
+
// Rounding down (by not emitting the remaining digits) yields a number
|
363 |
+
// that lies within the unsafe interval.
|
364 |
+
return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f(),
|
365 |
+
unsafe_interval.f(), rest,
|
366 |
+
static_cast<uint64_t>(divisor) << -one.e(), unit);
|
367 |
+
}
|
368 |
+
divisor /= 10;
|
369 |
+
}
|
370 |
+
|
371 |
+
// The integrals have been generated. We are at the point of the decimal
|
372 |
+
// separator. In the following loop we simply multiply the remaining digits by
|
373 |
+
// 10 and divide by one. We just need to pay attention to multiply associated
|
374 |
+
// data (like the interval or 'unit'), too.
|
375 |
+
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
376 |
+
// and thus one.e >= -60.
|
377 |
+
ASSERT(one.e() >= -60);
|
378 |
+
ASSERT(fractionals < one.f());
|
379 |
+
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
380 |
+
for (;;) {
|
381 |
+
fractionals *= 10;
|
382 |
+
unit *= 10;
|
383 |
+
unsafe_interval.set_f(unsafe_interval.f() * 10);
|
384 |
+
// Integer division by one.
|
385 |
+
int digit = static_cast<int>(fractionals >> -one.e());
|
386 |
+
ASSERT(digit <= 9);
|
387 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
388 |
+
(*length)++;
|
389 |
+
fractionals &= one.f() - 1; // Modulo by one.
|
390 |
+
(*kappa)--;
|
391 |
+
if (fractionals < unsafe_interval.f()) {
|
392 |
+
return RoundWeed(buffer, *length, DiyFp::Minus(too_high, w).f() * unit,
|
393 |
+
unsafe_interval.f(), fractionals, one.f(), unit);
|
394 |
+
}
|
395 |
+
}
|
396 |
+
}
|
397 |
+
|
398 |
+
|
399 |
+
|
400 |
+
// Generates (at most) requested_digits digits of input number w.
|
401 |
+
// w is a floating-point number (DiyFp), consisting of a significand and an
|
402 |
+
// exponent. Its exponent is bounded by kMinimalTargetExponent and
|
403 |
+
// kMaximalTargetExponent.
|
404 |
+
// Hence -60 <= w.e() <= -32.
|
405 |
+
//
|
406 |
+
// Returns false if it fails, in which case the generated digits in the buffer
|
407 |
+
// should not be used.
|
408 |
+
// Preconditions:
|
409 |
+
// * w is correct up to 1 ulp (unit in the last place). That
|
410 |
+
// is, its error must be strictly less than a unit of its last digit.
|
411 |
+
// * kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
|
412 |
+
//
|
413 |
+
// Postconditions: returns false if procedure fails.
|
414 |
+
// otherwise:
|
415 |
+
// * buffer is not null-terminated, but length contains the number of
|
416 |
+
// digits.
|
417 |
+
// * the representation in buffer is the most precise representation of
|
418 |
+
// requested_digits digits.
|
419 |
+
// * buffer contains at most requested_digits digits of w. If there are less
|
420 |
+
// than requested_digits digits then some trailing '0's have been removed.
|
421 |
+
// * kappa is such that
|
422 |
+
// w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
|
423 |
+
//
|
424 |
+
// Remark: This procedure takes into account the imprecision of its input
|
425 |
+
// numbers. If the precision is not enough to guarantee all the postconditions
|
426 |
+
// then false is returned. This usually happens rarely, but the failure-rate
|
427 |
+
// increases with higher requested_digits.
|
428 |
+
static bool DigitGenCounted(DiyFp w,
|
429 |
+
int requested_digits,
|
430 |
+
Vector<char> buffer,
|
431 |
+
int* length,
|
432 |
+
int* kappa) {
|
433 |
+
ASSERT(kMinimalTargetExponent <= w.e() && w.e() <= kMaximalTargetExponent);
|
434 |
+
ASSERT(kMinimalTargetExponent >= -60);
|
435 |
+
ASSERT(kMaximalTargetExponent <= -32);
|
436 |
+
// w is assumed to have an error less than 1 unit. Whenever w is scaled we
|
437 |
+
// also scale its error.
|
438 |
+
uint64_t w_error = 1;
|
439 |
+
// We cut the input number into two parts: the integral digits and the
|
440 |
+
// fractional digits. We don't emit any decimal separator, but adapt kappa
|
441 |
+
// instead. Example: instead of writing "1.2" we put "12" into the buffer and
|
442 |
+
// increase kappa by 1.
|
443 |
+
DiyFp one = DiyFp(static_cast<uint64_t>(1) << -w.e(), w.e());
|
444 |
+
// Division by one is a shift.
|
445 |
+
uint32_t integrals = static_cast<uint32_t>(w.f() >> -one.e());
|
446 |
+
// Modulo by one is an and.
|
447 |
+
uint64_t fractionals = w.f() & (one.f() - 1);
|
448 |
+
uint32_t divisor;
|
449 |
+
int divisor_exponent_plus_one;
|
450 |
+
BiggestPowerTen(integrals, DiyFp::kSignificandSize - (-one.e()),
|
451 |
+
&divisor, &divisor_exponent_plus_one);
|
452 |
+
*kappa = divisor_exponent_plus_one;
|
453 |
+
*length = 0;
|
454 |
+
|
455 |
+
// Loop invariant: buffer = w / 10^kappa (integer division)
|
456 |
+
// The invariant holds for the first iteration: kappa has been initialized
|
457 |
+
// with the divisor exponent + 1. And the divisor is the biggest power of ten
|
458 |
+
// that is smaller than 'integrals'.
|
459 |
+
while (*kappa > 0) {
|
460 |
+
int digit = integrals / divisor;
|
461 |
+
ASSERT(digit <= 9);
|
462 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
463 |
+
(*length)++;
|
464 |
+
requested_digits--;
|
465 |
+
integrals %= divisor;
|
466 |
+
(*kappa)--;
|
467 |
+
// Note that kappa now equals the exponent of the divisor and that the
|
468 |
+
// invariant thus holds again.
|
469 |
+
if (requested_digits == 0) break;
|
470 |
+
divisor /= 10;
|
471 |
+
}
|
472 |
+
|
473 |
+
if (requested_digits == 0) {
|
474 |
+
uint64_t rest =
|
475 |
+
(static_cast<uint64_t>(integrals) << -one.e()) + fractionals;
|
476 |
+
return RoundWeedCounted(buffer, *length, rest,
|
477 |
+
static_cast<uint64_t>(divisor) << -one.e(), w_error,
|
478 |
+
kappa);
|
479 |
+
}
|
480 |
+
|
481 |
+
// The integrals have been generated. We are at the point of the decimal
|
482 |
+
// separator. In the following loop we simply multiply the remaining digits by
|
483 |
+
// 10 and divide by one. We just need to pay attention to multiply associated
|
484 |
+
// data (the 'unit'), too.
|
485 |
+
// Note that the multiplication by 10 does not overflow, because w.e >= -60
|
486 |
+
// and thus one.e >= -60.
|
487 |
+
ASSERT(one.e() >= -60);
|
488 |
+
ASSERT(fractionals < one.f());
|
489 |
+
ASSERT(UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF) / 10 >= one.f());
|
490 |
+
while (requested_digits > 0 && fractionals > w_error) {
|
491 |
+
fractionals *= 10;
|
492 |
+
w_error *= 10;
|
493 |
+
// Integer division by one.
|
494 |
+
int digit = static_cast<int>(fractionals >> -one.e());
|
495 |
+
ASSERT(digit <= 9);
|
496 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
497 |
+
(*length)++;
|
498 |
+
requested_digits--;
|
499 |
+
fractionals &= one.f() - 1; // Modulo by one.
|
500 |
+
(*kappa)--;
|
501 |
+
}
|
502 |
+
if (requested_digits != 0) return false;
|
503 |
+
return RoundWeedCounted(buffer, *length, fractionals, one.f(), w_error,
|
504 |
+
kappa);
|
505 |
+
}
|
506 |
+
|
507 |
+
|
508 |
+
// Provides a decimal representation of v.
|
509 |
+
// Returns true if it succeeds, otherwise the result cannot be trusted.
|
510 |
+
// There will be *length digits inside the buffer (not null-terminated).
|
511 |
+
// If the function returns true then
|
512 |
+
// v == (double) (buffer * 10^decimal_exponent).
|
513 |
+
// The digits in the buffer are the shortest representation possible: no
|
514 |
+
// 0.09999999999999999 instead of 0.1. The shorter representation will even be
|
515 |
+
// chosen even if the longer one would be closer to v.
|
516 |
+
// The last digit will be closest to the actual v. That is, even if several
|
517 |
+
// digits might correctly yield 'v' when read again, the closest will be
|
518 |
+
// computed.
|
519 |
+
static bool Grisu3(double v,
|
520 |
+
FastDtoaMode mode,
|
521 |
+
Vector<char> buffer,
|
522 |
+
int* length,
|
523 |
+
int* decimal_exponent) {
|
524 |
+
DiyFp w = Double(v).AsNormalizedDiyFp();
|
525 |
+
// boundary_minus and boundary_plus are the boundaries between v and its
|
526 |
+
// closest floating-point neighbors. Any number strictly between
|
527 |
+
// boundary_minus and boundary_plus will round to v when convert to a double.
|
528 |
+
// Grisu3 will never output representations that lie exactly on a boundary.
|
529 |
+
DiyFp boundary_minus, boundary_plus;
|
530 |
+
if (mode == FAST_DTOA_SHORTEST) {
|
531 |
+
Double(v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
532 |
+
} else {
|
533 |
+
ASSERT(mode == FAST_DTOA_SHORTEST_SINGLE);
|
534 |
+
float single_v = static_cast<float>(v);
|
535 |
+
Single(single_v).NormalizedBoundaries(&boundary_minus, &boundary_plus);
|
536 |
+
}
|
537 |
+
ASSERT(boundary_plus.e() == w.e());
|
538 |
+
DiyFp ten_mk; // Cached power of ten: 10^-k
|
539 |
+
int mk; // -k
|
540 |
+
int ten_mk_minimal_binary_exponent =
|
541 |
+
kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
542 |
+
int ten_mk_maximal_binary_exponent =
|
543 |
+
kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
544 |
+
PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
545 |
+
ten_mk_minimal_binary_exponent,
|
546 |
+
ten_mk_maximal_binary_exponent,
|
547 |
+
&ten_mk, &mk);
|
548 |
+
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
549 |
+
DiyFp::kSignificandSize) &&
|
550 |
+
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
551 |
+
DiyFp::kSignificandSize));
|
552 |
+
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
|
553 |
+
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
|
554 |
+
|
555 |
+
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
|
556 |
+
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
|
557 |
+
// off by a small amount.
|
558 |
+
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
|
559 |
+
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
560 |
+
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
561 |
+
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
562 |
+
ASSERT(scaled_w.e() ==
|
563 |
+
boundary_plus.e() + ten_mk.e() + DiyFp::kSignificandSize);
|
564 |
+
// In theory it would be possible to avoid some recomputations by computing
|
565 |
+
// the difference between w and boundary_minus/plus (a power of 2) and to
|
566 |
+
// compute scaled_boundary_minus/plus by subtracting/adding from
|
567 |
+
// scaled_w. However the code becomes much less readable and the speed
|
568 |
+
// enhancements are not terriffic.
|
569 |
+
DiyFp scaled_boundary_minus = DiyFp::Times(boundary_minus, ten_mk);
|
570 |
+
DiyFp scaled_boundary_plus = DiyFp::Times(boundary_plus, ten_mk);
|
571 |
+
|
572 |
+
// DigitGen will generate the digits of scaled_w. Therefore we have
|
573 |
+
// v == (double) (scaled_w * 10^-mk).
|
574 |
+
// Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
|
575 |
+
// integer than it will be updated. For instance if scaled_w == 1.23 then
|
576 |
+
// the buffer will be filled with "123" und the decimal_exponent will be
|
577 |
+
// decreased by 2.
|
578 |
+
int kappa;
|
579 |
+
bool result = DigitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus,
|
580 |
+
buffer, length, &kappa);
|
581 |
+
*decimal_exponent = -mk + kappa;
|
582 |
+
return result;
|
583 |
+
}
|
584 |
+
|
585 |
+
|
586 |
+
// The "counted" version of grisu3 (see above) only generates requested_digits
|
587 |
+
// number of digits. This version does not generate the shortest representation,
|
588 |
+
// and with enough requested digits 0.1 will at some point print as 0.9999999...
|
589 |
+
// Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
|
590 |
+
// therefore the rounding strategy for halfway cases is irrelevant.
|
591 |
+
static bool Grisu3Counted(double v,
|
592 |
+
int requested_digits,
|
593 |
+
Vector<char> buffer,
|
594 |
+
int* length,
|
595 |
+
int* decimal_exponent) {
|
596 |
+
DiyFp w = Double(v).AsNormalizedDiyFp();
|
597 |
+
DiyFp ten_mk; // Cached power of ten: 10^-k
|
598 |
+
int mk; // -k
|
599 |
+
int ten_mk_minimal_binary_exponent =
|
600 |
+
kMinimalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
601 |
+
int ten_mk_maximal_binary_exponent =
|
602 |
+
kMaximalTargetExponent - (w.e() + DiyFp::kSignificandSize);
|
603 |
+
PowersOfTenCache::GetCachedPowerForBinaryExponentRange(
|
604 |
+
ten_mk_minimal_binary_exponent,
|
605 |
+
ten_mk_maximal_binary_exponent,
|
606 |
+
&ten_mk, &mk);
|
607 |
+
ASSERT((kMinimalTargetExponent <= w.e() + ten_mk.e() +
|
608 |
+
DiyFp::kSignificandSize) &&
|
609 |
+
(kMaximalTargetExponent >= w.e() + ten_mk.e() +
|
610 |
+
DiyFp::kSignificandSize));
|
611 |
+
// Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
|
612 |
+
// 64 bit significand and ten_mk is thus only precise up to 64 bits.
|
613 |
+
|
614 |
+
// The DiyFp::Times procedure rounds its result, and ten_mk is approximated
|
615 |
+
// too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
|
616 |
+
// off by a small amount.
|
617 |
+
// In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
|
618 |
+
// In other words: let f = scaled_w.f() and e = scaled_w.e(), then
|
619 |
+
// (f-1) * 2^e < w*10^k < (f+1) * 2^e
|
620 |
+
DiyFp scaled_w = DiyFp::Times(w, ten_mk);
|
621 |
+
|
622 |
+
// We now have (double) (scaled_w * 10^-mk).
|
623 |
+
// DigitGen will generate the first requested_digits digits of scaled_w and
|
624 |
+
// return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
|
625 |
+
// will not always be exactly the same since DigitGenCounted only produces a
|
626 |
+
// limited number of digits.)
|
627 |
+
int kappa;
|
628 |
+
bool result = DigitGenCounted(scaled_w, requested_digits,
|
629 |
+
buffer, length, &kappa);
|
630 |
+
*decimal_exponent = -mk + kappa;
|
631 |
+
return result;
|
632 |
+
}
|
633 |
+
|
634 |
+
|
635 |
+
bool FastDtoa(double v,
|
636 |
+
FastDtoaMode mode,
|
637 |
+
int requested_digits,
|
638 |
+
Vector<char> buffer,
|
639 |
+
int* length,
|
640 |
+
int* decimal_point) {
|
641 |
+
ASSERT(v > 0);
|
642 |
+
ASSERT(!Double(v).IsSpecial());
|
643 |
+
|
644 |
+
bool result = false;
|
645 |
+
int decimal_exponent = 0;
|
646 |
+
switch (mode) {
|
647 |
+
case FAST_DTOA_SHORTEST:
|
648 |
+
case FAST_DTOA_SHORTEST_SINGLE:
|
649 |
+
result = Grisu3(v, mode, buffer, length, &decimal_exponent);
|
650 |
+
break;
|
651 |
+
case FAST_DTOA_PRECISION:
|
652 |
+
result = Grisu3Counted(v, requested_digits,
|
653 |
+
buffer, length, &decimal_exponent);
|
654 |
+
break;
|
655 |
+
default:
|
656 |
+
UNREACHABLE();
|
657 |
+
}
|
658 |
+
if (result) {
|
659 |
+
*decimal_point = *length + decimal_exponent;
|
660 |
+
buffer[*length] = '\0';
|
661 |
+
}
|
662 |
+
return result;
|
663 |
+
}
|
664 |
+
|
665 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fast-dtoa.h
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_FAST_DTOA_H_
|
29 |
+
#define DOUBLE_CONVERSION_FAST_DTOA_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
enum FastDtoaMode {
|
36 |
+
// Computes the shortest representation of the given input. The returned
|
37 |
+
// result will be the most accurate number of this length. Longer
|
38 |
+
// representations might be more accurate.
|
39 |
+
FAST_DTOA_SHORTEST,
|
40 |
+
// Same as FAST_DTOA_SHORTEST but for single-precision floats.
|
41 |
+
FAST_DTOA_SHORTEST_SINGLE,
|
42 |
+
// Computes a representation where the precision (number of digits) is
|
43 |
+
// given as input. The precision is independent of the decimal point.
|
44 |
+
FAST_DTOA_PRECISION
|
45 |
+
};
|
46 |
+
|
47 |
+
// FastDtoa will produce at most kFastDtoaMaximalLength digits. This does not
|
48 |
+
// include the terminating '\0' character.
|
49 |
+
static const int kFastDtoaMaximalLength = 17;
|
50 |
+
// Same for single-precision numbers.
|
51 |
+
static const int kFastDtoaMaximalSingleLength = 9;
|
52 |
+
|
53 |
+
// Provides a decimal representation of v.
|
54 |
+
// The result should be interpreted as buffer * 10^(point - length).
|
55 |
+
//
|
56 |
+
// Precondition:
|
57 |
+
// * v must be a strictly positive finite double.
|
58 |
+
//
|
59 |
+
// Returns true if it succeeds, otherwise the result can not be trusted.
|
60 |
+
// There will be *length digits inside the buffer followed by a null terminator.
|
61 |
+
// If the function returns true and mode equals
|
62 |
+
// - FAST_DTOA_SHORTEST, then
|
63 |
+
// the parameter requested_digits is ignored.
|
64 |
+
// The result satisfies
|
65 |
+
// v == (double) (buffer * 10^(point - length)).
|
66 |
+
// The digits in the buffer are the shortest representation possible. E.g.
|
67 |
+
// if 0.099999999999 and 0.1 represent the same double then "1" is returned
|
68 |
+
// with point = 0.
|
69 |
+
// The last digit will be closest to the actual v. That is, even if several
|
70 |
+
// digits might correctly yield 'v' when read again, the buffer will contain
|
71 |
+
// the one closest to v.
|
72 |
+
// - FAST_DTOA_PRECISION, then
|
73 |
+
// the buffer contains requested_digits digits.
|
74 |
+
// the difference v - (buffer * 10^(point-length)) is closest to zero for
|
75 |
+
// all possible representations of requested_digits digits.
|
76 |
+
// If there are two values that are equally close, then FastDtoa returns
|
77 |
+
// false.
|
78 |
+
// For both modes the buffer must be large enough to hold the result.
|
79 |
+
bool FastDtoa(double d,
|
80 |
+
FastDtoaMode mode,
|
81 |
+
int requested_digits,
|
82 |
+
Vector<char> buffer,
|
83 |
+
int* length,
|
84 |
+
int* decimal_point);
|
85 |
+
|
86 |
+
} // namespace double_conversion
|
87 |
+
|
88 |
+
#endif // DOUBLE_CONVERSION_FAST_DTOA_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fixed-dtoa.cc
ADDED
@@ -0,0 +1,405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include <math.h>
|
29 |
+
|
30 |
+
#include "fixed-dtoa.h"
|
31 |
+
#include "ieee.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
// Represents a 128bit type. This class should be replaced by a native type on
|
36 |
+
// platforms that support 128bit integers.
|
37 |
+
class UInt128 {
|
38 |
+
public:
|
39 |
+
UInt128() : high_bits_(0), low_bits_(0) { }
|
40 |
+
UInt128(uint64_t high, uint64_t low) : high_bits_(high), low_bits_(low) { }
|
41 |
+
|
42 |
+
void Multiply(uint32_t multiplicand) {
|
43 |
+
uint64_t accumulator;
|
44 |
+
|
45 |
+
accumulator = (low_bits_ & kMask32) * multiplicand;
|
46 |
+
uint32_t part = static_cast<uint32_t>(accumulator & kMask32);
|
47 |
+
accumulator >>= 32;
|
48 |
+
accumulator = accumulator + (low_bits_ >> 32) * multiplicand;
|
49 |
+
low_bits_ = (accumulator << 32) + part;
|
50 |
+
accumulator >>= 32;
|
51 |
+
accumulator = accumulator + (high_bits_ & kMask32) * multiplicand;
|
52 |
+
part = static_cast<uint32_t>(accumulator & kMask32);
|
53 |
+
accumulator >>= 32;
|
54 |
+
accumulator = accumulator + (high_bits_ >> 32) * multiplicand;
|
55 |
+
high_bits_ = (accumulator << 32) + part;
|
56 |
+
ASSERT((accumulator >> 32) == 0);
|
57 |
+
}
|
58 |
+
|
59 |
+
void Shift(int shift_amount) {
|
60 |
+
ASSERT(-64 <= shift_amount && shift_amount <= 64);
|
61 |
+
if (shift_amount == 0) {
|
62 |
+
return;
|
63 |
+
} else if (shift_amount == -64) {
|
64 |
+
high_bits_ = low_bits_;
|
65 |
+
low_bits_ = 0;
|
66 |
+
} else if (shift_amount == 64) {
|
67 |
+
low_bits_ = high_bits_;
|
68 |
+
high_bits_ = 0;
|
69 |
+
} else if (shift_amount <= 0) {
|
70 |
+
high_bits_ <<= -shift_amount;
|
71 |
+
high_bits_ += low_bits_ >> (64 + shift_amount);
|
72 |
+
low_bits_ <<= -shift_amount;
|
73 |
+
} else {
|
74 |
+
low_bits_ >>= shift_amount;
|
75 |
+
low_bits_ += high_bits_ << (64 - shift_amount);
|
76 |
+
high_bits_ >>= shift_amount;
|
77 |
+
}
|
78 |
+
}
|
79 |
+
|
80 |
+
// Modifies *this to *this MOD (2^power).
|
81 |
+
// Returns *this DIV (2^power).
|
82 |
+
int DivModPowerOf2(int power) {
|
83 |
+
if (power >= 64) {
|
84 |
+
int result = static_cast<int>(high_bits_ >> (power - 64));
|
85 |
+
high_bits_ -= static_cast<uint64_t>(result) << (power - 64);
|
86 |
+
return result;
|
87 |
+
} else {
|
88 |
+
uint64_t part_low = low_bits_ >> power;
|
89 |
+
uint64_t part_high = high_bits_ << (64 - power);
|
90 |
+
int result = static_cast<int>(part_low + part_high);
|
91 |
+
high_bits_ = 0;
|
92 |
+
low_bits_ -= part_low << power;
|
93 |
+
return result;
|
94 |
+
}
|
95 |
+
}
|
96 |
+
|
97 |
+
bool IsZero() const {
|
98 |
+
return high_bits_ == 0 && low_bits_ == 0;
|
99 |
+
}
|
100 |
+
|
101 |
+
int BitAt(int position) const {
|
102 |
+
if (position >= 64) {
|
103 |
+
return static_cast<int>(high_bits_ >> (position - 64)) & 1;
|
104 |
+
} else {
|
105 |
+
return static_cast<int>(low_bits_ >> position) & 1;
|
106 |
+
}
|
107 |
+
}
|
108 |
+
|
109 |
+
private:
|
110 |
+
static const uint64_t kMask32 = 0xFFFFFFFF;
|
111 |
+
// Value == (high_bits_ << 64) + low_bits_
|
112 |
+
uint64_t high_bits_;
|
113 |
+
uint64_t low_bits_;
|
114 |
+
};
|
115 |
+
|
116 |
+
|
117 |
+
static const int kDoubleSignificandSize = 53; // Includes the hidden bit.
|
118 |
+
|
119 |
+
|
120 |
+
static void FillDigits32FixedLength(uint32_t number, int requested_length,
|
121 |
+
Vector<char> buffer, int* length) {
|
122 |
+
for (int i = requested_length - 1; i >= 0; --i) {
|
123 |
+
buffer[(*length) + i] = '0' + number % 10;
|
124 |
+
number /= 10;
|
125 |
+
}
|
126 |
+
*length += requested_length;
|
127 |
+
}
|
128 |
+
|
129 |
+
|
130 |
+
static void FillDigits32(uint32_t number, Vector<char> buffer, int* length) {
|
131 |
+
int number_length = 0;
|
132 |
+
// We fill the digits in reverse order and exchange them afterwards.
|
133 |
+
while (number != 0) {
|
134 |
+
int digit = number % 10;
|
135 |
+
number /= 10;
|
136 |
+
buffer[(*length) + number_length] = static_cast<char>('0' + digit);
|
137 |
+
number_length++;
|
138 |
+
}
|
139 |
+
// Exchange the digits.
|
140 |
+
int i = *length;
|
141 |
+
int j = *length + number_length - 1;
|
142 |
+
while (i < j) {
|
143 |
+
char tmp = buffer[i];
|
144 |
+
buffer[i] = buffer[j];
|
145 |
+
buffer[j] = tmp;
|
146 |
+
i++;
|
147 |
+
j--;
|
148 |
+
}
|
149 |
+
*length += number_length;
|
150 |
+
}
|
151 |
+
|
152 |
+
|
153 |
+
static void FillDigits64FixedLength(uint64_t number,
|
154 |
+
Vector<char> buffer, int* length) {
|
155 |
+
const uint32_t kTen7 = 10000000;
|
156 |
+
// For efficiency cut the number into 3 uint32_t parts, and print those.
|
157 |
+
uint32_t part2 = static_cast<uint32_t>(number % kTen7);
|
158 |
+
number /= kTen7;
|
159 |
+
uint32_t part1 = static_cast<uint32_t>(number % kTen7);
|
160 |
+
uint32_t part0 = static_cast<uint32_t>(number / kTen7);
|
161 |
+
|
162 |
+
FillDigits32FixedLength(part0, 3, buffer, length);
|
163 |
+
FillDigits32FixedLength(part1, 7, buffer, length);
|
164 |
+
FillDigits32FixedLength(part2, 7, buffer, length);
|
165 |
+
}
|
166 |
+
|
167 |
+
|
168 |
+
static void FillDigits64(uint64_t number, Vector<char> buffer, int* length) {
|
169 |
+
const uint32_t kTen7 = 10000000;
|
170 |
+
// For efficiency cut the number into 3 uint32_t parts, and print those.
|
171 |
+
uint32_t part2 = static_cast<uint32_t>(number % kTen7);
|
172 |
+
number /= kTen7;
|
173 |
+
uint32_t part1 = static_cast<uint32_t>(number % kTen7);
|
174 |
+
uint32_t part0 = static_cast<uint32_t>(number / kTen7);
|
175 |
+
|
176 |
+
if (part0 != 0) {
|
177 |
+
FillDigits32(part0, buffer, length);
|
178 |
+
FillDigits32FixedLength(part1, 7, buffer, length);
|
179 |
+
FillDigits32FixedLength(part2, 7, buffer, length);
|
180 |
+
} else if (part1 != 0) {
|
181 |
+
FillDigits32(part1, buffer, length);
|
182 |
+
FillDigits32FixedLength(part2, 7, buffer, length);
|
183 |
+
} else {
|
184 |
+
FillDigits32(part2, buffer, length);
|
185 |
+
}
|
186 |
+
}
|
187 |
+
|
188 |
+
|
189 |
+
static void RoundUp(Vector<char> buffer, int* length, int* decimal_point) {
|
190 |
+
// An empty buffer represents 0.
|
191 |
+
if (*length == 0) {
|
192 |
+
buffer[0] = '1';
|
193 |
+
*decimal_point = 1;
|
194 |
+
*length = 1;
|
195 |
+
return;
|
196 |
+
}
|
197 |
+
// Round the last digit until we either have a digit that was not '9' or until
|
198 |
+
// we reached the first digit.
|
199 |
+
buffer[(*length) - 1]++;
|
200 |
+
for (int i = (*length) - 1; i > 0; --i) {
|
201 |
+
if (buffer[i] != '0' + 10) {
|
202 |
+
return;
|
203 |
+
}
|
204 |
+
buffer[i] = '0';
|
205 |
+
buffer[i - 1]++;
|
206 |
+
}
|
207 |
+
// If the first digit is now '0' + 10, we would need to set it to '0' and add
|
208 |
+
// a '1' in front. However we reach the first digit only if all following
|
209 |
+
// digits had been '9' before rounding up. Now all trailing digits are '0' and
|
210 |
+
// we simply switch the first digit to '1' and update the decimal-point
|
211 |
+
// (indicating that the point is now one digit to the right).
|
212 |
+
if (buffer[0] == '0' + 10) {
|
213 |
+
buffer[0] = '1';
|
214 |
+
(*decimal_point)++;
|
215 |
+
}
|
216 |
+
}
|
217 |
+
|
218 |
+
|
219 |
+
// The given fractionals number represents a fixed-point number with binary
|
220 |
+
// point at bit (-exponent).
|
221 |
+
// Preconditions:
|
222 |
+
// -128 <= exponent <= 0.
|
223 |
+
// 0 <= fractionals * 2^exponent < 1
|
224 |
+
// The buffer holds the result.
|
225 |
+
// The function will round its result. During the rounding-process digits not
|
226 |
+
// generated by this function might be updated, and the decimal-point variable
|
227 |
+
// might be updated. If this function generates the digits 99 and the buffer
|
228 |
+
// already contained "199" (thus yielding a buffer of "19999") then a
|
229 |
+
// rounding-up will change the contents of the buffer to "20000".
|
230 |
+
static void FillFractionals(uint64_t fractionals, int exponent,
|
231 |
+
int fractional_count, Vector<char> buffer,
|
232 |
+
int* length, int* decimal_point) {
|
233 |
+
ASSERT(-128 <= exponent && exponent <= 0);
|
234 |
+
// 'fractionals' is a fixed-point number, with binary point at bit
|
235 |
+
// (-exponent). Inside the function the non-converted remainder of fractionals
|
236 |
+
// is a fixed-point number, with binary point at bit 'point'.
|
237 |
+
if (-exponent <= 64) {
|
238 |
+
// One 64 bit number is sufficient.
|
239 |
+
ASSERT(fractionals >> 56 == 0);
|
240 |
+
int point = -exponent;
|
241 |
+
for (int i = 0; i < fractional_count; ++i) {
|
242 |
+
if (fractionals == 0) break;
|
243 |
+
// Instead of multiplying by 10 we multiply by 5 and adjust the point
|
244 |
+
// location. This way the fractionals variable will not overflow.
|
245 |
+
// Invariant at the beginning of the loop: fractionals < 2^point.
|
246 |
+
// Initially we have: point <= 64 and fractionals < 2^56
|
247 |
+
// After each iteration the point is decremented by one.
|
248 |
+
// Note that 5^3 = 125 < 128 = 2^7.
|
249 |
+
// Therefore three iterations of this loop will not overflow fractionals
|
250 |
+
// (even without the subtraction at the end of the loop body). At this
|
251 |
+
// time point will satisfy point <= 61 and therefore fractionals < 2^point
|
252 |
+
// and any further multiplication of fractionals by 5 will not overflow.
|
253 |
+
fractionals *= 5;
|
254 |
+
point--;
|
255 |
+
int digit = static_cast<int>(fractionals >> point);
|
256 |
+
ASSERT(digit <= 9);
|
257 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
258 |
+
(*length)++;
|
259 |
+
fractionals -= static_cast<uint64_t>(digit) << point;
|
260 |
+
}
|
261 |
+
// If the first bit after the point is set we have to round up.
|
262 |
+
ASSERT(fractionals == 0 || point - 1 >= 0);
|
263 |
+
if ((fractionals != 0) && ((fractionals >> (point - 1)) & 1) == 1) {
|
264 |
+
RoundUp(buffer, length, decimal_point);
|
265 |
+
}
|
266 |
+
} else { // We need 128 bits.
|
267 |
+
ASSERT(64 < -exponent && -exponent <= 128);
|
268 |
+
UInt128 fractionals128 = UInt128(fractionals, 0);
|
269 |
+
fractionals128.Shift(-exponent - 64);
|
270 |
+
int point = 128;
|
271 |
+
for (int i = 0; i < fractional_count; ++i) {
|
272 |
+
if (fractionals128.IsZero()) break;
|
273 |
+
// As before: instead of multiplying by 10 we multiply by 5 and adjust the
|
274 |
+
// point location.
|
275 |
+
// This multiplication will not overflow for the same reasons as before.
|
276 |
+
fractionals128.Multiply(5);
|
277 |
+
point--;
|
278 |
+
int digit = fractionals128.DivModPowerOf2(point);
|
279 |
+
ASSERT(digit <= 9);
|
280 |
+
buffer[*length] = static_cast<char>('0' + digit);
|
281 |
+
(*length)++;
|
282 |
+
}
|
283 |
+
if (fractionals128.BitAt(point - 1) == 1) {
|
284 |
+
RoundUp(buffer, length, decimal_point);
|
285 |
+
}
|
286 |
+
}
|
287 |
+
}
|
288 |
+
|
289 |
+
|
290 |
+
// Removes leading and trailing zeros.
|
291 |
+
// If leading zeros are removed then the decimal point position is adjusted.
|
292 |
+
static void TrimZeros(Vector<char> buffer, int* length, int* decimal_point) {
|
293 |
+
while (*length > 0 && buffer[(*length) - 1] == '0') {
|
294 |
+
(*length)--;
|
295 |
+
}
|
296 |
+
int first_non_zero = 0;
|
297 |
+
while (first_non_zero < *length && buffer[first_non_zero] == '0') {
|
298 |
+
first_non_zero++;
|
299 |
+
}
|
300 |
+
if (first_non_zero != 0) {
|
301 |
+
for (int i = first_non_zero; i < *length; ++i) {
|
302 |
+
buffer[i - first_non_zero] = buffer[i];
|
303 |
+
}
|
304 |
+
*length -= first_non_zero;
|
305 |
+
*decimal_point -= first_non_zero;
|
306 |
+
}
|
307 |
+
}
|
308 |
+
|
309 |
+
|
310 |
+
bool FastFixedDtoa(double v,
|
311 |
+
int fractional_count,
|
312 |
+
Vector<char> buffer,
|
313 |
+
int* length,
|
314 |
+
int* decimal_point) {
|
315 |
+
const uint32_t kMaxUInt32 = 0xFFFFFFFF;
|
316 |
+
uint64_t significand = Double(v).Significand();
|
317 |
+
int exponent = Double(v).Exponent();
|
318 |
+
// v = significand * 2^exponent (with significand a 53bit integer).
|
319 |
+
// If the exponent is larger than 20 (i.e. we may have a 73bit number) then we
|
320 |
+
// don't know how to compute the representation. 2^73 ~= 9.5*10^21.
|
321 |
+
// If necessary this limit could probably be increased, but we don't need
|
322 |
+
// more.
|
323 |
+
if (exponent > 20) return false;
|
324 |
+
if (fractional_count > 20) return false;
|
325 |
+
*length = 0;
|
326 |
+
// At most kDoubleSignificandSize bits of the significand are non-zero.
|
327 |
+
// Given a 64 bit integer we have 11 0s followed by 53 potentially non-zero
|
328 |
+
// bits: 0..11*..0xxx..53*..xx
|
329 |
+
if (exponent + kDoubleSignificandSize > 64) {
|
330 |
+
// The exponent must be > 11.
|
331 |
+
//
|
332 |
+
// We know that v = significand * 2^exponent.
|
333 |
+
// And the exponent > 11.
|
334 |
+
// We simplify the task by dividing v by 10^17.
|
335 |
+
// The quotient delivers the first digits, and the remainder fits into a 64
|
336 |
+
// bit number.
|
337 |
+
// Dividing by 10^17 is equivalent to dividing by 5^17*2^17.
|
338 |
+
const uint64_t kFive17 = UINT64_2PART_C(0xB1, A2BC2EC5); // 5^17
|
339 |
+
uint64_t divisor = kFive17;
|
340 |
+
int divisor_power = 17;
|
341 |
+
uint64_t dividend = significand;
|
342 |
+
uint32_t quotient;
|
343 |
+
uint64_t remainder;
|
344 |
+
// Let v = f * 2^e with f == significand and e == exponent.
|
345 |
+
// Then need q (quotient) and r (remainder) as follows:
|
346 |
+
// v = q * 10^17 + r
|
347 |
+
// f * 2^e = q * 10^17 + r
|
348 |
+
// f * 2^e = q * 5^17 * 2^17 + r
|
349 |
+
// If e > 17 then
|
350 |
+
// f * 2^(e-17) = q * 5^17 + r/2^17
|
351 |
+
// else
|
352 |
+
// f = q * 5^17 * 2^(17-e) + r/2^e
|
353 |
+
if (exponent > divisor_power) {
|
354 |
+
// We only allow exponents of up to 20 and therefore (17 - e) <= 3
|
355 |
+
dividend <<= exponent - divisor_power;
|
356 |
+
quotient = static_cast<uint32_t>(dividend / divisor);
|
357 |
+
remainder = (dividend % divisor) << divisor_power;
|
358 |
+
} else {
|
359 |
+
divisor <<= divisor_power - exponent;
|
360 |
+
quotient = static_cast<uint32_t>(dividend / divisor);
|
361 |
+
remainder = (dividend % divisor) << exponent;
|
362 |
+
}
|
363 |
+
FillDigits32(quotient, buffer, length);
|
364 |
+
FillDigits64FixedLength(remainder, buffer, length);
|
365 |
+
*decimal_point = *length;
|
366 |
+
} else if (exponent >= 0) {
|
367 |
+
// 0 <= exponent <= 11
|
368 |
+
significand <<= exponent;
|
369 |
+
FillDigits64(significand, buffer, length);
|
370 |
+
*decimal_point = *length;
|
371 |
+
} else if (exponent > -kDoubleSignificandSize) {
|
372 |
+
// We have to cut the number.
|
373 |
+
uint64_t integrals = significand >> -exponent;
|
374 |
+
uint64_t fractionals = significand - (integrals << -exponent);
|
375 |
+
if (integrals > kMaxUInt32) {
|
376 |
+
FillDigits64(integrals, buffer, length);
|
377 |
+
} else {
|
378 |
+
FillDigits32(static_cast<uint32_t>(integrals), buffer, length);
|
379 |
+
}
|
380 |
+
*decimal_point = *length;
|
381 |
+
FillFractionals(fractionals, exponent, fractional_count,
|
382 |
+
buffer, length, decimal_point);
|
383 |
+
} else if (exponent < -128) {
|
384 |
+
// This configuration (with at most 20 digits) means that all digits must be
|
385 |
+
// 0.
|
386 |
+
ASSERT(fractional_count <= 20);
|
387 |
+
buffer[0] = '\0';
|
388 |
+
*length = 0;
|
389 |
+
*decimal_point = -fractional_count;
|
390 |
+
} else {
|
391 |
+
*decimal_point = 0;
|
392 |
+
FillFractionals(significand, exponent, fractional_count,
|
393 |
+
buffer, length, decimal_point);
|
394 |
+
}
|
395 |
+
TrimZeros(buffer, length, decimal_point);
|
396 |
+
buffer[*length] = '\0';
|
397 |
+
if ((*length) == 0) {
|
398 |
+
// The string is empty and the decimal_point thus has no importance. Mimick
|
399 |
+
// Gay's dtoa and and set it to -fractional_count.
|
400 |
+
*decimal_point = -fractional_count;
|
401 |
+
}
|
402 |
+
return true;
|
403 |
+
}
|
404 |
+
|
405 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/fixed-dtoa.h
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_FIXED_DTOA_H_
|
29 |
+
#define DOUBLE_CONVERSION_FIXED_DTOA_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
// Produces digits necessary to print a given number with
|
36 |
+
// 'fractional_count' digits after the decimal point.
|
37 |
+
// The buffer must be big enough to hold the result plus one terminating null
|
38 |
+
// character.
|
39 |
+
//
|
40 |
+
// The produced digits might be too short in which case the caller has to fill
|
41 |
+
// the gaps with '0's.
|
42 |
+
// Example: FastFixedDtoa(0.001, 5, ...) is allowed to return buffer = "1", and
|
43 |
+
// decimal_point = -2.
|
44 |
+
// Halfway cases are rounded towards +/-Infinity (away from 0). The call
|
45 |
+
// FastFixedDtoa(0.15, 2, ...) thus returns buffer = "2", decimal_point = 0.
|
46 |
+
// The returned buffer may contain digits that would be truncated from the
|
47 |
+
// shortest representation of the input.
|
48 |
+
//
|
49 |
+
// This method only works for some parameters. If it can't handle the input it
|
50 |
+
// returns false. The output is null-terminated when the function succeeds.
|
51 |
+
bool FastFixedDtoa(double v, int fractional_count,
|
52 |
+
Vector<char> buffer, int* length, int* decimal_point);
|
53 |
+
|
54 |
+
} // namespace double_conversion
|
55 |
+
|
56 |
+
#endif // DOUBLE_CONVERSION_FIXED_DTOA_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/ieee.h
ADDED
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2012 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_DOUBLE_H_
|
29 |
+
#define DOUBLE_CONVERSION_DOUBLE_H_
|
30 |
+
|
31 |
+
#include "diy-fp.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
// We assume that doubles and uint64_t have the same endianness.
|
36 |
+
static uint64_t double_to_uint64(double d) { return BitCast<uint64_t>(d); }
|
37 |
+
static double uint64_to_double(uint64_t d64) { return BitCast<double>(d64); }
|
38 |
+
static uint32_t float_to_uint32(float f) { return BitCast<uint32_t>(f); }
|
39 |
+
static float uint32_to_float(uint32_t d32) { return BitCast<float>(d32); }
|
40 |
+
|
41 |
+
// Helper functions for doubles.
|
42 |
+
class Double {
|
43 |
+
public:
|
44 |
+
static const uint64_t kSignMask = UINT64_2PART_C(0x80000000, 00000000);
|
45 |
+
static const uint64_t kExponentMask = UINT64_2PART_C(0x7FF00000, 00000000);
|
46 |
+
static const uint64_t kSignificandMask = UINT64_2PART_C(0x000FFFFF, FFFFFFFF);
|
47 |
+
static const uint64_t kHiddenBit = UINT64_2PART_C(0x00100000, 00000000);
|
48 |
+
static const int kPhysicalSignificandSize = 52; // Excludes the hidden bit.
|
49 |
+
static const int kSignificandSize = 53;
|
50 |
+
|
51 |
+
Double() : d64_(0) {}
|
52 |
+
explicit Double(double d) : d64_(double_to_uint64(d)) {}
|
53 |
+
explicit Double(uint64_t d64) : d64_(d64) {}
|
54 |
+
explicit Double(DiyFp diy_fp)
|
55 |
+
: d64_(DiyFpToUint64(diy_fp)) {}
|
56 |
+
|
57 |
+
// The value encoded by this Double must be greater or equal to +0.0.
|
58 |
+
// It must not be special (infinity, or NaN).
|
59 |
+
DiyFp AsDiyFp() const {
|
60 |
+
ASSERT(Sign() > 0);
|
61 |
+
ASSERT(!IsSpecial());
|
62 |
+
return DiyFp(Significand(), Exponent());
|
63 |
+
}
|
64 |
+
|
65 |
+
// The value encoded by this Double must be strictly greater than 0.
|
66 |
+
DiyFp AsNormalizedDiyFp() const {
|
67 |
+
ASSERT(value() > 0.0);
|
68 |
+
uint64_t f = Significand();
|
69 |
+
int e = Exponent();
|
70 |
+
|
71 |
+
// The current double could be a denormal.
|
72 |
+
while ((f & kHiddenBit) == 0) {
|
73 |
+
f <<= 1;
|
74 |
+
e--;
|
75 |
+
}
|
76 |
+
// Do the final shifts in one go.
|
77 |
+
f <<= DiyFp::kSignificandSize - kSignificandSize;
|
78 |
+
e -= DiyFp::kSignificandSize - kSignificandSize;
|
79 |
+
return DiyFp(f, e);
|
80 |
+
}
|
81 |
+
|
82 |
+
// Returns the double's bit as uint64.
|
83 |
+
uint64_t AsUint64() const {
|
84 |
+
return d64_;
|
85 |
+
}
|
86 |
+
|
87 |
+
// Returns the next greater double. Returns +infinity on input +infinity.
|
88 |
+
double NextDouble() const {
|
89 |
+
if (d64_ == kInfinity) return Double(kInfinity).value();
|
90 |
+
if (Sign() < 0 && Significand() == 0) {
|
91 |
+
// -0.0
|
92 |
+
return 0.0;
|
93 |
+
}
|
94 |
+
if (Sign() < 0) {
|
95 |
+
return Double(d64_ - 1).value();
|
96 |
+
} else {
|
97 |
+
return Double(d64_ + 1).value();
|
98 |
+
}
|
99 |
+
}
|
100 |
+
|
101 |
+
double PreviousDouble() const {
|
102 |
+
if (d64_ == (kInfinity | kSignMask)) return -Infinity();
|
103 |
+
if (Sign() < 0) {
|
104 |
+
return Double(d64_ + 1).value();
|
105 |
+
} else {
|
106 |
+
if (Significand() == 0) return -0.0;
|
107 |
+
return Double(d64_ - 1).value();
|
108 |
+
}
|
109 |
+
}
|
110 |
+
|
111 |
+
int Exponent() const {
|
112 |
+
if (IsDenormal()) return kDenormalExponent;
|
113 |
+
|
114 |
+
uint64_t d64 = AsUint64();
|
115 |
+
int biased_e =
|
116 |
+
static_cast<int>((d64 & kExponentMask) >> kPhysicalSignificandSize);
|
117 |
+
return biased_e - kExponentBias;
|
118 |
+
}
|
119 |
+
|
120 |
+
uint64_t Significand() const {
|
121 |
+
uint64_t d64 = AsUint64();
|
122 |
+
uint64_t significand = d64 & kSignificandMask;
|
123 |
+
if (!IsDenormal()) {
|
124 |
+
return significand + kHiddenBit;
|
125 |
+
} else {
|
126 |
+
return significand;
|
127 |
+
}
|
128 |
+
}
|
129 |
+
|
130 |
+
// Returns true if the double is a denormal.
|
131 |
+
bool IsDenormal() const {
|
132 |
+
uint64_t d64 = AsUint64();
|
133 |
+
return (d64 & kExponentMask) == 0;
|
134 |
+
}
|
135 |
+
|
136 |
+
// We consider denormals not to be special.
|
137 |
+
// Hence only Infinity and NaN are special.
|
138 |
+
bool IsSpecial() const {
|
139 |
+
uint64_t d64 = AsUint64();
|
140 |
+
return (d64 & kExponentMask) == kExponentMask;
|
141 |
+
}
|
142 |
+
|
143 |
+
bool IsNan() const {
|
144 |
+
uint64_t d64 = AsUint64();
|
145 |
+
return ((d64 & kExponentMask) == kExponentMask) &&
|
146 |
+
((d64 & kSignificandMask) != 0);
|
147 |
+
}
|
148 |
+
|
149 |
+
bool IsInfinite() const {
|
150 |
+
uint64_t d64 = AsUint64();
|
151 |
+
return ((d64 & kExponentMask) == kExponentMask) &&
|
152 |
+
((d64 & kSignificandMask) == 0);
|
153 |
+
}
|
154 |
+
|
155 |
+
int Sign() const {
|
156 |
+
uint64_t d64 = AsUint64();
|
157 |
+
return (d64 & kSignMask) == 0? 1: -1;
|
158 |
+
}
|
159 |
+
|
160 |
+
// Precondition: the value encoded by this Double must be greater or equal
|
161 |
+
// than +0.0.
|
162 |
+
DiyFp UpperBoundary() const {
|
163 |
+
ASSERT(Sign() > 0);
|
164 |
+
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
165 |
+
}
|
166 |
+
|
167 |
+
// Computes the two boundaries of this.
|
168 |
+
// The bigger boundary (m_plus) is normalized. The lower boundary has the same
|
169 |
+
// exponent as m_plus.
|
170 |
+
// Precondition: the value encoded by this Double must be greater than 0.
|
171 |
+
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
172 |
+
ASSERT(value() > 0.0);
|
173 |
+
DiyFp v = this->AsDiyFp();
|
174 |
+
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
175 |
+
DiyFp m_minus;
|
176 |
+
if (LowerBoundaryIsCloser()) {
|
177 |
+
m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
|
178 |
+
} else {
|
179 |
+
m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
|
180 |
+
}
|
181 |
+
m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
|
182 |
+
m_minus.set_e(m_plus.e());
|
183 |
+
*out_m_plus = m_plus;
|
184 |
+
*out_m_minus = m_minus;
|
185 |
+
}
|
186 |
+
|
187 |
+
bool LowerBoundaryIsCloser() const {
|
188 |
+
// The boundary is closer if the significand is of the form f == 2^p-1 then
|
189 |
+
// the lower boundary is closer.
|
190 |
+
// Think of v = 1000e10 and v- = 9999e9.
|
191 |
+
// Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
|
192 |
+
// at a distance of 1e8.
|
193 |
+
// The only exception is for the smallest normal: the largest denormal is
|
194 |
+
// at the same distance as its successor.
|
195 |
+
// Note: denormals have the same exponent as the smallest normals.
|
196 |
+
bool physical_significand_is_zero = ((AsUint64() & kSignificandMask) == 0);
|
197 |
+
return physical_significand_is_zero && (Exponent() != kDenormalExponent);
|
198 |
+
}
|
199 |
+
|
200 |
+
double value() const { return uint64_to_double(d64_); }
|
201 |
+
|
202 |
+
// Returns the significand size for a given order of magnitude.
|
203 |
+
// If v = f*2^e with 2^p-1 <= f <= 2^p then p+e is v's order of magnitude.
|
204 |
+
// This function returns the number of significant binary digits v will have
|
205 |
+
// once it's encoded into a double. In almost all cases this is equal to
|
206 |
+
// kSignificandSize. The only exceptions are denormals. They start with
|
207 |
+
// leading zeroes and their effective significand-size is hence smaller.
|
208 |
+
static int SignificandSizeForOrderOfMagnitude(int order) {
|
209 |
+
if (order >= (kDenormalExponent + kSignificandSize)) {
|
210 |
+
return kSignificandSize;
|
211 |
+
}
|
212 |
+
if (order <= kDenormalExponent) return 0;
|
213 |
+
return order - kDenormalExponent;
|
214 |
+
}
|
215 |
+
|
216 |
+
static double Infinity() {
|
217 |
+
return Double(kInfinity).value();
|
218 |
+
}
|
219 |
+
|
220 |
+
static double NaN() {
|
221 |
+
return Double(kNaN).value();
|
222 |
+
}
|
223 |
+
|
224 |
+
private:
|
225 |
+
static const int kExponentBias = 0x3FF + kPhysicalSignificandSize;
|
226 |
+
static const int kDenormalExponent = -kExponentBias + 1;
|
227 |
+
static const int kMaxExponent = 0x7FF - kExponentBias;
|
228 |
+
static const uint64_t kInfinity = UINT64_2PART_C(0x7FF00000, 00000000);
|
229 |
+
static const uint64_t kNaN = UINT64_2PART_C(0x7FF80000, 00000000);
|
230 |
+
|
231 |
+
const uint64_t d64_;
|
232 |
+
|
233 |
+
static uint64_t DiyFpToUint64(DiyFp diy_fp) {
|
234 |
+
uint64_t significand = diy_fp.f();
|
235 |
+
int exponent = diy_fp.e();
|
236 |
+
while (significand > kHiddenBit + kSignificandMask) {
|
237 |
+
significand >>= 1;
|
238 |
+
exponent++;
|
239 |
+
}
|
240 |
+
if (exponent >= kMaxExponent) {
|
241 |
+
return kInfinity;
|
242 |
+
}
|
243 |
+
if (exponent < kDenormalExponent) {
|
244 |
+
return 0;
|
245 |
+
}
|
246 |
+
while (exponent > kDenormalExponent && (significand & kHiddenBit) == 0) {
|
247 |
+
significand <<= 1;
|
248 |
+
exponent--;
|
249 |
+
}
|
250 |
+
uint64_t biased_exponent;
|
251 |
+
if (exponent == kDenormalExponent && (significand & kHiddenBit) == 0) {
|
252 |
+
biased_exponent = 0;
|
253 |
+
} else {
|
254 |
+
biased_exponent = static_cast<uint64_t>(exponent + kExponentBias);
|
255 |
+
}
|
256 |
+
return (significand & kSignificandMask) |
|
257 |
+
(biased_exponent << kPhysicalSignificandSize);
|
258 |
+
}
|
259 |
+
|
260 |
+
DISALLOW_COPY_AND_ASSIGN(Double);
|
261 |
+
};
|
262 |
+
|
263 |
+
class Single {
|
264 |
+
public:
|
265 |
+
static const uint32_t kSignMask = 0x80000000;
|
266 |
+
static const uint32_t kExponentMask = 0x7F800000;
|
267 |
+
static const uint32_t kSignificandMask = 0x007FFFFF;
|
268 |
+
static const uint32_t kHiddenBit = 0x00800000;
|
269 |
+
static const int kPhysicalSignificandSize = 23; // Excludes the hidden bit.
|
270 |
+
static const int kSignificandSize = 24;
|
271 |
+
|
272 |
+
Single() : d32_(0) {}
|
273 |
+
explicit Single(float f) : d32_(float_to_uint32(f)) {}
|
274 |
+
explicit Single(uint32_t d32) : d32_(d32) {}
|
275 |
+
|
276 |
+
// The value encoded by this Single must be greater or equal to +0.0.
|
277 |
+
// It must not be special (infinity, or NaN).
|
278 |
+
DiyFp AsDiyFp() const {
|
279 |
+
ASSERT(Sign() > 0);
|
280 |
+
ASSERT(!IsSpecial());
|
281 |
+
return DiyFp(Significand(), Exponent());
|
282 |
+
}
|
283 |
+
|
284 |
+
// Returns the single's bit as uint64.
|
285 |
+
uint32_t AsUint32() const {
|
286 |
+
return d32_;
|
287 |
+
}
|
288 |
+
|
289 |
+
int Exponent() const {
|
290 |
+
if (IsDenormal()) return kDenormalExponent;
|
291 |
+
|
292 |
+
uint32_t d32 = AsUint32();
|
293 |
+
int biased_e =
|
294 |
+
static_cast<int>((d32 & kExponentMask) >> kPhysicalSignificandSize);
|
295 |
+
return biased_e - kExponentBias;
|
296 |
+
}
|
297 |
+
|
298 |
+
uint32_t Significand() const {
|
299 |
+
uint32_t d32 = AsUint32();
|
300 |
+
uint32_t significand = d32 & kSignificandMask;
|
301 |
+
if (!IsDenormal()) {
|
302 |
+
return significand + kHiddenBit;
|
303 |
+
} else {
|
304 |
+
return significand;
|
305 |
+
}
|
306 |
+
}
|
307 |
+
|
308 |
+
// Returns true if the single is a denormal.
|
309 |
+
bool IsDenormal() const {
|
310 |
+
uint32_t d32 = AsUint32();
|
311 |
+
return (d32 & kExponentMask) == 0;
|
312 |
+
}
|
313 |
+
|
314 |
+
// We consider denormals not to be special.
|
315 |
+
// Hence only Infinity and NaN are special.
|
316 |
+
bool IsSpecial() const {
|
317 |
+
uint32_t d32 = AsUint32();
|
318 |
+
return (d32 & kExponentMask) == kExponentMask;
|
319 |
+
}
|
320 |
+
|
321 |
+
bool IsNan() const {
|
322 |
+
uint32_t d32 = AsUint32();
|
323 |
+
return ((d32 & kExponentMask) == kExponentMask) &&
|
324 |
+
((d32 & kSignificandMask) != 0);
|
325 |
+
}
|
326 |
+
|
327 |
+
bool IsInfinite() const {
|
328 |
+
uint32_t d32 = AsUint32();
|
329 |
+
return ((d32 & kExponentMask) == kExponentMask) &&
|
330 |
+
((d32 & kSignificandMask) == 0);
|
331 |
+
}
|
332 |
+
|
333 |
+
int Sign() const {
|
334 |
+
uint32_t d32 = AsUint32();
|
335 |
+
return (d32 & kSignMask) == 0? 1: -1;
|
336 |
+
}
|
337 |
+
|
338 |
+
// Computes the two boundaries of this.
|
339 |
+
// The bigger boundary (m_plus) is normalized. The lower boundary has the same
|
340 |
+
// exponent as m_plus.
|
341 |
+
// Precondition: the value encoded by this Single must be greater than 0.
|
342 |
+
void NormalizedBoundaries(DiyFp* out_m_minus, DiyFp* out_m_plus) const {
|
343 |
+
ASSERT(value() > 0.0);
|
344 |
+
DiyFp v = this->AsDiyFp();
|
345 |
+
DiyFp m_plus = DiyFp::Normalize(DiyFp((v.f() << 1) + 1, v.e() - 1));
|
346 |
+
DiyFp m_minus;
|
347 |
+
if (LowerBoundaryIsCloser()) {
|
348 |
+
m_minus = DiyFp((v.f() << 2) - 1, v.e() - 2);
|
349 |
+
} else {
|
350 |
+
m_minus = DiyFp((v.f() << 1) - 1, v.e() - 1);
|
351 |
+
}
|
352 |
+
m_minus.set_f(m_minus.f() << (m_minus.e() - m_plus.e()));
|
353 |
+
m_minus.set_e(m_plus.e());
|
354 |
+
*out_m_plus = m_plus;
|
355 |
+
*out_m_minus = m_minus;
|
356 |
+
}
|
357 |
+
|
358 |
+
// Precondition: the value encoded by this Single must be greater or equal
|
359 |
+
// than +0.0.
|
360 |
+
DiyFp UpperBoundary() const {
|
361 |
+
ASSERT(Sign() > 0);
|
362 |
+
return DiyFp(Significand() * 2 + 1, Exponent() - 1);
|
363 |
+
}
|
364 |
+
|
365 |
+
bool LowerBoundaryIsCloser() const {
|
366 |
+
// The boundary is closer if the significand is of the form f == 2^p-1 then
|
367 |
+
// the lower boundary is closer.
|
368 |
+
// Think of v = 1000e10 and v- = 9999e9.
|
369 |
+
// Then the boundary (== (v - v-)/2) is not just at a distance of 1e9 but
|
370 |
+
// at a distance of 1e8.
|
371 |
+
// The only exception is for the smallest normal: the largest denormal is
|
372 |
+
// at the same distance as its successor.
|
373 |
+
// Note: denormals have the same exponent as the smallest normals.
|
374 |
+
bool physical_significand_is_zero = ((AsUint32() & kSignificandMask) == 0);
|
375 |
+
return physical_significand_is_zero && (Exponent() != kDenormalExponent);
|
376 |
+
}
|
377 |
+
|
378 |
+
float value() const { return uint32_to_float(d32_); }
|
379 |
+
|
380 |
+
static float Infinity() {
|
381 |
+
return Single(kInfinity).value();
|
382 |
+
}
|
383 |
+
|
384 |
+
static float NaN() {
|
385 |
+
return Single(kNaN).value();
|
386 |
+
}
|
387 |
+
|
388 |
+
private:
|
389 |
+
static const int kExponentBias = 0x7F + kPhysicalSignificandSize;
|
390 |
+
static const int kDenormalExponent = -kExponentBias + 1;
|
391 |
+
static const int kMaxExponent = 0xFF - kExponentBias;
|
392 |
+
static const uint32_t kInfinity = 0x7F800000;
|
393 |
+
static const uint32_t kNaN = 0x7FC00000;
|
394 |
+
|
395 |
+
const uint32_t d32_;
|
396 |
+
|
397 |
+
DISALLOW_COPY_AND_ASSIGN(Single);
|
398 |
+
};
|
399 |
+
|
400 |
+
} // namespace double_conversion
|
401 |
+
|
402 |
+
#endif // DOUBLE_CONVERSION_DOUBLE_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/strtod.cc
ADDED
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#include <stdarg.h>
|
29 |
+
#include <limits.h>
|
30 |
+
|
31 |
+
#include "strtod.h"
|
32 |
+
#include "bignum.h"
|
33 |
+
#include "cached-powers.h"
|
34 |
+
#include "ieee.h"
|
35 |
+
|
36 |
+
namespace double_conversion {
|
37 |
+
|
38 |
+
// 2^53 = 9007199254740992.
|
39 |
+
// Any integer with at most 15 decimal digits will hence fit into a double
|
40 |
+
// (which has a 53bit significand) without loss of precision.
|
41 |
+
static const int kMaxExactDoubleIntegerDecimalDigits = 15;
|
42 |
+
// 2^64 = 18446744073709551616 > 10^19
|
43 |
+
static const int kMaxUint64DecimalDigits = 19;
|
44 |
+
|
45 |
+
// Max double: 1.7976931348623157 x 10^308
|
46 |
+
// Min non-zero double: 4.9406564584124654 x 10^-324
|
47 |
+
// Any x >= 10^309 is interpreted as +infinity.
|
48 |
+
// Any x <= 10^-324 is interpreted as 0.
|
49 |
+
// Note that 2.5e-324 (despite being smaller than the min double) will be read
|
50 |
+
// as non-zero (equal to the min non-zero double).
|
51 |
+
static const int kMaxDecimalPower = 309;
|
52 |
+
static const int kMinDecimalPower = -324;
|
53 |
+
|
54 |
+
// 2^64 = 18446744073709551616
|
55 |
+
static const uint64_t kMaxUint64 = UINT64_2PART_C(0xFFFFFFFF, FFFFFFFF);
|
56 |
+
|
57 |
+
|
58 |
+
static const double exact_powers_of_ten[] = {
|
59 |
+
1.0, // 10^0
|
60 |
+
10.0,
|
61 |
+
100.0,
|
62 |
+
1000.0,
|
63 |
+
10000.0,
|
64 |
+
100000.0,
|
65 |
+
1000000.0,
|
66 |
+
10000000.0,
|
67 |
+
100000000.0,
|
68 |
+
1000000000.0,
|
69 |
+
10000000000.0, // 10^10
|
70 |
+
100000000000.0,
|
71 |
+
1000000000000.0,
|
72 |
+
10000000000000.0,
|
73 |
+
100000000000000.0,
|
74 |
+
1000000000000000.0,
|
75 |
+
10000000000000000.0,
|
76 |
+
100000000000000000.0,
|
77 |
+
1000000000000000000.0,
|
78 |
+
10000000000000000000.0,
|
79 |
+
100000000000000000000.0, // 10^20
|
80 |
+
1000000000000000000000.0,
|
81 |
+
// 10^22 = 0x21e19e0c9bab2400000 = 0x878678326eac9 * 2^22
|
82 |
+
10000000000000000000000.0
|
83 |
+
};
|
84 |
+
static const int kExactPowersOfTenSize = ARRAY_SIZE(exact_powers_of_ten);
|
85 |
+
|
86 |
+
// Maximum number of significant digits in the decimal representation.
|
87 |
+
// In fact the value is 772 (see conversions.cc), but to give us some margin
|
88 |
+
// we round up to 780.
|
89 |
+
static const int kMaxSignificantDecimalDigits = 780;
|
90 |
+
|
91 |
+
static Vector<const char> TrimLeadingZeros(Vector<const char> buffer) {
|
92 |
+
for (int i = 0; i < buffer.length(); i++) {
|
93 |
+
if (buffer[i] != '0') {
|
94 |
+
return buffer.SubVector(i, buffer.length());
|
95 |
+
}
|
96 |
+
}
|
97 |
+
return Vector<const char>(buffer.start(), 0);
|
98 |
+
}
|
99 |
+
|
100 |
+
|
101 |
+
static Vector<const char> TrimTrailingZeros(Vector<const char> buffer) {
|
102 |
+
for (int i = buffer.length() - 1; i >= 0; --i) {
|
103 |
+
if (buffer[i] != '0') {
|
104 |
+
return buffer.SubVector(0, i + 1);
|
105 |
+
}
|
106 |
+
}
|
107 |
+
return Vector<const char>(buffer.start(), 0);
|
108 |
+
}
|
109 |
+
|
110 |
+
|
111 |
+
static void CutToMaxSignificantDigits(Vector<const char> buffer,
|
112 |
+
int exponent,
|
113 |
+
char* significant_buffer,
|
114 |
+
int* significant_exponent) {
|
115 |
+
for (int i = 0; i < kMaxSignificantDecimalDigits - 1; ++i) {
|
116 |
+
significant_buffer[i] = buffer[i];
|
117 |
+
}
|
118 |
+
// The input buffer has been trimmed. Therefore the last digit must be
|
119 |
+
// different from '0'.
|
120 |
+
ASSERT(buffer[buffer.length() - 1] != '0');
|
121 |
+
// Set the last digit to be non-zero. This is sufficient to guarantee
|
122 |
+
// correct rounding.
|
123 |
+
significant_buffer[kMaxSignificantDecimalDigits - 1] = '1';
|
124 |
+
*significant_exponent =
|
125 |
+
exponent + (buffer.length() - kMaxSignificantDecimalDigits);
|
126 |
+
}
|
127 |
+
|
128 |
+
|
129 |
+
// Trims the buffer and cuts it to at most kMaxSignificantDecimalDigits.
|
130 |
+
// If possible the input-buffer is reused, but if the buffer needs to be
|
131 |
+
// modified (due to cutting), then the input needs to be copied into the
|
132 |
+
// buffer_copy_space.
|
133 |
+
static void TrimAndCut(Vector<const char> buffer, int exponent,
|
134 |
+
char* buffer_copy_space, int space_size,
|
135 |
+
Vector<const char>* trimmed, int* updated_exponent) {
|
136 |
+
Vector<const char> left_trimmed = TrimLeadingZeros(buffer);
|
137 |
+
Vector<const char> right_trimmed = TrimTrailingZeros(left_trimmed);
|
138 |
+
exponent += left_trimmed.length() - right_trimmed.length();
|
139 |
+
if (right_trimmed.length() > kMaxSignificantDecimalDigits) {
|
140 |
+
(void) space_size; // Mark variable as used.
|
141 |
+
ASSERT(space_size >= kMaxSignificantDecimalDigits);
|
142 |
+
CutToMaxSignificantDigits(right_trimmed, exponent,
|
143 |
+
buffer_copy_space, updated_exponent);
|
144 |
+
*trimmed = Vector<const char>(buffer_copy_space,
|
145 |
+
kMaxSignificantDecimalDigits);
|
146 |
+
} else {
|
147 |
+
*trimmed = right_trimmed;
|
148 |
+
*updated_exponent = exponent;
|
149 |
+
}
|
150 |
+
}
|
151 |
+
|
152 |
+
|
153 |
+
// Reads digits from the buffer and converts them to a uint64.
|
154 |
+
// Reads in as many digits as fit into a uint64.
|
155 |
+
// When the string starts with "1844674407370955161" no further digit is read.
|
156 |
+
// Since 2^64 = 18446744073709551616 it would still be possible read another
|
157 |
+
// digit if it was less or equal than 6, but this would complicate the code.
|
158 |
+
static uint64_t ReadUint64(Vector<const char> buffer,
|
159 |
+
int* number_of_read_digits) {
|
160 |
+
uint64_t result = 0;
|
161 |
+
int i = 0;
|
162 |
+
while (i < buffer.length() && result <= (kMaxUint64 / 10 - 1)) {
|
163 |
+
int digit = buffer[i++] - '0';
|
164 |
+
ASSERT(0 <= digit && digit <= 9);
|
165 |
+
result = 10 * result + digit;
|
166 |
+
}
|
167 |
+
*number_of_read_digits = i;
|
168 |
+
return result;
|
169 |
+
}
|
170 |
+
|
171 |
+
|
172 |
+
// Reads a DiyFp from the buffer.
|
173 |
+
// The returned DiyFp is not necessarily normalized.
|
174 |
+
// If remaining_decimals is zero then the returned DiyFp is accurate.
|
175 |
+
// Otherwise it has been rounded and has error of at most 1/2 ulp.
|
176 |
+
static void ReadDiyFp(Vector<const char> buffer,
|
177 |
+
DiyFp* result,
|
178 |
+
int* remaining_decimals) {
|
179 |
+
int read_digits;
|
180 |
+
uint64_t significand = ReadUint64(buffer, &read_digits);
|
181 |
+
if (buffer.length() == read_digits) {
|
182 |
+
*result = DiyFp(significand, 0);
|
183 |
+
*remaining_decimals = 0;
|
184 |
+
} else {
|
185 |
+
// Round the significand.
|
186 |
+
if (buffer[read_digits] >= '5') {
|
187 |
+
significand++;
|
188 |
+
}
|
189 |
+
// Compute the binary exponent.
|
190 |
+
int exponent = 0;
|
191 |
+
*result = DiyFp(significand, exponent);
|
192 |
+
*remaining_decimals = buffer.length() - read_digits;
|
193 |
+
}
|
194 |
+
}
|
195 |
+
|
196 |
+
|
197 |
+
static bool DoubleStrtod(Vector<const char> trimmed,
|
198 |
+
int exponent,
|
199 |
+
double* result) {
|
200 |
+
#if !defined(DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS)
|
201 |
+
// On x86 the floating-point stack can be 64 or 80 bits wide. If it is
|
202 |
+
// 80 bits wide (as is the case on Linux) then double-rounding occurs and the
|
203 |
+
// result is not accurate.
|
204 |
+
// We know that Windows32 uses 64 bits and is therefore accurate.
|
205 |
+
// Note that the ARM simulator is compiled for 32bits. It therefore exhibits
|
206 |
+
// the same problem.
|
207 |
+
return false;
|
208 |
+
#endif
|
209 |
+
if (trimmed.length() <= kMaxExactDoubleIntegerDecimalDigits) {
|
210 |
+
int read_digits;
|
211 |
+
// The trimmed input fits into a double.
|
212 |
+
// If the 10^exponent (resp. 10^-exponent) fits into a double too then we
|
213 |
+
// can compute the result-double simply by multiplying (resp. dividing) the
|
214 |
+
// two numbers.
|
215 |
+
// This is possible because IEEE guarantees that floating-point operations
|
216 |
+
// return the best possible approximation.
|
217 |
+
if (exponent < 0 && -exponent < kExactPowersOfTenSize) {
|
218 |
+
// 10^-exponent fits into a double.
|
219 |
+
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
220 |
+
ASSERT(read_digits == trimmed.length());
|
221 |
+
*result /= exact_powers_of_ten[-exponent];
|
222 |
+
return true;
|
223 |
+
}
|
224 |
+
if (0 <= exponent && exponent < kExactPowersOfTenSize) {
|
225 |
+
// 10^exponent fits into a double.
|
226 |
+
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
227 |
+
ASSERT(read_digits == trimmed.length());
|
228 |
+
*result *= exact_powers_of_ten[exponent];
|
229 |
+
return true;
|
230 |
+
}
|
231 |
+
int remaining_digits =
|
232 |
+
kMaxExactDoubleIntegerDecimalDigits - trimmed.length();
|
233 |
+
if ((0 <= exponent) &&
|
234 |
+
(exponent - remaining_digits < kExactPowersOfTenSize)) {
|
235 |
+
// The trimmed string was short and we can multiply it with
|
236 |
+
// 10^remaining_digits. As a result the remaining exponent now fits
|
237 |
+
// into a double too.
|
238 |
+
*result = static_cast<double>(ReadUint64(trimmed, &read_digits));
|
239 |
+
ASSERT(read_digits == trimmed.length());
|
240 |
+
*result *= exact_powers_of_ten[remaining_digits];
|
241 |
+
*result *= exact_powers_of_ten[exponent - remaining_digits];
|
242 |
+
return true;
|
243 |
+
}
|
244 |
+
}
|
245 |
+
return false;
|
246 |
+
}
|
247 |
+
|
248 |
+
|
249 |
+
// Returns 10^exponent as an exact DiyFp.
|
250 |
+
// The given exponent must be in the range [1; kDecimalExponentDistance[.
|
251 |
+
static DiyFp AdjustmentPowerOfTen(int exponent) {
|
252 |
+
ASSERT(0 < exponent);
|
253 |
+
ASSERT(exponent < PowersOfTenCache::kDecimalExponentDistance);
|
254 |
+
// Simply hardcode the remaining powers for the given decimal exponent
|
255 |
+
// distance.
|
256 |
+
ASSERT(PowersOfTenCache::kDecimalExponentDistance == 8);
|
257 |
+
switch (exponent) {
|
258 |
+
case 1: return DiyFp(UINT64_2PART_C(0xa0000000, 00000000), -60);
|
259 |
+
case 2: return DiyFp(UINT64_2PART_C(0xc8000000, 00000000), -57);
|
260 |
+
case 3: return DiyFp(UINT64_2PART_C(0xfa000000, 00000000), -54);
|
261 |
+
case 4: return DiyFp(UINT64_2PART_C(0x9c400000, 00000000), -50);
|
262 |
+
case 5: return DiyFp(UINT64_2PART_C(0xc3500000, 00000000), -47);
|
263 |
+
case 6: return DiyFp(UINT64_2PART_C(0xf4240000, 00000000), -44);
|
264 |
+
case 7: return DiyFp(UINT64_2PART_C(0x98968000, 00000000), -40);
|
265 |
+
default:
|
266 |
+
UNREACHABLE();
|
267 |
+
}
|
268 |
+
}
|
269 |
+
|
270 |
+
|
271 |
+
// If the function returns true then the result is the correct double.
|
272 |
+
// Otherwise it is either the correct double or the double that is just below
|
273 |
+
// the correct double.
|
274 |
+
static bool DiyFpStrtod(Vector<const char> buffer,
|
275 |
+
int exponent,
|
276 |
+
double* result) {
|
277 |
+
DiyFp input;
|
278 |
+
int remaining_decimals;
|
279 |
+
ReadDiyFp(buffer, &input, &remaining_decimals);
|
280 |
+
// Since we may have dropped some digits the input is not accurate.
|
281 |
+
// If remaining_decimals is different than 0 than the error is at most
|
282 |
+
// .5 ulp (unit in the last place).
|
283 |
+
// We don't want to deal with fractions and therefore keep a common
|
284 |
+
// denominator.
|
285 |
+
const int kDenominatorLog = 3;
|
286 |
+
const int kDenominator = 1 << kDenominatorLog;
|
287 |
+
// Move the remaining decimals into the exponent.
|
288 |
+
exponent += remaining_decimals;
|
289 |
+
uint64_t error = (remaining_decimals == 0 ? 0 : kDenominator / 2);
|
290 |
+
|
291 |
+
int old_e = input.e();
|
292 |
+
input.Normalize();
|
293 |
+
error <<= old_e - input.e();
|
294 |
+
|
295 |
+
ASSERT(exponent <= PowersOfTenCache::kMaxDecimalExponent);
|
296 |
+
if (exponent < PowersOfTenCache::kMinDecimalExponent) {
|
297 |
+
*result = 0.0;
|
298 |
+
return true;
|
299 |
+
}
|
300 |
+
DiyFp cached_power;
|
301 |
+
int cached_decimal_exponent;
|
302 |
+
PowersOfTenCache::GetCachedPowerForDecimalExponent(exponent,
|
303 |
+
&cached_power,
|
304 |
+
&cached_decimal_exponent);
|
305 |
+
|
306 |
+
if (cached_decimal_exponent != exponent) {
|
307 |
+
int adjustment_exponent = exponent - cached_decimal_exponent;
|
308 |
+
DiyFp adjustment_power = AdjustmentPowerOfTen(adjustment_exponent);
|
309 |
+
input.Multiply(adjustment_power);
|
310 |
+
if (kMaxUint64DecimalDigits - buffer.length() >= adjustment_exponent) {
|
311 |
+
// The product of input with the adjustment power fits into a 64 bit
|
312 |
+
// integer.
|
313 |
+
ASSERT(DiyFp::kSignificandSize == 64);
|
314 |
+
} else {
|
315 |
+
// The adjustment power is exact. There is hence only an error of 0.5.
|
316 |
+
error += kDenominator / 2;
|
317 |
+
}
|
318 |
+
}
|
319 |
+
|
320 |
+
input.Multiply(cached_power);
|
321 |
+
// The error introduced by a multiplication of a*b equals
|
322 |
+
// error_a + error_b + error_a*error_b/2^64 + 0.5
|
323 |
+
// Substituting a with 'input' and b with 'cached_power' we have
|
324 |
+
// error_b = 0.5 (all cached powers have an error of less than 0.5 ulp),
|
325 |
+
// error_ab = 0 or 1 / kDenominator > error_a*error_b/ 2^64
|
326 |
+
int error_b = kDenominator / 2;
|
327 |
+
int error_ab = (error == 0 ? 0 : 1); // We round up to 1.
|
328 |
+
int fixed_error = kDenominator / 2;
|
329 |
+
error += error_b + error_ab + fixed_error;
|
330 |
+
|
331 |
+
old_e = input.e();
|
332 |
+
input.Normalize();
|
333 |
+
error <<= old_e - input.e();
|
334 |
+
|
335 |
+
// See if the double's significand changes if we add/subtract the error.
|
336 |
+
int order_of_magnitude = DiyFp::kSignificandSize + input.e();
|
337 |
+
int effective_significand_size =
|
338 |
+
Double::SignificandSizeForOrderOfMagnitude(order_of_magnitude);
|
339 |
+
int precision_digits_count =
|
340 |
+
DiyFp::kSignificandSize - effective_significand_size;
|
341 |
+
if (precision_digits_count + kDenominatorLog >= DiyFp::kSignificandSize) {
|
342 |
+
// This can only happen for very small denormals. In this case the
|
343 |
+
// half-way multiplied by the denominator exceeds the range of an uint64.
|
344 |
+
// Simply shift everything to the right.
|
345 |
+
int shift_amount = (precision_digits_count + kDenominatorLog) -
|
346 |
+
DiyFp::kSignificandSize + 1;
|
347 |
+
input.set_f(input.f() >> shift_amount);
|
348 |
+
input.set_e(input.e() + shift_amount);
|
349 |
+
// We add 1 for the lost precision of error, and kDenominator for
|
350 |
+
// the lost precision of input.f().
|
351 |
+
error = (error >> shift_amount) + 1 + kDenominator;
|
352 |
+
precision_digits_count -= shift_amount;
|
353 |
+
}
|
354 |
+
// We use uint64_ts now. This only works if the DiyFp uses uint64_ts too.
|
355 |
+
ASSERT(DiyFp::kSignificandSize == 64);
|
356 |
+
ASSERT(precision_digits_count < 64);
|
357 |
+
uint64_t one64 = 1;
|
358 |
+
uint64_t precision_bits_mask = (one64 << precision_digits_count) - 1;
|
359 |
+
uint64_t precision_bits = input.f() & precision_bits_mask;
|
360 |
+
uint64_t half_way = one64 << (precision_digits_count - 1);
|
361 |
+
precision_bits *= kDenominator;
|
362 |
+
half_way *= kDenominator;
|
363 |
+
DiyFp rounded_input(input.f() >> precision_digits_count,
|
364 |
+
input.e() + precision_digits_count);
|
365 |
+
if (precision_bits >= half_way + error) {
|
366 |
+
rounded_input.set_f(rounded_input.f() + 1);
|
367 |
+
}
|
368 |
+
// If the last_bits are too close to the half-way case than we are too
|
369 |
+
// inaccurate and round down. In this case we return false so that we can
|
370 |
+
// fall back to a more precise algorithm.
|
371 |
+
|
372 |
+
*result = Double(rounded_input).value();
|
373 |
+
if (half_way - error < precision_bits && precision_bits < half_way + error) {
|
374 |
+
// Too imprecise. The caller will have to fall back to a slower version.
|
375 |
+
// However the returned number is guaranteed to be either the correct
|
376 |
+
// double, or the next-lower double.
|
377 |
+
return false;
|
378 |
+
} else {
|
379 |
+
return true;
|
380 |
+
}
|
381 |
+
}
|
382 |
+
|
383 |
+
|
384 |
+
// Returns
|
385 |
+
// - -1 if buffer*10^exponent < diy_fp.
|
386 |
+
// - 0 if buffer*10^exponent == diy_fp.
|
387 |
+
// - +1 if buffer*10^exponent > diy_fp.
|
388 |
+
// Preconditions:
|
389 |
+
// buffer.length() + exponent <= kMaxDecimalPower + 1
|
390 |
+
// buffer.length() + exponent > kMinDecimalPower
|
391 |
+
// buffer.length() <= kMaxDecimalSignificantDigits
|
392 |
+
static int CompareBufferWithDiyFp(Vector<const char> buffer,
|
393 |
+
int exponent,
|
394 |
+
DiyFp diy_fp) {
|
395 |
+
ASSERT(buffer.length() + exponent <= kMaxDecimalPower + 1);
|
396 |
+
ASSERT(buffer.length() + exponent > kMinDecimalPower);
|
397 |
+
ASSERT(buffer.length() <= kMaxSignificantDecimalDigits);
|
398 |
+
// Make sure that the Bignum will be able to hold all our numbers.
|
399 |
+
// Our Bignum implementation has a separate field for exponents. Shifts will
|
400 |
+
// consume at most one bigit (< 64 bits).
|
401 |
+
// ln(10) == 3.3219...
|
402 |
+
ASSERT(((kMaxDecimalPower + 1) * 333 / 100) < Bignum::kMaxSignificantBits);
|
403 |
+
Bignum buffer_bignum;
|
404 |
+
Bignum diy_fp_bignum;
|
405 |
+
buffer_bignum.AssignDecimalString(buffer);
|
406 |
+
diy_fp_bignum.AssignUInt64(diy_fp.f());
|
407 |
+
if (exponent >= 0) {
|
408 |
+
buffer_bignum.MultiplyByPowerOfTen(exponent);
|
409 |
+
} else {
|
410 |
+
diy_fp_bignum.MultiplyByPowerOfTen(-exponent);
|
411 |
+
}
|
412 |
+
if (diy_fp.e() > 0) {
|
413 |
+
diy_fp_bignum.ShiftLeft(diy_fp.e());
|
414 |
+
} else {
|
415 |
+
buffer_bignum.ShiftLeft(-diy_fp.e());
|
416 |
+
}
|
417 |
+
return Bignum::Compare(buffer_bignum, diy_fp_bignum);
|
418 |
+
}
|
419 |
+
|
420 |
+
|
421 |
+
// Returns true if the guess is the correct double.
|
422 |
+
// Returns false, when guess is either correct or the next-lower double.
|
423 |
+
static bool ComputeGuess(Vector<const char> trimmed, int exponent,
|
424 |
+
double* guess) {
|
425 |
+
if (trimmed.length() == 0) {
|
426 |
+
*guess = 0.0;
|
427 |
+
return true;
|
428 |
+
}
|
429 |
+
if (exponent + trimmed.length() - 1 >= kMaxDecimalPower) {
|
430 |
+
*guess = Double::Infinity();
|
431 |
+
return true;
|
432 |
+
}
|
433 |
+
if (exponent + trimmed.length() <= kMinDecimalPower) {
|
434 |
+
*guess = 0.0;
|
435 |
+
return true;
|
436 |
+
}
|
437 |
+
|
438 |
+
if (DoubleStrtod(trimmed, exponent, guess) ||
|
439 |
+
DiyFpStrtod(trimmed, exponent, guess)) {
|
440 |
+
return true;
|
441 |
+
}
|
442 |
+
if (*guess == Double::Infinity()) {
|
443 |
+
return true;
|
444 |
+
}
|
445 |
+
return false;
|
446 |
+
}
|
447 |
+
|
448 |
+
double Strtod(Vector<const char> buffer, int exponent) {
|
449 |
+
char copy_buffer[kMaxSignificantDecimalDigits];
|
450 |
+
Vector<const char> trimmed;
|
451 |
+
int updated_exponent;
|
452 |
+
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
453 |
+
&trimmed, &updated_exponent);
|
454 |
+
exponent = updated_exponent;
|
455 |
+
|
456 |
+
double guess;
|
457 |
+
bool is_correct = ComputeGuess(trimmed, exponent, &guess);
|
458 |
+
if (is_correct) return guess;
|
459 |
+
|
460 |
+
DiyFp upper_boundary = Double(guess).UpperBoundary();
|
461 |
+
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
462 |
+
if (comparison < 0) {
|
463 |
+
return guess;
|
464 |
+
} else if (comparison > 0) {
|
465 |
+
return Double(guess).NextDouble();
|
466 |
+
} else if ((Double(guess).Significand() & 1) == 0) {
|
467 |
+
// Round towards even.
|
468 |
+
return guess;
|
469 |
+
} else {
|
470 |
+
return Double(guess).NextDouble();
|
471 |
+
}
|
472 |
+
}
|
473 |
+
|
474 |
+
float Strtof(Vector<const char> buffer, int exponent) {
|
475 |
+
char copy_buffer[kMaxSignificantDecimalDigits];
|
476 |
+
Vector<const char> trimmed;
|
477 |
+
int updated_exponent;
|
478 |
+
TrimAndCut(buffer, exponent, copy_buffer, kMaxSignificantDecimalDigits,
|
479 |
+
&trimmed, &updated_exponent);
|
480 |
+
exponent = updated_exponent;
|
481 |
+
|
482 |
+
double double_guess;
|
483 |
+
bool is_correct = ComputeGuess(trimmed, exponent, &double_guess);
|
484 |
+
|
485 |
+
float float_guess = static_cast<float>(double_guess);
|
486 |
+
if (float_guess == double_guess) {
|
487 |
+
// This shortcut triggers for integer values.
|
488 |
+
return float_guess;
|
489 |
+
}
|
490 |
+
|
491 |
+
// We must catch double-rounding. Say the double has been rounded up, and is
|
492 |
+
// now a boundary of a float, and rounds up again. This is why we have to
|
493 |
+
// look at previous too.
|
494 |
+
// Example (in decimal numbers):
|
495 |
+
// input: 12349
|
496 |
+
// high-precision (4 digits): 1235
|
497 |
+
// low-precision (3 digits):
|
498 |
+
// when read from input: 123
|
499 |
+
// when rounded from high precision: 124.
|
500 |
+
// To do this we simply look at the neigbors of the correct result and see
|
501 |
+
// if they would round to the same float. If the guess is not correct we have
|
502 |
+
// to look at four values (since two different doubles could be the correct
|
503 |
+
// double).
|
504 |
+
|
505 |
+
double double_next = Double(double_guess).NextDouble();
|
506 |
+
double double_previous = Double(double_guess).PreviousDouble();
|
507 |
+
|
508 |
+
float f1 = static_cast<float>(double_previous);
|
509 |
+
float f2 = float_guess;
|
510 |
+
float f3 = static_cast<float>(double_next);
|
511 |
+
float f4;
|
512 |
+
if (is_correct) {
|
513 |
+
f4 = f3;
|
514 |
+
} else {
|
515 |
+
double double_next2 = Double(double_next).NextDouble();
|
516 |
+
f4 = static_cast<float>(double_next2);
|
517 |
+
}
|
518 |
+
(void) f2; // Mark variable as used.
|
519 |
+
ASSERT(f1 <= f2 && f2 <= f3 && f3 <= f4);
|
520 |
+
|
521 |
+
// If the guess doesn't lie near a single-precision boundary we can simply
|
522 |
+
// return its float-value.
|
523 |
+
if (f1 == f4) {
|
524 |
+
return float_guess;
|
525 |
+
}
|
526 |
+
|
527 |
+
ASSERT((f1 != f2 && f2 == f3 && f3 == f4) ||
|
528 |
+
(f1 == f2 && f2 != f3 && f3 == f4) ||
|
529 |
+
(f1 == f2 && f2 == f3 && f3 != f4));
|
530 |
+
|
531 |
+
// guess and next are the two possible canditates (in the same way that
|
532 |
+
// double_guess was the lower candidate for a double-precision guess).
|
533 |
+
float guess = f1;
|
534 |
+
float next = f4;
|
535 |
+
DiyFp upper_boundary;
|
536 |
+
if (guess == 0.0f) {
|
537 |
+
float min_float = 1e-45f;
|
538 |
+
upper_boundary = Double(static_cast<double>(min_float) / 2).AsDiyFp();
|
539 |
+
} else {
|
540 |
+
upper_boundary = Single(guess).UpperBoundary();
|
541 |
+
}
|
542 |
+
int comparison = CompareBufferWithDiyFp(trimmed, exponent, upper_boundary);
|
543 |
+
if (comparison < 0) {
|
544 |
+
return guess;
|
545 |
+
} else if (comparison > 0) {
|
546 |
+
return next;
|
547 |
+
} else if ((Single(guess).Significand() & 1) == 0) {
|
548 |
+
// Round towards even.
|
549 |
+
return guess;
|
550 |
+
} else {
|
551 |
+
return next;
|
552 |
+
}
|
553 |
+
}
|
554 |
+
|
555 |
+
} // namespace double_conversion
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/strtod.h
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_STRTOD_H_
|
29 |
+
#define DOUBLE_CONVERSION_STRTOD_H_
|
30 |
+
|
31 |
+
#include "utils.h"
|
32 |
+
|
33 |
+
namespace double_conversion {
|
34 |
+
|
35 |
+
// The buffer must only contain digits in the range [0-9]. It must not
|
36 |
+
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
37 |
+
double Strtod(Vector<const char> buffer, int exponent);
|
38 |
+
|
39 |
+
// The buffer must only contain digits in the range [0-9]. It must not
|
40 |
+
// contain a dot or a sign. It must not start with '0', and must not be empty.
|
41 |
+
float Strtof(Vector<const char> buffer, int exponent);
|
42 |
+
|
43 |
+
} // namespace double_conversion
|
44 |
+
|
45 |
+
#endif // DOUBLE_CONVERSION_STRTOD_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/double-conversion/utils.h
ADDED
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Copyright 2010 the V8 project authors. All rights reserved.
|
2 |
+
// Redistribution and use in source and binary forms, with or without
|
3 |
+
// modification, are permitted provided that the following conditions are
|
4 |
+
// met:
|
5 |
+
//
|
6 |
+
// * Redistributions of source code must retain the above copyright
|
7 |
+
// notice, this list of conditions and the following disclaimer.
|
8 |
+
// * Redistributions in binary form must reproduce the above
|
9 |
+
// copyright notice, this list of conditions and the following
|
10 |
+
// disclaimer in the documentation and/or other materials provided
|
11 |
+
// with the distribution.
|
12 |
+
// * Neither the name of Google Inc. nor the names of its
|
13 |
+
// contributors may be used to endorse or promote products derived
|
14 |
+
// from this software without specific prior written permission.
|
15 |
+
//
|
16 |
+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
17 |
+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
18 |
+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
19 |
+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
20 |
+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
23 |
+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
24 |
+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
25 |
+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
26 |
+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
27 |
+
|
28 |
+
#ifndef DOUBLE_CONVERSION_UTILS_H_
|
29 |
+
#define DOUBLE_CONVERSION_UTILS_H_
|
30 |
+
|
31 |
+
#include <stdlib.h>
|
32 |
+
#include <string.h>
|
33 |
+
|
34 |
+
#include <assert.h>
|
35 |
+
#ifndef ASSERT
|
36 |
+
#define ASSERT(condition) \
|
37 |
+
assert(condition);
|
38 |
+
#endif
|
39 |
+
#ifndef UNIMPLEMENTED
|
40 |
+
#define UNIMPLEMENTED() (abort())
|
41 |
+
#endif
|
42 |
+
#ifndef DOUBLE_CONVERSION_NO_RETURN
|
43 |
+
#ifdef _MSC_VER
|
44 |
+
#define DOUBLE_CONVERSION_NO_RETURN __declspec(noreturn)
|
45 |
+
#else
|
46 |
+
#define DOUBLE_CONVERSION_NO_RETURN __attribute__((noreturn))
|
47 |
+
#endif
|
48 |
+
#endif
|
49 |
+
#ifndef UNREACHABLE
|
50 |
+
#ifdef _MSC_VER
|
51 |
+
void DOUBLE_CONVERSION_NO_RETURN abort_noreturn();
|
52 |
+
inline void abort_noreturn() { abort(); }
|
53 |
+
#define UNREACHABLE() (abort_noreturn())
|
54 |
+
#else
|
55 |
+
#define UNREACHABLE() (abort())
|
56 |
+
#endif
|
57 |
+
#endif
|
58 |
+
|
59 |
+
|
60 |
+
// Double operations detection based on target architecture.
|
61 |
+
// Linux uses a 80bit wide floating point stack on x86. This induces double
|
62 |
+
// rounding, which in turn leads to wrong results.
|
63 |
+
// An easy way to test if the floating-point operations are correct is to
|
64 |
+
// evaluate: 89255.0/1e22. If the floating-point stack is 64 bits wide then
|
65 |
+
// the result is equal to 89255e-22.
|
66 |
+
// The best way to test this, is to create a division-function and to compare
|
67 |
+
// the output of the division with the expected result. (Inlining must be
|
68 |
+
// disabled.)
|
69 |
+
// On Linux,x86 89255e-22 != Div_double(89255.0/1e22)
|
70 |
+
#if defined(_M_X64) || defined(__x86_64__) || \
|
71 |
+
defined(__ARMEL__) || defined(__avr32__) || \
|
72 |
+
defined(__hppa__) || defined(__ia64__) || \
|
73 |
+
defined(__mips__) || \
|
74 |
+
defined(__powerpc__) || defined(__ppc__) || defined(__ppc64__) || \
|
75 |
+
defined(_POWER) || defined(_ARCH_PPC) || defined(_ARCH_PPC64) || \
|
76 |
+
defined(__sparc__) || defined(__sparc) || defined(__s390__) || \
|
77 |
+
defined(__SH4__) || defined(__alpha__) || \
|
78 |
+
defined(_MIPS_ARCH_MIPS32R2) || \
|
79 |
+
defined(__AARCH64EL__) || defined(__aarch64__) || \
|
80 |
+
defined(__riscv)
|
81 |
+
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
82 |
+
#elif defined(__mc68000__)
|
83 |
+
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
|
84 |
+
#elif defined(_M_IX86) || defined(__i386__) || defined(__i386)
|
85 |
+
#if defined(_WIN32)
|
86 |
+
// Windows uses a 64bit wide floating point stack.
|
87 |
+
#define DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS 1
|
88 |
+
#else
|
89 |
+
#undef DOUBLE_CONVERSION_CORRECT_DOUBLE_OPERATIONS
|
90 |
+
#endif // _WIN32
|
91 |
+
#else
|
92 |
+
#error Target architecture was not detected as supported by Double-Conversion.
|
93 |
+
#endif
|
94 |
+
|
95 |
+
#if defined(__GNUC__)
|
96 |
+
#define DOUBLE_CONVERSION_UNUSED __attribute__((unused))
|
97 |
+
#else
|
98 |
+
#define DOUBLE_CONVERSION_UNUSED
|
99 |
+
#endif
|
100 |
+
|
101 |
+
#if defined(_WIN32) && !defined(__MINGW32__)
|
102 |
+
|
103 |
+
typedef signed char int8_t;
|
104 |
+
typedef unsigned char uint8_t;
|
105 |
+
typedef short int16_t; // NOLINT
|
106 |
+
typedef unsigned short uint16_t; // NOLINT
|
107 |
+
typedef int int32_t;
|
108 |
+
typedef unsigned int uint32_t;
|
109 |
+
typedef __int64 int64_t;
|
110 |
+
typedef unsigned __int64 uint64_t;
|
111 |
+
// intptr_t and friends are defined in crtdefs.h through stdio.h.
|
112 |
+
|
113 |
+
#else
|
114 |
+
|
115 |
+
#include <stdint.h>
|
116 |
+
|
117 |
+
#endif
|
118 |
+
|
119 |
+
typedef uint16_t uc16;
|
120 |
+
|
121 |
+
// The following macro works on both 32 and 64-bit platforms.
|
122 |
+
// Usage: instead of writing 0x1234567890123456
|
123 |
+
// write UINT64_2PART_C(0x12345678,90123456);
|
124 |
+
#define UINT64_2PART_C(a, b) (((static_cast<uint64_t>(a) << 32) + 0x##b##u))
|
125 |
+
|
126 |
+
|
127 |
+
// The expression ARRAY_SIZE(a) is a compile-time constant of type
|
128 |
+
// size_t which represents the number of elements of the given
|
129 |
+
// array. You should only use ARRAY_SIZE on statically allocated
|
130 |
+
// arrays.
|
131 |
+
#ifndef ARRAY_SIZE
|
132 |
+
#define ARRAY_SIZE(a) \
|
133 |
+
((sizeof(a) / sizeof(*(a))) / \
|
134 |
+
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
|
135 |
+
#endif
|
136 |
+
|
137 |
+
// A macro to disallow the evil copy constructor and operator= functions
|
138 |
+
// This should be used in the private: declarations for a class
|
139 |
+
#ifndef DISALLOW_COPY_AND_ASSIGN
|
140 |
+
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
|
141 |
+
TypeName(const TypeName&); \
|
142 |
+
void operator=(const TypeName&)
|
143 |
+
#endif
|
144 |
+
|
145 |
+
// A macro to disallow all the implicit constructors, namely the
|
146 |
+
// default constructor, copy constructor and operator= functions.
|
147 |
+
//
|
148 |
+
// This should be used in the private: declarations for a class
|
149 |
+
// that wants to prevent anyone from instantiating it. This is
|
150 |
+
// especially useful for classes containing only static methods.
|
151 |
+
#ifndef DISALLOW_IMPLICIT_CONSTRUCTORS
|
152 |
+
#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
|
153 |
+
TypeName(); \
|
154 |
+
DISALLOW_COPY_AND_ASSIGN(TypeName)
|
155 |
+
#endif
|
156 |
+
|
157 |
+
namespace double_conversion {
|
158 |
+
|
159 |
+
static const int kCharSize = sizeof(char);
|
160 |
+
|
161 |
+
// Returns the maximum of the two parameters.
|
162 |
+
template <typename T>
|
163 |
+
static T Max(T a, T b) {
|
164 |
+
return a < b ? b : a;
|
165 |
+
}
|
166 |
+
|
167 |
+
|
168 |
+
// Returns the minimum of the two parameters.
|
169 |
+
template <typename T>
|
170 |
+
static T Min(T a, T b) {
|
171 |
+
return a < b ? a : b;
|
172 |
+
}
|
173 |
+
|
174 |
+
|
175 |
+
inline int StrLength(const char* string) {
|
176 |
+
size_t length = strlen(string);
|
177 |
+
ASSERT(length == static_cast<size_t>(static_cast<int>(length)));
|
178 |
+
return static_cast<int>(length);
|
179 |
+
}
|
180 |
+
|
181 |
+
// This is a simplified version of V8's Vector class.
|
182 |
+
template <typename T>
|
183 |
+
class Vector {
|
184 |
+
public:
|
185 |
+
Vector() : start_(NULL), length_(0) {}
|
186 |
+
Vector(T* data, int len) : start_(data), length_(len) {
|
187 |
+
ASSERT(len == 0 || (len > 0 && data != NULL));
|
188 |
+
}
|
189 |
+
|
190 |
+
// Returns a vector using the same backing storage as this one,
|
191 |
+
// spanning from and including 'from', to but not including 'to'.
|
192 |
+
Vector<T> SubVector(int from, int to) {
|
193 |
+
ASSERT(to <= length_);
|
194 |
+
ASSERT(from < to);
|
195 |
+
ASSERT(0 <= from);
|
196 |
+
return Vector<T>(start() + from, to - from);
|
197 |
+
}
|
198 |
+
|
199 |
+
// Returns the length of the vector.
|
200 |
+
int length() const { return length_; }
|
201 |
+
|
202 |
+
// Returns whether or not the vector is empty.
|
203 |
+
bool is_empty() const { return length_ == 0; }
|
204 |
+
|
205 |
+
// Returns the pointer to the start of the data in the vector.
|
206 |
+
T* start() const { return start_; }
|
207 |
+
|
208 |
+
// Access individual vector elements - checks bounds in debug mode.
|
209 |
+
T& operator[](int index) const {
|
210 |
+
ASSERT(0 <= index && index < length_);
|
211 |
+
return start_[index];
|
212 |
+
}
|
213 |
+
|
214 |
+
T& first() { return start_[0]; }
|
215 |
+
|
216 |
+
T& last() { return start_[length_ - 1]; }
|
217 |
+
|
218 |
+
private:
|
219 |
+
T* start_;
|
220 |
+
int length_;
|
221 |
+
};
|
222 |
+
|
223 |
+
|
224 |
+
// Helper class for building result strings in a character buffer. The
|
225 |
+
// purpose of the class is to use safe operations that checks the
|
226 |
+
// buffer bounds on all operations in debug mode.
|
227 |
+
class StringBuilder {
|
228 |
+
public:
|
229 |
+
StringBuilder(char* buffer, int buffer_size)
|
230 |
+
: buffer_(buffer, buffer_size), position_(0) { }
|
231 |
+
|
232 |
+
~StringBuilder() { if (!is_finalized()) Finalize(); }
|
233 |
+
|
234 |
+
int size() const { return buffer_.length(); }
|
235 |
+
|
236 |
+
// Get the current position in the builder.
|
237 |
+
int position() const {
|
238 |
+
ASSERT(!is_finalized());
|
239 |
+
return position_;
|
240 |
+
}
|
241 |
+
|
242 |
+
// Reset the position.
|
243 |
+
void Reset() { position_ = 0; }
|
244 |
+
|
245 |
+
// Add a single character to the builder. It is not allowed to add
|
246 |
+
// 0-characters; use the Finalize() method to terminate the string
|
247 |
+
// instead.
|
248 |
+
void AddCharacter(char c) {
|
249 |
+
ASSERT(c != '\0');
|
250 |
+
ASSERT(!is_finalized() && position_ < buffer_.length());
|
251 |
+
buffer_[position_++] = c;
|
252 |
+
}
|
253 |
+
|
254 |
+
// Add an entire string to the builder. Uses strlen() internally to
|
255 |
+
// compute the length of the input string.
|
256 |
+
void AddString(const char* s) {
|
257 |
+
AddSubstring(s, StrLength(s));
|
258 |
+
}
|
259 |
+
|
260 |
+
// Add the first 'n' characters of the given string 's' to the
|
261 |
+
// builder. The input string must have enough characters.
|
262 |
+
void AddSubstring(const char* s, int n) {
|
263 |
+
ASSERT(!is_finalized() && position_ + n < buffer_.length());
|
264 |
+
ASSERT(static_cast<size_t>(n) <= strlen(s));
|
265 |
+
memmove(&buffer_[position_], s, n * kCharSize);
|
266 |
+
position_ += n;
|
267 |
+
}
|
268 |
+
|
269 |
+
|
270 |
+
// Add character padding to the builder. If count is non-positive,
|
271 |
+
// nothing is added to the builder.
|
272 |
+
void AddPadding(char c, int count) {
|
273 |
+
for (int i = 0; i < count; i++) {
|
274 |
+
AddCharacter(c);
|
275 |
+
}
|
276 |
+
}
|
277 |
+
|
278 |
+
// Finalize the string by 0-terminating it and returning the buffer.
|
279 |
+
char* Finalize() {
|
280 |
+
ASSERT(!is_finalized() && position_ < buffer_.length());
|
281 |
+
buffer_[position_] = '\0';
|
282 |
+
// Make sure nobody managed to add a 0-character to the
|
283 |
+
// buffer while building the string.
|
284 |
+
ASSERT(strlen(buffer_.start()) == static_cast<size_t>(position_));
|
285 |
+
position_ = -1;
|
286 |
+
ASSERT(is_finalized());
|
287 |
+
return buffer_.start();
|
288 |
+
}
|
289 |
+
|
290 |
+
private:
|
291 |
+
Vector<char> buffer_;
|
292 |
+
int position_;
|
293 |
+
|
294 |
+
bool is_finalized() const { return position_ < 0; }
|
295 |
+
|
296 |
+
DISALLOW_IMPLICIT_CONSTRUCTORS(StringBuilder);
|
297 |
+
};
|
298 |
+
|
299 |
+
// The type-based aliasing rule allows the compiler to assume that pointers of
|
300 |
+
// different types (for some definition of different) never alias each other.
|
301 |
+
// Thus the following code does not work:
|
302 |
+
//
|
303 |
+
// float f = foo();
|
304 |
+
// int fbits = *(int*)(&f);
|
305 |
+
//
|
306 |
+
// The compiler 'knows' that the int pointer can't refer to f since the types
|
307 |
+
// don't match, so the compiler may cache f in a register, leaving random data
|
308 |
+
// in fbits. Using C++ style casts makes no difference, however a pointer to
|
309 |
+
// char data is assumed to alias any other pointer. This is the 'memcpy
|
310 |
+
// exception'.
|
311 |
+
//
|
312 |
+
// Bit_cast uses the memcpy exception to move the bits from a variable of one
|
313 |
+
// type of a variable of another type. Of course the end result is likely to
|
314 |
+
// be implementation dependent. Most compilers (gcc-4.2 and MSVC 2005)
|
315 |
+
// will completely optimize BitCast away.
|
316 |
+
//
|
317 |
+
// There is an additional use for BitCast.
|
318 |
+
// Recent gccs will warn when they see casts that may result in breakage due to
|
319 |
+
// the type-based aliasing rule. If you have checked that there is no breakage
|
320 |
+
// you can use BitCast to cast one pointer type to another. This confuses gcc
|
321 |
+
// enough that it can no longer see that you have cast one pointer type to
|
322 |
+
// another thus avoiding the warning.
|
323 |
+
template <class Dest, class Source>
|
324 |
+
inline Dest BitCast(const Source& source) {
|
325 |
+
// Compile time assertion: sizeof(Dest) == sizeof(Source)
|
326 |
+
// A compile error here means your Dest and Source have different sizes.
|
327 |
+
DOUBLE_CONVERSION_UNUSED
|
328 |
+
typedef char VerifySizesAreEqual[sizeof(Dest) == sizeof(Source) ? 1 : -1];
|
329 |
+
|
330 |
+
Dest dest;
|
331 |
+
memmove(&dest, &source, sizeof(dest));
|
332 |
+
return dest;
|
333 |
+
}
|
334 |
+
|
335 |
+
template <class Dest, class Source>
|
336 |
+
inline Dest BitCast(Source* source) {
|
337 |
+
return BitCast<Dest>(reinterpret_cast<uintptr_t>(source));
|
338 |
+
}
|
339 |
+
|
340 |
+
} // namespace double_conversion
|
341 |
+
|
342 |
+
#endif // DOUBLE_CONVERSION_UTILS_H_
|
cc-multilingual-main/cc_net/third_party/kenlm/util/ersatz_progress.hh
ADDED
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_ERSATZ_PROGRESS_H
|
2 |
+
#define UTIL_ERSATZ_PROGRESS_H
|
3 |
+
|
4 |
+
#include <iostream>
|
5 |
+
#include <string>
|
6 |
+
#include <stdint.h>
|
7 |
+
|
8 |
+
// Ersatz version of boost::progress so core language model doesn't depend on
|
9 |
+
// boost. Also adds option to print nothing.
|
10 |
+
|
11 |
+
namespace util {
|
12 |
+
|
13 |
+
extern const char kProgressBanner[];
|
14 |
+
|
15 |
+
class ErsatzProgress {
|
16 |
+
public:
|
17 |
+
// No output.
|
18 |
+
ErsatzProgress();
|
19 |
+
|
20 |
+
// Null means no output. The null value is useful for passing along the ostream pointer from another caller.
|
21 |
+
explicit ErsatzProgress(uint64_t complete, std::ostream *to = &std::cerr, const std::string &message = "");
|
22 |
+
|
23 |
+
#if __cplusplus >= 201103L
|
24 |
+
ErsatzProgress(ErsatzProgress &&from) noexcept : current_(from.current_), next_(from.next_), complete_(from.complete_), stones_written_(from.stones_written_), out_(from.out_) {
|
25 |
+
from.out_ = nullptr;
|
26 |
+
from.next_ = (uint64_t)-1;
|
27 |
+
}
|
28 |
+
#endif
|
29 |
+
|
30 |
+
~ErsatzProgress();
|
31 |
+
|
32 |
+
ErsatzProgress &operator++() {
|
33 |
+
if (++current_ >= next_) Milestone();
|
34 |
+
return *this;
|
35 |
+
}
|
36 |
+
|
37 |
+
ErsatzProgress &operator+=(uint64_t amount) {
|
38 |
+
if ((current_ += amount) >= next_) Milestone();
|
39 |
+
return *this;
|
40 |
+
}
|
41 |
+
|
42 |
+
void Set(uint64_t to) {
|
43 |
+
if ((current_ = to) >= next_) Milestone();
|
44 |
+
}
|
45 |
+
|
46 |
+
void Finished() {
|
47 |
+
Set(complete_);
|
48 |
+
}
|
49 |
+
|
50 |
+
private:
|
51 |
+
void Milestone();
|
52 |
+
|
53 |
+
uint64_t current_, next_, complete_;
|
54 |
+
unsigned char stones_written_;
|
55 |
+
std::ostream *out_;
|
56 |
+
|
57 |
+
// noncopyable
|
58 |
+
ErsatzProgress(const ErsatzProgress &other);
|
59 |
+
ErsatzProgress &operator=(const ErsatzProgress &other);
|
60 |
+
};
|
61 |
+
|
62 |
+
} // namespace util
|
63 |
+
|
64 |
+
#endif // UTIL_ERSATZ_PROGRESS_H
|
cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece.hh
ADDED
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_FILE_PIECE_H
|
2 |
+
#define UTIL_FILE_PIECE_H
|
3 |
+
|
4 |
+
#include "ersatz_progress.hh"
|
5 |
+
#include "exception.hh"
|
6 |
+
#include "file.hh"
|
7 |
+
#include "mmap.hh"
|
8 |
+
#include "read_compressed.hh"
|
9 |
+
#include "spaces.hh"
|
10 |
+
#include "string_piece.hh"
|
11 |
+
|
12 |
+
#include <cstddef>
|
13 |
+
#include <iosfwd>
|
14 |
+
#include <string>
|
15 |
+
#include <cassert>
|
16 |
+
#include <stdint.h>
|
17 |
+
|
18 |
+
namespace util {
|
19 |
+
|
20 |
+
class ParseNumberException : public Exception {
|
21 |
+
public:
|
22 |
+
explicit ParseNumberException(StringPiece value) throw();
|
23 |
+
~ParseNumberException() throw() {}
|
24 |
+
};
|
25 |
+
|
26 |
+
class FilePiece;
|
27 |
+
|
28 |
+
// Input Iterator over lines. This allows
|
29 |
+
// for (StringPiece l : FilePiece("file"))
|
30 |
+
// in C++11.
|
31 |
+
// NB: not multipass.
|
32 |
+
class LineIterator {
|
33 |
+
public:
|
34 |
+
LineIterator() : backing_(NULL) {}
|
35 |
+
|
36 |
+
explicit LineIterator(FilePiece &f, char delim = '\n') : backing_(&f), delim_(delim) {
|
37 |
+
++*this;
|
38 |
+
}
|
39 |
+
|
40 |
+
LineIterator &operator++();
|
41 |
+
|
42 |
+
bool operator==(const LineIterator &other) const {
|
43 |
+
return backing_ == other.backing_;
|
44 |
+
}
|
45 |
+
|
46 |
+
bool operator!=(const LineIterator &other) const {
|
47 |
+
return backing_ != other.backing_;
|
48 |
+
}
|
49 |
+
|
50 |
+
operator bool() const { return backing_ != NULL; }
|
51 |
+
|
52 |
+
StringPiece operator*() const { return line_; }
|
53 |
+
const StringPiece *operator->() const { return &line_; }
|
54 |
+
|
55 |
+
private:
|
56 |
+
FilePiece *backing_;
|
57 |
+
StringPiece line_;
|
58 |
+
char delim_;
|
59 |
+
};
|
60 |
+
|
61 |
+
// Memory backing the returned StringPiece may vanish on the next call.
|
62 |
+
class FilePiece {
|
63 |
+
public:
|
64 |
+
// 1 MB default.
|
65 |
+
explicit FilePiece(const char *file, std::ostream *show_progress = NULL, std::size_t min_buffer = 1048576);
|
66 |
+
// Takes ownership of fd. name is used for messages.
|
67 |
+
explicit FilePiece(int fd, const char *name = NULL, std::ostream *show_progress = NULL, std::size_t min_buffer = 1048576);
|
68 |
+
|
69 |
+
/* Read from an istream. Don't use this if you can avoid it. Raw fd IO is
|
70 |
+
* much faster. But sometimes you just have an istream like Boost's HTTP
|
71 |
+
* server and want to parse it the same way.
|
72 |
+
* name is just used for messages and FileName().
|
73 |
+
*/
|
74 |
+
explicit FilePiece(std::istream &stream, const char *name = NULL, std::size_t min_buffer = 1048576);
|
75 |
+
|
76 |
+
LineIterator begin() {
|
77 |
+
return LineIterator(*this);
|
78 |
+
}
|
79 |
+
|
80 |
+
LineIterator end() {
|
81 |
+
return LineIterator();
|
82 |
+
}
|
83 |
+
|
84 |
+
char peek() {
|
85 |
+
if (position_ == position_end_) {
|
86 |
+
Shift();
|
87 |
+
if (at_end_) throw EndOfFileException();
|
88 |
+
}
|
89 |
+
return *position_;
|
90 |
+
}
|
91 |
+
|
92 |
+
char get() {
|
93 |
+
char ret = peek();
|
94 |
+
++position_;
|
95 |
+
return ret;
|
96 |
+
}
|
97 |
+
|
98 |
+
// Leaves the delimiter, if any, to be returned by get(). Delimiters defined by isspace().
|
99 |
+
StringPiece ReadDelimited(const bool *delim = kSpaces) {
|
100 |
+
SkipSpaces(delim);
|
101 |
+
return Consume(FindDelimiterOrEOF(delim));
|
102 |
+
}
|
103 |
+
|
104 |
+
/// Read word until the line or file ends.
|
105 |
+
bool ReadWordSameLine(StringPiece &to, const bool *delim = kSpaces) {
|
106 |
+
assert(delim[static_cast<unsigned char>('\n')]);
|
107 |
+
// Skip non-enter spaces.
|
108 |
+
for (; ; ++position_) {
|
109 |
+
if (position_ == position_end_) {
|
110 |
+
try {
|
111 |
+
Shift();
|
112 |
+
} catch (const util::EndOfFileException &) { return false; }
|
113 |
+
// And break out at end of file.
|
114 |
+
if (position_ == position_end_) return false;
|
115 |
+
}
|
116 |
+
if (!delim[static_cast<unsigned char>(*position_)]) break;
|
117 |
+
if (*position_ == '\n') return false;
|
118 |
+
}
|
119 |
+
// We can't be at the end of file because there's at least one character open.
|
120 |
+
to = Consume(FindDelimiterOrEOF(delim));
|
121 |
+
return true;
|
122 |
+
}
|
123 |
+
|
124 |
+
/** Read a line of text from the file.
|
125 |
+
*
|
126 |
+
* Unlike ReadDelimited, this includes leading spaces and consumes the
|
127 |
+
* delimiter. It is similar to getline in that way.
|
128 |
+
*
|
129 |
+
* If strip_cr is true, any trailing carriate return (as would be found on
|
130 |
+
* a file written on Windows) will be left out of the returned line.
|
131 |
+
*
|
132 |
+
* Throws EndOfFileException if the end of the file is encountered. If the
|
133 |
+
* file does not end in a newline, this could mean that the last line is
|
134 |
+
* never read.
|
135 |
+
*/
|
136 |
+
StringPiece ReadLine(char delim = '\n', bool strip_cr = true);
|
137 |
+
|
138 |
+
/** Read a line of text from the file, or return false on EOF.
|
139 |
+
*
|
140 |
+
* This is like ReadLine, except it returns false where ReadLine throws
|
141 |
+
* EndOfFileException. Like ReadLine it may not read the last line in the
|
142 |
+
* file if the file does not end in a newline.
|
143 |
+
*
|
144 |
+
* If strip_cr is true, any trailing carriate return (as would be found on
|
145 |
+
* a file written on Windows) will be left out of the returned line.
|
146 |
+
*/
|
147 |
+
bool ReadLineOrEOF(StringPiece &to, char delim = '\n', bool strip_cr = true);
|
148 |
+
|
149 |
+
float ReadFloat();
|
150 |
+
double ReadDouble();
|
151 |
+
long int ReadLong();
|
152 |
+
unsigned long int ReadULong();
|
153 |
+
|
154 |
+
// Skip spaces defined by isspace.
|
155 |
+
void SkipSpaces(const bool *delim = kSpaces) {
|
156 |
+
assert(position_ <= position_end_);
|
157 |
+
for (; ; ++position_) {
|
158 |
+
if (position_ == position_end_) {
|
159 |
+
Shift();
|
160 |
+
// And break out at end of file.
|
161 |
+
if (position_ == position_end_) return;
|
162 |
+
}
|
163 |
+
assert(position_ < position_end_);
|
164 |
+
if (!delim[static_cast<unsigned char>(*position_)]) return;
|
165 |
+
}
|
166 |
+
}
|
167 |
+
|
168 |
+
uint64_t Offset() const {
|
169 |
+
return position_ - data_.begin() + mapped_offset_;
|
170 |
+
}
|
171 |
+
|
172 |
+
const std::string &FileName() const { return file_name_; }
|
173 |
+
|
174 |
+
// Force a progress update.
|
175 |
+
void UpdateProgress();
|
176 |
+
|
177 |
+
private:
|
178 |
+
void InitializeNoRead(const char *name, std::size_t min_buffer);
|
179 |
+
// Calls InitializeNoRead, so don't call both.
|
180 |
+
void Initialize(const char *name, std::ostream *show_progress, std::size_t min_buffer);
|
181 |
+
|
182 |
+
template <class T> T ReadNumber();
|
183 |
+
|
184 |
+
StringPiece Consume(const char *to) {
|
185 |
+
assert(to >= position_);
|
186 |
+
StringPiece ret(position_, to - position_);
|
187 |
+
position_ = to;
|
188 |
+
return ret;
|
189 |
+
}
|
190 |
+
|
191 |
+
const char *FindDelimiterOrEOF(const bool *delim = kSpaces);
|
192 |
+
|
193 |
+
void Shift();
|
194 |
+
// Backends to Shift().
|
195 |
+
void MMapShift(uint64_t desired_begin);
|
196 |
+
|
197 |
+
void TransitionToRead();
|
198 |
+
void ReadShift();
|
199 |
+
|
200 |
+
const char *position_, *last_space_, *position_end_;
|
201 |
+
|
202 |
+
scoped_fd file_;
|
203 |
+
const uint64_t total_size_;
|
204 |
+
|
205 |
+
std::size_t default_map_size_;
|
206 |
+
uint64_t mapped_offset_;
|
207 |
+
|
208 |
+
// Order matters: file_ should always be destroyed after this.
|
209 |
+
scoped_memory data_;
|
210 |
+
|
211 |
+
bool at_end_;
|
212 |
+
bool fallback_to_read_;
|
213 |
+
|
214 |
+
ErsatzProgress progress_;
|
215 |
+
|
216 |
+
std::string file_name_;
|
217 |
+
|
218 |
+
ReadCompressed fell_back_;
|
219 |
+
};
|
220 |
+
|
221 |
+
} // namespace util
|
222 |
+
|
223 |
+
#endif // UTIL_FILE_PIECE_H
|
cc-multilingual-main/cc_net/third_party/kenlm/util/file_piece_test.cc
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// Tests might fail if you have creative characters in your path. Sue me.
|
2 |
+
#include "file_piece.hh"
|
3 |
+
|
4 |
+
#include "file_stream.hh"
|
5 |
+
#include "file.hh"
|
6 |
+
#include "scoped.hh"
|
7 |
+
|
8 |
+
#define BOOST_TEST_MODULE FilePieceTest
|
9 |
+
#include <boost/test/unit_test.hpp>
|
10 |
+
#include <fstream>
|
11 |
+
#include <iostream>
|
12 |
+
#include <cstdio>
|
13 |
+
#include <sys/types.h>
|
14 |
+
#include <sys/stat.h>
|
15 |
+
|
16 |
+
namespace util {
|
17 |
+
namespace {
|
18 |
+
|
19 |
+
std::string FileLocation() {
|
20 |
+
if (boost::unit_test::framework::master_test_suite().argc < 2) {
|
21 |
+
return "file_piece.cc";
|
22 |
+
}
|
23 |
+
std::string ret(boost::unit_test::framework::master_test_suite().argv[1]);
|
24 |
+
return ret;
|
25 |
+
}
|
26 |
+
|
27 |
+
/* istream */
|
28 |
+
BOOST_AUTO_TEST_CASE(IStream) {
|
29 |
+
std::fstream ref(FileLocation().c_str(), std::ios::in);
|
30 |
+
std::fstream backing(FileLocation().c_str(), std::ios::in);
|
31 |
+
FilePiece test(backing);
|
32 |
+
std::string ref_line;
|
33 |
+
while (getline(ref, ref_line)) {
|
34 |
+
StringPiece test_line(test.ReadLine());
|
35 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
36 |
+
}
|
37 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
38 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
39 |
+
}
|
40 |
+
|
41 |
+
/* mmap implementation */
|
42 |
+
BOOST_AUTO_TEST_CASE(MMapReadLine) {
|
43 |
+
std::fstream ref(FileLocation().c_str(), std::ios::in);
|
44 |
+
FilePiece test(FileLocation().c_str(), NULL, 1);
|
45 |
+
std::string ref_line;
|
46 |
+
while (getline(ref, ref_line)) {
|
47 |
+
StringPiece test_line(test.ReadLine());
|
48 |
+
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
49 |
+
if (!test_line.empty() || !ref_line.empty()) {
|
50 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
51 |
+
}
|
52 |
+
}
|
53 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
54 |
+
}
|
55 |
+
|
56 |
+
/* mmap with seek beforehand */
|
57 |
+
BOOST_AUTO_TEST_CASE(MMapSeek) {
|
58 |
+
std::fstream ref(FileLocation().c_str(), std::ios::in);
|
59 |
+
ref.seekg(10);
|
60 |
+
scoped_fd file(util::OpenReadOrThrow(FileLocation().c_str()));
|
61 |
+
SeekOrThrow(file.get(), 10);
|
62 |
+
FilePiece test(file.release());
|
63 |
+
std::string ref_line;
|
64 |
+
while (getline(ref, ref_line)) {
|
65 |
+
StringPiece test_line(test.ReadLine());
|
66 |
+
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
67 |
+
if (!test_line.empty() || !ref_line.empty()) {
|
68 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
69 |
+
}
|
70 |
+
}
|
71 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
72 |
+
}
|
73 |
+
|
74 |
+
#if !defined(_WIN32) && !defined(_WIN64) && !defined(__APPLE__)
|
75 |
+
/* Apple isn't happy with the popen, fileno, dup. And I don't want to
|
76 |
+
* reimplement popen. This is an issue with the test.
|
77 |
+
*/
|
78 |
+
/* read() implementation */
|
79 |
+
BOOST_AUTO_TEST_CASE(StreamReadLine) {
|
80 |
+
std::fstream ref(FileLocation().c_str(), std::ios::in);
|
81 |
+
|
82 |
+
std::string popen_args = "cat \"";
|
83 |
+
popen_args += FileLocation();
|
84 |
+
popen_args += '"';
|
85 |
+
|
86 |
+
FILE *catter = popen(popen_args.c_str(), "r");
|
87 |
+
BOOST_REQUIRE(catter);
|
88 |
+
|
89 |
+
FilePiece test(dup(fileno(catter)), "file_piece.cc", NULL, 1);
|
90 |
+
std::string ref_line;
|
91 |
+
while (getline(ref, ref_line)) {
|
92 |
+
StringPiece test_line(test.ReadLine());
|
93 |
+
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
94 |
+
if (!test_line.empty() || !ref_line.empty()) {
|
95 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
96 |
+
}
|
97 |
+
}
|
98 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
99 |
+
BOOST_REQUIRE(!pclose(catter));
|
100 |
+
}
|
101 |
+
#endif
|
102 |
+
|
103 |
+
#ifdef HAVE_ZLIB
|
104 |
+
|
105 |
+
// gzip file
|
106 |
+
BOOST_AUTO_TEST_CASE(PlainZipReadLine) {
|
107 |
+
std::string location(FileLocation());
|
108 |
+
std::fstream ref(location.c_str(), std::ios::in);
|
109 |
+
|
110 |
+
std::string command("gzip <\"");
|
111 |
+
command += location + "\" >\"" + location + "\".gz";
|
112 |
+
|
113 |
+
BOOST_REQUIRE_EQUAL(0, system(command.c_str()));
|
114 |
+
FilePiece test((location + ".gz").c_str(), NULL, 1);
|
115 |
+
unlink((location + ".gz").c_str());
|
116 |
+
std::string ref_line;
|
117 |
+
while (getline(ref, ref_line)) {
|
118 |
+
StringPiece test_line(test.ReadLine());
|
119 |
+
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
120 |
+
if (!test_line.empty() || !ref_line.empty()) {
|
121 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
122 |
+
}
|
123 |
+
}
|
124 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
125 |
+
}
|
126 |
+
|
127 |
+
// gzip stream. Apple doesn't like popen, fileno, dup. This is an issue with
|
128 |
+
// the test.
|
129 |
+
#if !defined __APPLE__ && !defined __MINGW32__
|
130 |
+
BOOST_AUTO_TEST_CASE(StreamZipReadLine) {
|
131 |
+
std::fstream ref(FileLocation().c_str(), std::ios::in);
|
132 |
+
|
133 |
+
std::string command("gzip <\"");
|
134 |
+
command += FileLocation() + "\"";
|
135 |
+
|
136 |
+
FILE * catter = popen(command.c_str(), "r");
|
137 |
+
BOOST_REQUIRE(catter);
|
138 |
+
|
139 |
+
FilePiece test(dup(fileno(catter)), "file_piece.cc.gz", NULL, 1);
|
140 |
+
std::string ref_line;
|
141 |
+
while (getline(ref, ref_line)) {
|
142 |
+
StringPiece test_line(test.ReadLine());
|
143 |
+
// I submitted a bug report to ICU: http://bugs.icu-project.org/trac/ticket/7924
|
144 |
+
if (!test_line.empty() || !ref_line.empty()) {
|
145 |
+
BOOST_CHECK_EQUAL(ref_line, test_line);
|
146 |
+
}
|
147 |
+
}
|
148 |
+
BOOST_CHECK_THROW(test.get(), EndOfFileException);
|
149 |
+
BOOST_REQUIRE(!pclose(catter));
|
150 |
+
}
|
151 |
+
#endif // __APPLE__
|
152 |
+
|
153 |
+
#endif // HAVE_ZLIB
|
154 |
+
|
155 |
+
BOOST_AUTO_TEST_CASE(Numbers) {
|
156 |
+
scoped_fd file(MakeTemp(FileLocation()));
|
157 |
+
const float floating = 3.2;
|
158 |
+
{
|
159 |
+
util::FileStream writing(file.get());
|
160 |
+
writing << "94389483984398493890287 " << floating << " 5";
|
161 |
+
}
|
162 |
+
SeekOrThrow(file.get(), 0);
|
163 |
+
util::FilePiece f(file.release());
|
164 |
+
BOOST_CHECK_THROW(f.ReadULong(), ParseNumberException);
|
165 |
+
BOOST_CHECK_EQUAL("94389483984398493890287", f.ReadDelimited());
|
166 |
+
// Yes, exactly equal. Isn't double-conversion wonderful?
|
167 |
+
BOOST_CHECK_EQUAL(floating, f.ReadFloat());
|
168 |
+
BOOST_CHECK_EQUAL(5, f.ReadULong());
|
169 |
+
}
|
170 |
+
|
171 |
+
} // namespace
|
172 |
+
} // namespace util
|
cc-multilingual-main/cc_net/third_party/kenlm/util/float_to_string.cc
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "float_to_string.hh"
|
2 |
+
|
3 |
+
#include "double-conversion/double-conversion.h"
|
4 |
+
#include "double-conversion/utils.h"
|
5 |
+
|
6 |
+
namespace util {
|
7 |
+
namespace {
|
8 |
+
const double_conversion::DoubleToStringConverter kConverter(double_conversion::DoubleToStringConverter::NO_FLAGS, "inf", "NaN", 'e', -6, 21, 6, 0);
|
9 |
+
} // namespace
|
10 |
+
|
11 |
+
char *ToString(double value, char *to) {
|
12 |
+
double_conversion::StringBuilder builder(to, ToStringBuf<double>::kBytes);
|
13 |
+
kConverter.ToShortest(value, &builder);
|
14 |
+
return &to[builder.position()];
|
15 |
+
}
|
16 |
+
|
17 |
+
char *ToString(float value, char *to) {
|
18 |
+
double_conversion::StringBuilder builder(to, ToStringBuf<float>::kBytes);
|
19 |
+
kConverter.ToShortestSingle(value, &builder);
|
20 |
+
return &to[builder.position()];
|
21 |
+
}
|
22 |
+
|
23 |
+
} // namespace util
|
cc-multilingual-main/cc_net/third_party/kenlm/util/getopt.c
ADDED
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
POSIX getopt for Windows
|
3 |
+
|
4 |
+
AT&T Public License
|
5 |
+
|
6 |
+
Code given out at the 1985 UNIFORUM conference in Dallas.
|
7 |
+
*/
|
8 |
+
|
9 |
+
#ifndef __GNUC__
|
10 |
+
|
11 |
+
#include "getopt.hh"
|
12 |
+
#include <stdio.h>
|
13 |
+
#include <string.h>
|
14 |
+
|
15 |
+
#define NULL 0
|
16 |
+
#define EOF (-1)
|
17 |
+
#define ERR(s, c) if(opterr){\
|
18 |
+
char errbuf[2];\
|
19 |
+
errbuf[0] = c; errbuf[1] = '\n';\
|
20 |
+
fputs(argv[0], stderr);\
|
21 |
+
fputs(s, stderr);\
|
22 |
+
fputc(c, stderr);}
|
23 |
+
//(void) write(2, argv[0], (unsigned)strlen(argv[0]));\
|
24 |
+
//(void) write(2, s, (unsigned)strlen(s));\
|
25 |
+
//(void) write(2, errbuf, 2);}
|
26 |
+
|
27 |
+
int opterr = 1;
|
28 |
+
int optind = 1;
|
29 |
+
int optopt;
|
30 |
+
char *optarg;
|
31 |
+
|
32 |
+
int
|
33 |
+
getopt(argc, argv, opts)
|
34 |
+
int argc;
|
35 |
+
char **argv, *opts;
|
36 |
+
{
|
37 |
+
static int sp = 1;
|
38 |
+
register int c;
|
39 |
+
register char *cp;
|
40 |
+
|
41 |
+
if(sp == 1)
|
42 |
+
if(optind >= argc ||
|
43 |
+
argv[optind][0] != '-' || argv[optind][1] == '\0')
|
44 |
+
return(EOF);
|
45 |
+
else if(strcmp(argv[optind], "--") == NULL) {
|
46 |
+
optind++;
|
47 |
+
return(EOF);
|
48 |
+
}
|
49 |
+
optopt = c = argv[optind][sp];
|
50 |
+
if(c == ':' || (cp=strchr(opts, c)) == NULL) {
|
51 |
+
ERR(": illegal option -- ", c);
|
52 |
+
if(argv[optind][++sp] == '\0') {
|
53 |
+
optind++;
|
54 |
+
sp = 1;
|
55 |
+
}
|
56 |
+
return('?');
|
57 |
+
}
|
58 |
+
if(*++cp == ':') {
|
59 |
+
if(argv[optind][sp+1] != '\0')
|
60 |
+
optarg = &argv[optind++][sp+1];
|
61 |
+
else if(++optind >= argc) {
|
62 |
+
ERR(": option requires an argument -- ", c);
|
63 |
+
sp = 1;
|
64 |
+
return('?');
|
65 |
+
} else
|
66 |
+
optarg = argv[optind++];
|
67 |
+
sp = 1;
|
68 |
+
} else {
|
69 |
+
if(argv[optind][++sp] == '\0') {
|
70 |
+
sp = 1;
|
71 |
+
optind++;
|
72 |
+
}
|
73 |
+
optarg = NULL;
|
74 |
+
}
|
75 |
+
return(c);
|
76 |
+
}
|
77 |
+
|
78 |
+
#endif /* __GNUC__ */
|
cc-multilingual-main/cc_net/third_party/kenlm/util/have.hh
ADDED
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* Optional packages. You might want to integrate this with your build system e.g. config.h from ./configure. */
|
2 |
+
#ifndef UTIL_HAVE_H
|
3 |
+
#define UTIL_HAVE_H
|
4 |
+
|
5 |
+
#ifdef HAVE_CONFIG_H
|
6 |
+
#include "config.h"
|
7 |
+
#endif
|
8 |
+
|
9 |
+
#ifndef HAVE_ICU
|
10 |
+
//#define HAVE_ICU
|
11 |
+
#endif
|
12 |
+
|
13 |
+
#endif // UTIL_HAVE_H
|
cc-multilingual-main/cc_net/third_party/kenlm/util/integer_to_string.cc
ADDED
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include <iostream>
|
2 |
+
/* Fast integer to string conversion.
|
3 |
+
Source: https://github.com/miloyip/itoa-benchmark
|
4 |
+
Local modifications:
|
5 |
+
1. Return end of buffer instead of null terminating
|
6 |
+
2. Collapse to single file
|
7 |
+
3. Namespace
|
8 |
+
4. Remove test hook
|
9 |
+
5. Non-x86 support from the branch_lut code
|
10 |
+
6. Rename functions
|
11 |
+
7. Require __SSE2__ on i386
|
12 |
+
|
13 |
+
Copyright (C) 2014 Milo Yip
|
14 |
+
|
15 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
16 |
+
of this software and associated documentation files (the "Software"), to deal
|
17 |
+
in the Software without restriction, including without limitation the rights
|
18 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
19 |
+
copies of the Software, and to permit persons to whom the Software is
|
20 |
+
furnished to do so, subject to the following conditions:
|
21 |
+
|
22 |
+
The above copyright notice and this permission notice shall be included in
|
23 |
+
all copies or substantial portions of the Software.
|
24 |
+
|
25 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
26 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
27 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
28 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
29 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
30 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
31 |
+
THE SOFTWARE.
|
32 |
+
|
33 |
+
Which is based on: http://0x80.pl/snippets/asm/sse-utoa.c
|
34 |
+
|
35 |
+
SSE: conversion integers to decimal representation
|
36 |
+
|
37 |
+
Author: Wojciech Muła
|
38 |
+
e-mail: [email protected]
|
39 |
+
www: http://0x80.pl/
|
40 |
+
|
41 |
+
License: BSD
|
42 |
+
|
43 |
+
initial release 2011-10-21
|
44 |
+
$Id$
|
45 |
+
*/
|
46 |
+
|
47 |
+
#include "integer_to_string.hh"
|
48 |
+
#include <cassert>
|
49 |
+
#include <stdint.h>
|
50 |
+
|
51 |
+
namespace util {
|
52 |
+
|
53 |
+
namespace {
|
54 |
+
const char gDigitsLut[200] = {
|
55 |
+
'0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',
|
56 |
+
'1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',
|
57 |
+
'2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',
|
58 |
+
'3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',
|
59 |
+
'4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',
|
60 |
+
'5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',
|
61 |
+
'6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',
|
62 |
+
'7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',
|
63 |
+
'8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',
|
64 |
+
'9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'
|
65 |
+
};
|
66 |
+
} // namespace
|
67 |
+
|
68 |
+
// SSE2 implementation according to http://0x80.pl/articles/sse-itoa.html
|
69 |
+
// Modifications: (1) fix incorrect digits (2) accept all ranges (3) write to user provided buffer.
|
70 |
+
|
71 |
+
#if defined(__amd64) || defined(_M_X64) || (defined(__SSE2__) && (defined(_M_IX86) || defined(i386)))
|
72 |
+
|
73 |
+
#include <emmintrin.h>
|
74 |
+
|
75 |
+
#ifdef _MSC_VER
|
76 |
+
#include "intrin.h"
|
77 |
+
#endif
|
78 |
+
|
79 |
+
#ifdef _MSC_VER
|
80 |
+
#define ALIGN_PRE __declspec(align(16))
|
81 |
+
#define ALIGN_SUF
|
82 |
+
#else
|
83 |
+
#define ALIGN_PRE
|
84 |
+
#define ALIGN_SUF __attribute__ ((aligned(16)))
|
85 |
+
#endif
|
86 |
+
|
87 |
+
namespace {
|
88 |
+
|
89 |
+
static const uint32_t kDiv10000 = 0xd1b71759;
|
90 |
+
ALIGN_PRE static const uint32_t kDiv10000Vector[4] ALIGN_SUF = { kDiv10000, kDiv10000, kDiv10000, kDiv10000 };
|
91 |
+
ALIGN_PRE static const uint32_t k10000Vector[4] ALIGN_SUF = { 10000, 10000, 10000, 10000 };
|
92 |
+
ALIGN_PRE static const uint16_t kDivPowersVector[8] ALIGN_SUF = { 8389, 5243, 13108, 32768, 8389, 5243, 13108, 32768 }; // 10^3, 10^2, 10^1, 10^0
|
93 |
+
ALIGN_PRE static const uint16_t kShiftPowersVector[8] ALIGN_SUF = {
|
94 |
+
1 << (16 - (23 + 2 - 16)),
|
95 |
+
1 << (16 - (19 + 2 - 16)),
|
96 |
+
1 << (16 - 1 - 2),
|
97 |
+
1 << (15),
|
98 |
+
1 << (16 - (23 + 2 - 16)),
|
99 |
+
1 << (16 - (19 + 2 - 16)),
|
100 |
+
1 << (16 - 1 - 2),
|
101 |
+
1 << (15)
|
102 |
+
};
|
103 |
+
ALIGN_PRE static const uint16_t k10Vector[8] ALIGN_SUF = { 10, 10, 10, 10, 10, 10, 10, 10 };
|
104 |
+
ALIGN_PRE static const char kAsciiZero[16] ALIGN_SUF = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
|
105 |
+
|
106 |
+
inline __m128i Convert8DigitsSSE2(uint32_t value) {
|
107 |
+
assert(value <= 99999999);
|
108 |
+
|
109 |
+
// abcd, efgh = abcdefgh divmod 10000
|
110 |
+
const __m128i abcdefgh = _mm_cvtsi32_si128(value);
|
111 |
+
const __m128i abcd = _mm_srli_epi64(_mm_mul_epu32(abcdefgh, reinterpret_cast<const __m128i*>(kDiv10000Vector)[0]), 45);
|
112 |
+
const __m128i efgh = _mm_sub_epi32(abcdefgh, _mm_mul_epu32(abcd, reinterpret_cast<const __m128i*>(k10000Vector)[0]));
|
113 |
+
|
114 |
+
// v1 = [ abcd, efgh, 0, 0, 0, 0, 0, 0 ]
|
115 |
+
const __m128i v1 = _mm_unpacklo_epi16(abcd, efgh);
|
116 |
+
|
117 |
+
// v1a = v1 * 4 = [ abcd * 4, efgh * 4, 0, 0, 0, 0, 0, 0 ]
|
118 |
+
const __m128i v1a = _mm_slli_epi64(v1, 2);
|
119 |
+
|
120 |
+
// v2 = [ abcd * 4, abcd * 4, abcd * 4, abcd * 4, efgh * 4, efgh * 4, efgh * 4, efgh * 4 ]
|
121 |
+
const __m128i v2a = _mm_unpacklo_epi16(v1a, v1a);
|
122 |
+
const __m128i v2 = _mm_unpacklo_epi32(v2a, v2a);
|
123 |
+
|
124 |
+
// v4 = v2 div 10^3, 10^2, 10^1, 10^0 = [ a, ab, abc, abcd, e, ef, efg, efgh ]
|
125 |
+
const __m128i v3 = _mm_mulhi_epu16(v2, reinterpret_cast<const __m128i*>(kDivPowersVector)[0]);
|
126 |
+
const __m128i v4 = _mm_mulhi_epu16(v3, reinterpret_cast<const __m128i*>(kShiftPowersVector)[0]);
|
127 |
+
|
128 |
+
// v5 = v4 * 10 = [ a0, ab0, abc0, abcd0, e0, ef0, efg0, efgh0 ]
|
129 |
+
const __m128i v5 = _mm_mullo_epi16(v4, reinterpret_cast<const __m128i*>(k10Vector)[0]);
|
130 |
+
|
131 |
+
// v6 = v5 << 16 = [ 0, a0, ab0, abc0, 0, e0, ef0, efg0 ]
|
132 |
+
const __m128i v6 = _mm_slli_epi64(v5, 16);
|
133 |
+
|
134 |
+
// v7 = v4 - v6 = { a, b, c, d, e, f, g, h }
|
135 |
+
const __m128i v7 = _mm_sub_epi16(v4, v6);
|
136 |
+
|
137 |
+
return v7;
|
138 |
+
}
|
139 |
+
|
140 |
+
inline __m128i ShiftDigits_SSE2(__m128i a, unsigned digit) {
|
141 |
+
assert(digit <= 8);
|
142 |
+
switch (digit) {
|
143 |
+
case 0: return a;
|
144 |
+
case 1: return _mm_srli_si128(a, 1);
|
145 |
+
case 2: return _mm_srli_si128(a, 2);
|
146 |
+
case 3: return _mm_srli_si128(a, 3);
|
147 |
+
case 4: return _mm_srli_si128(a, 4);
|
148 |
+
case 5: return _mm_srli_si128(a, 5);
|
149 |
+
case 6: return _mm_srli_si128(a, 6);
|
150 |
+
case 7: return _mm_srli_si128(a, 7);
|
151 |
+
case 8: return _mm_srli_si128(a, 8);
|
152 |
+
}
|
153 |
+
return a; // should not execute here.
|
154 |
+
}
|
155 |
+
|
156 |
+
} // namespace
|
157 |
+
|
158 |
+
// Original name: u32toa_sse2
|
159 |
+
char *ToString(uint32_t value, char* buffer) {
|
160 |
+
if (value < 10000) {
|
161 |
+
const uint32_t d1 = (value / 100) << 1;
|
162 |
+
const uint32_t d2 = (value % 100) << 1;
|
163 |
+
|
164 |
+
if (value >= 1000)
|
165 |
+
*buffer++ = gDigitsLut[d1];
|
166 |
+
if (value >= 100)
|
167 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
168 |
+
if (value >= 10)
|
169 |
+
*buffer++ = gDigitsLut[d2];
|
170 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
171 |
+
//*buffer++ = '\0';
|
172 |
+
return buffer;
|
173 |
+
}
|
174 |
+
else if (value < 100000000) {
|
175 |
+
// Experiment shows that this case SSE2 is slower
|
176 |
+
#if 0
|
177 |
+
const __m128i a = Convert8DigitsSSE2(value);
|
178 |
+
|
179 |
+
// Convert to bytes, add '0'
|
180 |
+
const __m128i va = _mm_add_epi8(_mm_packus_epi16(a, _mm_setzero_si128()), reinterpret_cast<const __m128i*>(kAsciiZero)[0]);
|
181 |
+
|
182 |
+
// Count number of digit
|
183 |
+
const unsigned mask = _mm_movemask_epi8(_mm_cmpeq_epi8(va, reinterpret_cast<const __m128i*>(kAsciiZero)[0]));
|
184 |
+
unsigned long digit;
|
185 |
+
#ifdef _MSC_VER
|
186 |
+
_BitScanForward(&digit, ~mask | 0x8000);
|
187 |
+
#else
|
188 |
+
digit = __builtin_ctz(~mask | 0x8000);
|
189 |
+
#endif
|
190 |
+
|
191 |
+
// Shift digits to the beginning
|
192 |
+
__m128i result = ShiftDigits_SSE2(va, digit);
|
193 |
+
//__m128i result = _mm_srl_epi64(va, _mm_cvtsi32_si128(digit * 8));
|
194 |
+
_mm_storel_epi64(reinterpret_cast<__m128i*>(buffer), result);
|
195 |
+
buffer[8 - digit] = '\0';
|
196 |
+
#else
|
197 |
+
// value = bbbbcccc
|
198 |
+
const uint32_t b = value / 10000;
|
199 |
+
const uint32_t c = value % 10000;
|
200 |
+
|
201 |
+
const uint32_t d1 = (b / 100) << 1;
|
202 |
+
const uint32_t d2 = (b % 100) << 1;
|
203 |
+
|
204 |
+
const uint32_t d3 = (c / 100) << 1;
|
205 |
+
const uint32_t d4 = (c % 100) << 1;
|
206 |
+
|
207 |
+
if (value >= 10000000)
|
208 |
+
*buffer++ = gDigitsLut[d1];
|
209 |
+
if (value >= 1000000)
|
210 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
211 |
+
if (value >= 100000)
|
212 |
+
*buffer++ = gDigitsLut[d2];
|
213 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
214 |
+
|
215 |
+
*buffer++ = gDigitsLut[d3];
|
216 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
217 |
+
*buffer++ = gDigitsLut[d4];
|
218 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
219 |
+
// *buffer++ = '\0';
|
220 |
+
return buffer;
|
221 |
+
#endif
|
222 |
+
}
|
223 |
+
else {
|
224 |
+
// value = aabbbbbbbb in decimal
|
225 |
+
|
226 |
+
const uint32_t a = value / 100000000; // 1 to 42
|
227 |
+
value %= 100000000;
|
228 |
+
|
229 |
+
if (a >= 10) {
|
230 |
+
const unsigned i = a << 1;
|
231 |
+
*buffer++ = gDigitsLut[i];
|
232 |
+
*buffer++ = gDigitsLut[i + 1];
|
233 |
+
}
|
234 |
+
else
|
235 |
+
*buffer++ = '0' + static_cast<char>(a);
|
236 |
+
|
237 |
+
const __m128i b = Convert8DigitsSSE2(value);
|
238 |
+
const __m128i ba = _mm_add_epi8(_mm_packus_epi16(_mm_setzero_si128(), b), reinterpret_cast<const __m128i*>(kAsciiZero)[0]);
|
239 |
+
const __m128i result = _mm_srli_si128(ba, 8);
|
240 |
+
_mm_storel_epi64(reinterpret_cast<__m128i*>(buffer), result);
|
241 |
+
// buffer[8] = '\0';
|
242 |
+
return buffer + 8;
|
243 |
+
}
|
244 |
+
}
|
245 |
+
|
246 |
+
// Original name: u64toa_sse2
|
247 |
+
char *ToString(uint64_t value, char* buffer) {
|
248 |
+
if (value < 100000000) {
|
249 |
+
uint32_t v = static_cast<uint32_t>(value);
|
250 |
+
if (v < 10000) {
|
251 |
+
const uint32_t d1 = (v / 100) << 1;
|
252 |
+
const uint32_t d2 = (v % 100) << 1;
|
253 |
+
|
254 |
+
if (v >= 1000)
|
255 |
+
*buffer++ = gDigitsLut[d1];
|
256 |
+
if (v >= 100)
|
257 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
258 |
+
if (v >= 10)
|
259 |
+
*buffer++ = gDigitsLut[d2];
|
260 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
261 |
+
//*buffer++ = '\0';
|
262 |
+
return buffer;
|
263 |
+
}
|
264 |
+
else {
|
265 |
+
// Experiment shows that this case SSE2 is slower
|
266 |
+
#if 0
|
267 |
+
const __m128i a = Convert8DigitsSSE2(v);
|
268 |
+
|
269 |
+
// Convert to bytes, add '0'
|
270 |
+
const __m128i va = _mm_add_epi8(_mm_packus_epi16(a, _mm_setzero_si128()), reinterpret_cast<const __m128i*>(kAsciiZero)[0]);
|
271 |
+
|
272 |
+
// Count number of digit
|
273 |
+
const unsigned mask = _mm_movemask_epi8(_mm_cmpeq_epi8(va, reinterpret_cast<const __m128i*>(kAsciiZero)[0]));
|
274 |
+
unsigned long digit;
|
275 |
+
#ifdef _MSC_VER
|
276 |
+
_BitScanForward(&digit, ~mask | 0x8000);
|
277 |
+
#else
|
278 |
+
digit = __builtin_ctz(~mask | 0x8000);
|
279 |
+
#endif
|
280 |
+
|
281 |
+
// Shift digits to the beginning
|
282 |
+
__m128i result = ShiftDigits_SSE2(va, digit);
|
283 |
+
_mm_storel_epi64(reinterpret_cast<__m128i*>(buffer), result);
|
284 |
+
buffer[8 - digit] = '\0';
|
285 |
+
#else
|
286 |
+
// value = bbbbcccc
|
287 |
+
const uint32_t b = v / 10000;
|
288 |
+
const uint32_t c = v % 10000;
|
289 |
+
|
290 |
+
const uint32_t d1 = (b / 100) << 1;
|
291 |
+
const uint32_t d2 = (b % 100) << 1;
|
292 |
+
|
293 |
+
const uint32_t d3 = (c / 100) << 1;
|
294 |
+
const uint32_t d4 = (c % 100) << 1;
|
295 |
+
|
296 |
+
if (value >= 10000000)
|
297 |
+
*buffer++ = gDigitsLut[d1];
|
298 |
+
if (value >= 1000000)
|
299 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
300 |
+
if (value >= 100000)
|
301 |
+
*buffer++ = gDigitsLut[d2];
|
302 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
303 |
+
|
304 |
+
*buffer++ = gDigitsLut[d3];
|
305 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
306 |
+
*buffer++ = gDigitsLut[d4];
|
307 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
308 |
+
//*buffer++ = '\0';
|
309 |
+
return buffer;
|
310 |
+
#endif
|
311 |
+
}
|
312 |
+
}
|
313 |
+
else if (value < 10000000000000000) {
|
314 |
+
const uint32_t v0 = static_cast<uint32_t>(value / 100000000);
|
315 |
+
const uint32_t v1 = static_cast<uint32_t>(value % 100000000);
|
316 |
+
|
317 |
+
const __m128i a0 = Convert8DigitsSSE2(v0);
|
318 |
+
const __m128i a1 = Convert8DigitsSSE2(v1);
|
319 |
+
|
320 |
+
// Convert to bytes, add '0'
|
321 |
+
const __m128i va = _mm_add_epi8(_mm_packus_epi16(a0, a1), reinterpret_cast<const __m128i*>(kAsciiZero)[0]);
|
322 |
+
|
323 |
+
// Count number of digit
|
324 |
+
const unsigned mask = _mm_movemask_epi8(_mm_cmpeq_epi8(va, reinterpret_cast<const __m128i*>(kAsciiZero)[0]));
|
325 |
+
#ifdef _MSC_VER
|
326 |
+
unsigned long digit;
|
327 |
+
_BitScanForward(&digit, ~mask | 0x8000);
|
328 |
+
#else
|
329 |
+
unsigned digit = __builtin_ctz(~mask | 0x8000);
|
330 |
+
#endif
|
331 |
+
|
332 |
+
// Shift digits to the beginning
|
333 |
+
__m128i result = ShiftDigits_SSE2(va, digit);
|
334 |
+
_mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), result);
|
335 |
+
// buffer[16 - digit] = '\0';
|
336 |
+
return &buffer[16 - digit];
|
337 |
+
}
|
338 |
+
else {
|
339 |
+
const uint32_t a = static_cast<uint32_t>(value / 10000000000000000); // 1 to 1844
|
340 |
+
value %= 10000000000000000;
|
341 |
+
|
342 |
+
if (a < 10)
|
343 |
+
*buffer++ = '0' + static_cast<char>(a);
|
344 |
+
else if (a < 100) {
|
345 |
+
const uint32_t i = a << 1;
|
346 |
+
*buffer++ = gDigitsLut[i];
|
347 |
+
*buffer++ = gDigitsLut[i + 1];
|
348 |
+
}
|
349 |
+
else if (a < 1000) {
|
350 |
+
*buffer++ = '0' + static_cast<char>(a / 100);
|
351 |
+
|
352 |
+
const uint32_t i = (a % 100) << 1;
|
353 |
+
*buffer++ = gDigitsLut[i];
|
354 |
+
*buffer++ = gDigitsLut[i + 1];
|
355 |
+
}
|
356 |
+
else {
|
357 |
+
const uint32_t i = (a / 100) << 1;
|
358 |
+
const uint32_t j = (a % 100) << 1;
|
359 |
+
*buffer++ = gDigitsLut[i];
|
360 |
+
*buffer++ = gDigitsLut[i + 1];
|
361 |
+
*buffer++ = gDigitsLut[j];
|
362 |
+
*buffer++ = gDigitsLut[j + 1];
|
363 |
+
}
|
364 |
+
|
365 |
+
const uint32_t v0 = static_cast<uint32_t>(value / 100000000);
|
366 |
+
const uint32_t v1 = static_cast<uint32_t>(value % 100000000);
|
367 |
+
|
368 |
+
const __m128i a0 = Convert8DigitsSSE2(v0);
|
369 |
+
const __m128i a1 = Convert8DigitsSSE2(v1);
|
370 |
+
|
371 |
+
// Convert to bytes, add '0'
|
372 |
+
const __m128i va = _mm_add_epi8(_mm_packus_epi16(a0, a1), reinterpret_cast<const __m128i*>(kAsciiZero)[0]);
|
373 |
+
_mm_storeu_si128(reinterpret_cast<__m128i*>(buffer), va);
|
374 |
+
// buffer[16] = '\0';
|
375 |
+
return &buffer[16];
|
376 |
+
}
|
377 |
+
}
|
378 |
+
|
379 |
+
#else // Generic Non-x86 case
|
380 |
+
|
381 |
+
// Orignal name: u32toa_branchlut
|
382 |
+
char *ToString(uint32_t value, char* buffer) {
|
383 |
+
if (value < 10000) {
|
384 |
+
const uint32_t d1 = (value / 100) << 1;
|
385 |
+
const uint32_t d2 = (value % 100) << 1;
|
386 |
+
|
387 |
+
if (value >= 1000)
|
388 |
+
*buffer++ = gDigitsLut[d1];
|
389 |
+
if (value >= 100)
|
390 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
391 |
+
if (value >= 10)
|
392 |
+
*buffer++ = gDigitsLut[d2];
|
393 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
394 |
+
}
|
395 |
+
else if (value < 100000000) {
|
396 |
+
// value = bbbbcccc
|
397 |
+
const uint32_t b = value / 10000;
|
398 |
+
const uint32_t c = value % 10000;
|
399 |
+
|
400 |
+
const uint32_t d1 = (b / 100) << 1;
|
401 |
+
const uint32_t d2 = (b % 100) << 1;
|
402 |
+
|
403 |
+
const uint32_t d3 = (c / 100) << 1;
|
404 |
+
const uint32_t d4 = (c % 100) << 1;
|
405 |
+
|
406 |
+
if (value >= 10000000)
|
407 |
+
*buffer++ = gDigitsLut[d1];
|
408 |
+
if (value >= 1000000)
|
409 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
410 |
+
if (value >= 100000)
|
411 |
+
*buffer++ = gDigitsLut[d2];
|
412 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
413 |
+
|
414 |
+
*buffer++ = gDigitsLut[d3];
|
415 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
416 |
+
*buffer++ = gDigitsLut[d4];
|
417 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
418 |
+
}
|
419 |
+
else {
|
420 |
+
// value = aabbbbcccc in decimal
|
421 |
+
|
422 |
+
const uint32_t a = value / 100000000; // 1 to 42
|
423 |
+
value %= 100000000;
|
424 |
+
|
425 |
+
if (a >= 10) {
|
426 |
+
const unsigned i = a << 1;
|
427 |
+
*buffer++ = gDigitsLut[i];
|
428 |
+
*buffer++ = gDigitsLut[i + 1];
|
429 |
+
}
|
430 |
+
else
|
431 |
+
*buffer++ = '0' + static_cast<char>(a);
|
432 |
+
|
433 |
+
const uint32_t b = value / 10000; // 0 to 9999
|
434 |
+
const uint32_t c = value % 10000; // 0 to 9999
|
435 |
+
|
436 |
+
const uint32_t d1 = (b / 100) << 1;
|
437 |
+
const uint32_t d2 = (b % 100) << 1;
|
438 |
+
|
439 |
+
const uint32_t d3 = (c / 100) << 1;
|
440 |
+
const uint32_t d4 = (c % 100) << 1;
|
441 |
+
|
442 |
+
*buffer++ = gDigitsLut[d1];
|
443 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
444 |
+
*buffer++ = gDigitsLut[d2];
|
445 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
446 |
+
*buffer++ = gDigitsLut[d3];
|
447 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
448 |
+
*buffer++ = gDigitsLut[d4];
|
449 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
450 |
+
}
|
451 |
+
return buffer; //*buffer++ = '\0';
|
452 |
+
}
|
453 |
+
|
454 |
+
// Original name: u64toa_branchlut
|
455 |
+
char *ToString(uint64_t value, char* buffer) {
|
456 |
+
if (value < 100000000) {
|
457 |
+
uint32_t v = static_cast<uint32_t>(value);
|
458 |
+
if (v < 10000) {
|
459 |
+
const uint32_t d1 = (v / 100) << 1;
|
460 |
+
const uint32_t d2 = (v % 100) << 1;
|
461 |
+
|
462 |
+
if (v >= 1000)
|
463 |
+
*buffer++ = gDigitsLut[d1];
|
464 |
+
if (v >= 100)
|
465 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
466 |
+
if (v >= 10)
|
467 |
+
*buffer++ = gDigitsLut[d2];
|
468 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
469 |
+
}
|
470 |
+
else {
|
471 |
+
// value = bbbbcccc
|
472 |
+
const uint32_t b = v / 10000;
|
473 |
+
const uint32_t c = v % 10000;
|
474 |
+
|
475 |
+
const uint32_t d1 = (b / 100) << 1;
|
476 |
+
const uint32_t d2 = (b % 100) << 1;
|
477 |
+
|
478 |
+
const uint32_t d3 = (c / 100) << 1;
|
479 |
+
const uint32_t d4 = (c % 100) << 1;
|
480 |
+
|
481 |
+
if (value >= 10000000)
|
482 |
+
*buffer++ = gDigitsLut[d1];
|
483 |
+
if (value >= 1000000)
|
484 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
485 |
+
if (value >= 100000)
|
486 |
+
*buffer++ = gDigitsLut[d2];
|
487 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
488 |
+
|
489 |
+
*buffer++ = gDigitsLut[d3];
|
490 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
491 |
+
*buffer++ = gDigitsLut[d4];
|
492 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
493 |
+
}
|
494 |
+
}
|
495 |
+
else if (value < 10000000000000000) {
|
496 |
+
const uint32_t v0 = static_cast<uint32_t>(value / 100000000);
|
497 |
+
const uint32_t v1 = static_cast<uint32_t>(value % 100000000);
|
498 |
+
|
499 |
+
const uint32_t b0 = v0 / 10000;
|
500 |
+
const uint32_t c0 = v0 % 10000;
|
501 |
+
|
502 |
+
const uint32_t d1 = (b0 / 100) << 1;
|
503 |
+
const uint32_t d2 = (b0 % 100) << 1;
|
504 |
+
|
505 |
+
const uint32_t d3 = (c0 / 100) << 1;
|
506 |
+
const uint32_t d4 = (c0 % 100) << 1;
|
507 |
+
|
508 |
+
const uint32_t b1 = v1 / 10000;
|
509 |
+
const uint32_t c1 = v1 % 10000;
|
510 |
+
|
511 |
+
const uint32_t d5 = (b1 / 100) << 1;
|
512 |
+
const uint32_t d6 = (b1 % 100) << 1;
|
513 |
+
|
514 |
+
const uint32_t d7 = (c1 / 100) << 1;
|
515 |
+
const uint32_t d8 = (c1 % 100) << 1;
|
516 |
+
|
517 |
+
if (value >= 1000000000000000)
|
518 |
+
*buffer++ = gDigitsLut[d1];
|
519 |
+
if (value >= 100000000000000)
|
520 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
521 |
+
if (value >= 10000000000000)
|
522 |
+
*buffer++ = gDigitsLut[d2];
|
523 |
+
if (value >= 1000000000000)
|
524 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
525 |
+
if (value >= 100000000000)
|
526 |
+
*buffer++ = gDigitsLut[d3];
|
527 |
+
if (value >= 10000000000)
|
528 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
529 |
+
if (value >= 1000000000)
|
530 |
+
*buffer++ = gDigitsLut[d4];
|
531 |
+
if (value >= 100000000)
|
532 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
533 |
+
|
534 |
+
*buffer++ = gDigitsLut[d5];
|
535 |
+
*buffer++ = gDigitsLut[d5 + 1];
|
536 |
+
*buffer++ = gDigitsLut[d6];
|
537 |
+
*buffer++ = gDigitsLut[d6 + 1];
|
538 |
+
*buffer++ = gDigitsLut[d7];
|
539 |
+
*buffer++ = gDigitsLut[d7 + 1];
|
540 |
+
*buffer++ = gDigitsLut[d8];
|
541 |
+
*buffer++ = gDigitsLut[d8 + 1];
|
542 |
+
}
|
543 |
+
else {
|
544 |
+
const uint32_t a = static_cast<uint32_t>(value / 10000000000000000); // 1 to 1844
|
545 |
+
value %= 10000000000000000;
|
546 |
+
|
547 |
+
if (a < 10)
|
548 |
+
*buffer++ = '0' + static_cast<char>(a);
|
549 |
+
else if (a < 100) {
|
550 |
+
const uint32_t i = a << 1;
|
551 |
+
*buffer++ = gDigitsLut[i];
|
552 |
+
*buffer++ = gDigitsLut[i + 1];
|
553 |
+
}
|
554 |
+
else if (a < 1000) {
|
555 |
+
*buffer++ = '0' + static_cast<char>(a / 100);
|
556 |
+
|
557 |
+
const uint32_t i = (a % 100) << 1;
|
558 |
+
*buffer++ = gDigitsLut[i];
|
559 |
+
*buffer++ = gDigitsLut[i + 1];
|
560 |
+
}
|
561 |
+
else {
|
562 |
+
const uint32_t i = (a / 100) << 1;
|
563 |
+
const uint32_t j = (a % 100) << 1;
|
564 |
+
*buffer++ = gDigitsLut[i];
|
565 |
+
*buffer++ = gDigitsLut[i + 1];
|
566 |
+
*buffer++ = gDigitsLut[j];
|
567 |
+
*buffer++ = gDigitsLut[j + 1];
|
568 |
+
}
|
569 |
+
|
570 |
+
const uint32_t v0 = static_cast<uint32_t>(value / 100000000);
|
571 |
+
const uint32_t v1 = static_cast<uint32_t>(value % 100000000);
|
572 |
+
|
573 |
+
const uint32_t b0 = v0 / 10000;
|
574 |
+
const uint32_t c0 = v0 % 10000;
|
575 |
+
|
576 |
+
const uint32_t d1 = (b0 / 100) << 1;
|
577 |
+
const uint32_t d2 = (b0 % 100) << 1;
|
578 |
+
|
579 |
+
const uint32_t d3 = (c0 / 100) << 1;
|
580 |
+
const uint32_t d4 = (c0 % 100) << 1;
|
581 |
+
|
582 |
+
const uint32_t b1 = v1 / 10000;
|
583 |
+
const uint32_t c1 = v1 % 10000;
|
584 |
+
|
585 |
+
const uint32_t d5 = (b1 / 100) << 1;
|
586 |
+
const uint32_t d6 = (b1 % 100) << 1;
|
587 |
+
|
588 |
+
const uint32_t d7 = (c1 / 100) << 1;
|
589 |
+
const uint32_t d8 = (c1 % 100) << 1;
|
590 |
+
|
591 |
+
*buffer++ = gDigitsLut[d1];
|
592 |
+
*buffer++ = gDigitsLut[d1 + 1];
|
593 |
+
*buffer++ = gDigitsLut[d2];
|
594 |
+
*buffer++ = gDigitsLut[d2 + 1];
|
595 |
+
*buffer++ = gDigitsLut[d3];
|
596 |
+
*buffer++ = gDigitsLut[d3 + 1];
|
597 |
+
*buffer++ = gDigitsLut[d4];
|
598 |
+
*buffer++ = gDigitsLut[d4 + 1];
|
599 |
+
*buffer++ = gDigitsLut[d5];
|
600 |
+
*buffer++ = gDigitsLut[d5 + 1];
|
601 |
+
*buffer++ = gDigitsLut[d6];
|
602 |
+
*buffer++ = gDigitsLut[d6 + 1];
|
603 |
+
*buffer++ = gDigitsLut[d7];
|
604 |
+
*buffer++ = gDigitsLut[d7 + 1];
|
605 |
+
*buffer++ = gDigitsLut[d8];
|
606 |
+
*buffer++ = gDigitsLut[d8 + 1];
|
607 |
+
}
|
608 |
+
return buffer;
|
609 |
+
}
|
610 |
+
|
611 |
+
#endif // End of architecture if statement.
|
612 |
+
|
613 |
+
// Signed wrappers. The negation is done on the unsigned version because
|
614 |
+
// doing so has defined behavior for INT_MIN.
|
615 |
+
char *ToString(int32_t value, char *to) {
|
616 |
+
uint32_t un = static_cast<uint32_t>(value);
|
617 |
+
if (value < 0) {
|
618 |
+
*to++ = '-';
|
619 |
+
un = -un;
|
620 |
+
}
|
621 |
+
return ToString(un, to);
|
622 |
+
}
|
623 |
+
|
624 |
+
char *ToString(int64_t value, char *to) {
|
625 |
+
uint64_t un = static_cast<uint64_t>(value);
|
626 |
+
if (value < 0) {
|
627 |
+
*to++ = '-';
|
628 |
+
un = -un;
|
629 |
+
}
|
630 |
+
return ToString(un, to);
|
631 |
+
}
|
632 |
+
|
633 |
+
// No optimization for this case yet.
|
634 |
+
char *ToString(int16_t value, char *to) {
|
635 |
+
return ToString((int32_t)value, to);
|
636 |
+
}
|
637 |
+
char *ToString(uint16_t value, char *to) {
|
638 |
+
return ToString((uint32_t)value, to);
|
639 |
+
}
|
640 |
+
|
641 |
+
// void * to string. This hasn't been optimized at all really.
|
642 |
+
namespace {
|
643 |
+
const char kHexDigits[] = "0123456789abcdef";
|
644 |
+
} // namespace
|
645 |
+
|
646 |
+
char *ToString(const void *v, char *to) {
|
647 |
+
*to++ = '0';
|
648 |
+
*to++ = 'x';
|
649 |
+
|
650 |
+
// Fun fact: gcc/clang boost::lexical_cast on Linux do just "0" while clang on OS X does "0x0"
|
651 |
+
// I happen to prefer 0x0.
|
652 |
+
if (!v) {
|
653 |
+
*to++ = '0';
|
654 |
+
return to;
|
655 |
+
}
|
656 |
+
|
657 |
+
uintptr_t value = reinterpret_cast<uintptr_t>(v);
|
658 |
+
uint8_t shift = sizeof(void*) * 8 - 4;
|
659 |
+
for (; !(value >> shift); shift -= 4) {}
|
660 |
+
for (; ; shift -= 4) {
|
661 |
+
*to++ = kHexDigits[(value >> shift) & 0xf];
|
662 |
+
if (!shift) break;
|
663 |
+
}
|
664 |
+
return to;
|
665 |
+
}
|
666 |
+
|
667 |
+
} // namespace util
|
cc-multilingual-main/cc_net/third_party/kenlm/util/murmur_hash.hh
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_MURMUR_HASH_H
|
2 |
+
#define UTIL_MURMUR_HASH_H
|
3 |
+
#include <cstddef>
|
4 |
+
#include <stdint.h>
|
5 |
+
|
6 |
+
namespace util {
|
7 |
+
|
8 |
+
// 64-bit machine version
|
9 |
+
uint64_t MurmurHash64A(const void * key, std::size_t len, uint64_t seed = 0);
|
10 |
+
// 32-bit machine version (not the same function as above)
|
11 |
+
uint64_t MurmurHash64B(const void * key, std::size_t len, uint64_t seed = 0);
|
12 |
+
// Use the version for this arch. Because the values differ across
|
13 |
+
// architectures, really only use it for in-memory structures.
|
14 |
+
uint64_t MurmurHashNative(const void * key, std::size_t len, uint64_t seed = 0);
|
15 |
+
|
16 |
+
} // namespace util
|
17 |
+
|
18 |
+
#endif // UTIL_MURMUR_HASH_H
|
cc-multilingual-main/cc_net/third_party/kenlm/util/parallel_read.hh
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_PARALLEL_READ__
|
2 |
+
#define UTIL_PARALLEL_READ__
|
3 |
+
|
4 |
+
/* Read pieces of a file in parallel. This has a very specific use case:
|
5 |
+
* reading files from Lustre is CPU bound so multiple threads actually
|
6 |
+
* increases throughput. Speed matters when an LM takes a terabyte.
|
7 |
+
*/
|
8 |
+
|
9 |
+
#include <cstddef>
|
10 |
+
#include <stdint.h>
|
11 |
+
|
12 |
+
namespace util {
|
13 |
+
void ParallelRead(int fd, void *to, std::size_t amount, uint64_t offset);
|
14 |
+
} // namespace util
|
15 |
+
|
16 |
+
#endif // UTIL_PARALLEL_READ__
|
cc-multilingual-main/cc_net/third_party/kenlm/util/probing_hash_table_benchmark_main.cc
ADDED
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "file.hh"
|
2 |
+
#include "probing_hash_table.hh"
|
3 |
+
#include "mmap.hh"
|
4 |
+
#include "usage.hh"
|
5 |
+
#include "thread_pool.hh"
|
6 |
+
#include <boost/thread/mutex.hpp>
|
7 |
+
#include <boost/thread/locks.hpp>
|
8 |
+
|
9 |
+
#ifdef WIN32
|
10 |
+
#include <windows.h>
|
11 |
+
#include <processthreadsapi.h>
|
12 |
+
#else
|
13 |
+
#include <sys/resource.h>
|
14 |
+
#include <sys/time.h>
|
15 |
+
#endif
|
16 |
+
|
17 |
+
#include <iostream>
|
18 |
+
|
19 |
+
namespace util {
|
20 |
+
namespace {
|
21 |
+
|
22 |
+
struct Entry {
|
23 |
+
typedef uint64_t Key;
|
24 |
+
Key key;
|
25 |
+
Key GetKey() const { return key; }
|
26 |
+
};
|
27 |
+
|
28 |
+
// I don't care if this doesn't run on Windows. Empirically /dev/urandom was faster than boost::random's Mersenne Twister.
|
29 |
+
class URandom {
|
30 |
+
public:
|
31 |
+
URandom() :
|
32 |
+
it_(buf_ + 1024), end_(buf_ + 1024),
|
33 |
+
file_(util::OpenReadOrThrow("/dev/urandom")) {}
|
34 |
+
|
35 |
+
uint64_t Get() {
|
36 |
+
if (it_ == end_) {
|
37 |
+
it_ = buf_;
|
38 |
+
util::ReadOrThrow(file_.get(), buf_, sizeof(buf_));
|
39 |
+
it_ = buf_;
|
40 |
+
}
|
41 |
+
return *it_++;
|
42 |
+
}
|
43 |
+
|
44 |
+
void Batch(uint64_t *begin, uint64_t *end) {
|
45 |
+
util::ReadOrThrow(file_.get(), begin, (end - begin) * sizeof(uint64_t));
|
46 |
+
}
|
47 |
+
|
48 |
+
private:
|
49 |
+
uint64_t buf_[1024];
|
50 |
+
uint64_t *it_, *end_;
|
51 |
+
|
52 |
+
util::scoped_fd file_;
|
53 |
+
};
|
54 |
+
|
55 |
+
struct PrefetchEntry {
|
56 |
+
uint64_t key;
|
57 |
+
const Entry *pointer;
|
58 |
+
};
|
59 |
+
|
60 |
+
template <class TableT, unsigned PrefetchSize> class PrefetchQueue {
|
61 |
+
public:
|
62 |
+
typedef TableT Table;
|
63 |
+
|
64 |
+
explicit PrefetchQueue(Table &table) : table_(table), cur_(0), twiddle_(false) {
|
65 |
+
for (PrefetchEntry *i = entries_; i != entries_ + PrefetchSize; ++i)
|
66 |
+
i->pointer = NULL;
|
67 |
+
}
|
68 |
+
|
69 |
+
void Add(uint64_t key) {
|
70 |
+
if (Cur().pointer) {
|
71 |
+
twiddle_ ^= table_.FindFromIdeal(Cur().key, Cur().pointer);
|
72 |
+
}
|
73 |
+
Cur().key = key;
|
74 |
+
Cur().pointer = table_.Ideal(key);
|
75 |
+
__builtin_prefetch(Cur().pointer, 0, 0);
|
76 |
+
Next();
|
77 |
+
}
|
78 |
+
|
79 |
+
bool Drain() {
|
80 |
+
if (Cur().pointer) {
|
81 |
+
for (PrefetchEntry *i = &Cur(); i < entries_ + PrefetchSize; ++i) {
|
82 |
+
twiddle_ ^= table_.FindFromIdeal(i->key, i->pointer);
|
83 |
+
}
|
84 |
+
}
|
85 |
+
for (PrefetchEntry *i = entries_; i < &Cur(); ++i) {
|
86 |
+
twiddle_ ^= table_.FindFromIdeal(i->key, i->pointer);
|
87 |
+
}
|
88 |
+
return twiddle_;
|
89 |
+
}
|
90 |
+
|
91 |
+
private:
|
92 |
+
PrefetchEntry &Cur() { return entries_[cur_]; }
|
93 |
+
void Next() {
|
94 |
+
++cur_;
|
95 |
+
cur_ = cur_ % PrefetchSize;
|
96 |
+
}
|
97 |
+
|
98 |
+
Table &table_;
|
99 |
+
PrefetchEntry entries_[PrefetchSize];
|
100 |
+
std::size_t cur_;
|
101 |
+
|
102 |
+
bool twiddle_;
|
103 |
+
|
104 |
+
PrefetchQueue(const PrefetchQueue&);
|
105 |
+
void operator=(const PrefetchQueue&);
|
106 |
+
};
|
107 |
+
|
108 |
+
template <class TableT> class Immediate {
|
109 |
+
public:
|
110 |
+
typedef TableT Table;
|
111 |
+
|
112 |
+
explicit Immediate(Table &table) : table_(table), twiddle_(false) {}
|
113 |
+
|
114 |
+
void Add(uint64_t key) {
|
115 |
+
typename Table::ConstIterator it;
|
116 |
+
twiddle_ ^= table_.Find(key, it);
|
117 |
+
}
|
118 |
+
|
119 |
+
bool Drain() const { return twiddle_; }
|
120 |
+
|
121 |
+
private:
|
122 |
+
Table &table_;
|
123 |
+
bool twiddle_;
|
124 |
+
};
|
125 |
+
|
126 |
+
std::size_t Size(uint64_t entries, float multiplier = 1.5) {
|
127 |
+
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
|
128 |
+
// Always round up to power of 2 for fair comparison.
|
129 |
+
return Power2Mod::RoundBuckets(Table::Size(entries, multiplier) / sizeof(Entry)) * sizeof(Entry);
|
130 |
+
}
|
131 |
+
|
132 |
+
template <class Queue> bool Test(URandom &rn, uint64_t entries, const uint64_t *const queries_begin, const uint64_t *const queries_end, bool ordinary_malloc, float multiplier = 1.5) {
|
133 |
+
std::size_t size = Size(entries, multiplier);
|
134 |
+
scoped_memory backing;
|
135 |
+
if (ordinary_malloc) {
|
136 |
+
backing.reset(util::CallocOrThrow(size), size, scoped_memory::MALLOC_ALLOCATED);
|
137 |
+
} else {
|
138 |
+
util::HugeMalloc(size, true, backing);
|
139 |
+
}
|
140 |
+
typename Queue::Table table(backing.get(), size);
|
141 |
+
|
142 |
+
double start = CPUTime();
|
143 |
+
for (uint64_t i = 0; i < entries; ++i) {
|
144 |
+
Entry entry;
|
145 |
+
entry.key = rn.Get();
|
146 |
+
table.Insert(entry);
|
147 |
+
}
|
148 |
+
double inserted = CPUTime() - start;
|
149 |
+
double before_lookup = CPUTime();
|
150 |
+
Queue queue(table);
|
151 |
+
for (const uint64_t *i = queries_begin; i != queries_end; ++i) {
|
152 |
+
queue.Add(*i);
|
153 |
+
}
|
154 |
+
bool meaningless = queue.Drain();
|
155 |
+
std::cout << ' ' << (inserted / static_cast<double>(entries)) << ' ' << (CPUTime() - before_lookup) / static_cast<double>(queries_end - queries_begin) << std::flush;
|
156 |
+
return meaningless;
|
157 |
+
}
|
158 |
+
|
159 |
+
bool TestRun(uint64_t lookups = 20000000, float multiplier = 1.5) {
|
160 |
+
URandom rn;
|
161 |
+
util::scoped_memory queries;
|
162 |
+
HugeMalloc(lookups * sizeof(uint64_t), true, queries);
|
163 |
+
rn.Batch(static_cast<uint64_t*>(queries.get()), static_cast<uint64_t*>(queries.get()) + lookups);
|
164 |
+
uint64_t physical_mem_limit = util::GuessPhysicalMemory() / 2;
|
165 |
+
bool meaningless = true;
|
166 |
+
for (uint64_t i = 4; Size(i / multiplier) < physical_mem_limit; i *= 4) {
|
167 |
+
std::cout << static_cast<std::size_t>(i / multiplier) << ' ' << Size(i / multiplier);
|
168 |
+
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
|
169 |
+
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, DivMod> TableDiv;
|
170 |
+
const uint64_t *const queries_begin = static_cast<const uint64_t*>(queries.get());
|
171 |
+
meaningless ^= util::Test<Immediate<TableDiv> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
|
172 |
+
meaningless ^= util::Test<Immediate<Table> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
|
173 |
+
meaningless ^= util::Test<PrefetchQueue<Table, 4> >(rn, i / multiplier, queries_begin, queries_begin + lookups, true, multiplier);
|
174 |
+
meaningless ^= util::Test<Immediate<Table> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
|
175 |
+
meaningless ^= util::Test<PrefetchQueue<Table, 2> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
|
176 |
+
meaningless ^= util::Test<PrefetchQueue<Table, 4> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
|
177 |
+
meaningless ^= util::Test<PrefetchQueue<Table, 8> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
|
178 |
+
meaningless ^= util::Test<PrefetchQueue<Table, 16> >(rn, i / multiplier, queries_begin, queries_begin + lookups, false, multiplier);
|
179 |
+
std::cout << std::endl;
|
180 |
+
}
|
181 |
+
return meaningless;
|
182 |
+
}
|
183 |
+
|
184 |
+
template<class Table>
|
185 |
+
struct ParallelTestRequest{
|
186 |
+
ParallelTestRequest() : queries_begin_(NULL), queries_end_(NULL), table_(NULL) {}
|
187 |
+
ParallelTestRequest(const uint64_t *queries_begin, const uint64_t *queries_end, Table *table) :
|
188 |
+
queries_begin_(queries_begin),
|
189 |
+
queries_end_(queries_end),
|
190 |
+
table_(table) {}
|
191 |
+
bool operator==(const ParallelTestRequest &rhs) const {
|
192 |
+
return this->queries_begin_ == rhs.queries_begin_ && this->queries_end_ == rhs.queries_end_;
|
193 |
+
}
|
194 |
+
const uint64_t *queries_begin_;
|
195 |
+
const uint64_t *queries_end_;
|
196 |
+
Table * table_;
|
197 |
+
};
|
198 |
+
|
199 |
+
template <class TableT>
|
200 |
+
struct ParallelTestConstruct{
|
201 |
+
ParallelTestConstruct(boost::mutex& lock, const uint64_t* const burn_begin, const uint64_t* const burn_end, TableT* table) : lock_(lock), burn_begin_(burn_begin), burn_end_(burn_end), table_(table){}
|
202 |
+
boost::mutex& lock_;
|
203 |
+
const uint64_t* const burn_begin_;
|
204 |
+
const uint64_t* const burn_end_;
|
205 |
+
TableT* table_;
|
206 |
+
};
|
207 |
+
|
208 |
+
template<class Queue>
|
209 |
+
struct ParallelTestHandler{
|
210 |
+
typedef ParallelTestRequest<typename Queue::Table> Request;
|
211 |
+
explicit ParallelTestHandler(const ParallelTestConstruct<typename Queue::Table>& construct) : lock_(construct.lock_), totalTime_(0.0), nRequests_(0), nQueries_(0), error_(false), twiddle_(false){
|
212 |
+
//perform initial burn
|
213 |
+
for(const uint64_t* i = construct.burn_begin_; i < construct.burn_end_; i++){
|
214 |
+
typename Queue::Table::ConstIterator it;
|
215 |
+
twiddle_ ^= construct.table_->Find(*i, it);
|
216 |
+
}
|
217 |
+
}
|
218 |
+
void operator()(Request request){
|
219 |
+
if (error_) return;
|
220 |
+
Queue queue(*request.table_);
|
221 |
+
double start = ThreadTime();
|
222 |
+
if(start < 0.0){
|
223 |
+
error_ = true;
|
224 |
+
return;
|
225 |
+
}
|
226 |
+
for(const uint64_t *i = request.queries_begin_; i != request.queries_end_; ++i){
|
227 |
+
queue.Add(*i);
|
228 |
+
}
|
229 |
+
twiddle_ ^= queue.Drain();
|
230 |
+
double end = ThreadTime();
|
231 |
+
if(end < 0.0){
|
232 |
+
error_ = true;
|
233 |
+
return;
|
234 |
+
}
|
235 |
+
totalTime_ += end - start;
|
236 |
+
nQueries_ += request.queries_end_ - request.queries_begin_;
|
237 |
+
++nRequests_;
|
238 |
+
}
|
239 |
+
virtual ~ParallelTestHandler() {
|
240 |
+
boost::unique_lock<boost::mutex> produce_lock(lock_);
|
241 |
+
if (error_){
|
242 |
+
std::cout << "Error ";
|
243 |
+
}
|
244 |
+
else {
|
245 |
+
std::cout << nRequests_ << ' ' << ' ' << nQueries_ << ' ' << totalTime_ << std::endl;
|
246 |
+
}
|
247 |
+
std::cerr << "Meaningless " << twiddle_ << std::endl;
|
248 |
+
}
|
249 |
+
private:
|
250 |
+
boost::mutex &lock_;
|
251 |
+
double totalTime_;
|
252 |
+
std::size_t nRequests_;
|
253 |
+
std::size_t nQueries_;
|
254 |
+
bool error_;
|
255 |
+
bool twiddle_;
|
256 |
+
};
|
257 |
+
|
258 |
+
template<class Queue>
|
259 |
+
void ParallelTest(typename Queue::Table* table, const uint64_t *const queries_begin,
|
260 |
+
const uint64_t *const queries_end, std::size_t num_threads,
|
261 |
+
std::size_t tasks_per_thread, std::size_t burn){
|
262 |
+
boost::mutex lock;
|
263 |
+
ParallelTestConstruct<typename Queue::Table> construct(lock, queries_begin, queries_begin + burn, table);
|
264 |
+
ParallelTestRequest<typename Queue::Table> poison(NULL, NULL, NULL);
|
265 |
+
{
|
266 |
+
util::ThreadPool<ParallelTestHandler<Queue> > pool(num_threads, num_threads, construct, poison);
|
267 |
+
const uint64_t queries_per_thread =(static_cast<uint64_t>(queries_end-queries_begin-burn)/num_threads)/tasks_per_thread;
|
268 |
+
for (const uint64_t *i = queries_begin+burn; i + queries_per_thread <= queries_end; i += queries_per_thread){
|
269 |
+
ParallelTestRequest<typename Queue::Table> request(i, i+queries_per_thread, table);
|
270 |
+
pool.Produce(request);
|
271 |
+
}
|
272 |
+
} // pool gets deallocated and all jobs finish
|
273 |
+
std::cout << std::endl;
|
274 |
+
}
|
275 |
+
|
276 |
+
void ParallelTestRun(std::size_t tasks_per_thread = 1, std::size_t burn = 4000, uint64_t lookups = 20000000, float multiplier = 1.5) {
|
277 |
+
URandom rn;
|
278 |
+
util::scoped_memory queries;
|
279 |
+
HugeMalloc((lookups + burn)* sizeof(uint64_t), true, queries);
|
280 |
+
rn.Batch(static_cast<uint64_t*>(queries.get()), static_cast<uint64_t*>(queries.get()) + lookups + burn);
|
281 |
+
const uint64_t *const queries_begin = static_cast<const uint64_t*>(queries.get());
|
282 |
+
const uint64_t *const queries_end = queries_begin + lookups + burn;
|
283 |
+
typedef util::ProbingHashTable<Entry, util::IdentityHash, std::equal_to<Entry::Key>, Power2Mod> Table;
|
284 |
+
uint64_t physical_mem_limit = util::GuessPhysicalMemory() / 2;
|
285 |
+
for (uint64_t i = 4; Size(i / multiplier, multiplier) < physical_mem_limit; i *= 4) {
|
286 |
+
std::size_t entries = static_cast<std::size_t>(i / multiplier);
|
287 |
+
std::size_t size = Size(i/multiplier, multiplier);
|
288 |
+
scoped_memory backing;
|
289 |
+
util::HugeMalloc(size, true, backing);
|
290 |
+
Table table(backing.get(), size);
|
291 |
+
for (uint64_t j = 0; j < entries; ++j) {
|
292 |
+
Entry entry;
|
293 |
+
entry.key = rn.Get();
|
294 |
+
table.Insert(entry);
|
295 |
+
}
|
296 |
+
for(std::size_t num_threads = 1; num_threads <= 16; num_threads*=2){
|
297 |
+
std::cout << entries << ' ' << size << ' ' << num_threads << ' ' << std::endl;
|
298 |
+
util::ParallelTest<Immediate<Table> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
|
299 |
+
util::ParallelTest<PrefetchQueue<Table, 2> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
|
300 |
+
util::ParallelTest<PrefetchQueue<Table, 4> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
|
301 |
+
util::ParallelTest<PrefetchQueue<Table, 8> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
|
302 |
+
util::ParallelTest<PrefetchQueue<Table, 16> >(&table, queries_begin, queries_end, num_threads, tasks_per_thread, burn);
|
303 |
+
}
|
304 |
+
}
|
305 |
+
}
|
306 |
+
|
307 |
+
} // namespace
|
308 |
+
} // namespace util
|
309 |
+
|
310 |
+
int main() {
|
311 |
+
//bool meaningless = false;
|
312 |
+
std::cout << "#CPU time\n";
|
313 |
+
//meaningless ^= util::TestRun();
|
314 |
+
util::ParallelTestRun(10, 4000);
|
315 |
+
//std::cerr << "Meaningless: " << meaningless << '\n';
|
316 |
+
}
|
cc-multilingual-main/cc_net/third_party/kenlm/util/read_compressed_test.cc
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "read_compressed.hh"
|
2 |
+
|
3 |
+
#include "file.hh"
|
4 |
+
#include "have.hh"
|
5 |
+
|
6 |
+
#define BOOST_TEST_MODULE ReadCompressedTest
|
7 |
+
#include <boost/test/unit_test.hpp>
|
8 |
+
#include <boost/scoped_ptr.hpp>
|
9 |
+
|
10 |
+
#include <fstream>
|
11 |
+
#include <string>
|
12 |
+
#include <cstdlib>
|
13 |
+
|
14 |
+
#if defined __MINGW32__
|
15 |
+
#include <ctime>
|
16 |
+
#include <fcntl.h>
|
17 |
+
|
18 |
+
#if !defined mkstemp
|
19 |
+
// TODO insecure
|
20 |
+
int mkstemp(char * stemplate)
|
21 |
+
{
|
22 |
+
char *filename = mktemp(stemplate);
|
23 |
+
if (filename == NULL)
|
24 |
+
return -1;
|
25 |
+
return open(filename, O_RDWR | O_CREAT, 0600);
|
26 |
+
}
|
27 |
+
#endif
|
28 |
+
|
29 |
+
#endif // defined
|
30 |
+
|
31 |
+
namespace util {
|
32 |
+
namespace {
|
33 |
+
|
34 |
+
void ReadLoop(ReadCompressed &reader, void *to_void, std::size_t amount) {
|
35 |
+
uint8_t *to = static_cast<uint8_t*>(to_void);
|
36 |
+
while (amount) {
|
37 |
+
std::size_t ret = reader.Read(to, amount);
|
38 |
+
BOOST_REQUIRE(ret);
|
39 |
+
to += ret;
|
40 |
+
amount -= ret;
|
41 |
+
}
|
42 |
+
}
|
43 |
+
|
44 |
+
const uint32_t kSize4 = 100000 / 4;
|
45 |
+
|
46 |
+
std::string WriteRandom() {
|
47 |
+
char name[] = "tempXXXXXX";
|
48 |
+
scoped_fd original(mkstemp(name));
|
49 |
+
BOOST_REQUIRE(original.get() > 0);
|
50 |
+
for (uint32_t i = 0; i < kSize4; ++i) {
|
51 |
+
WriteOrThrow(original.get(), &i, sizeof(uint32_t));
|
52 |
+
}
|
53 |
+
return name;
|
54 |
+
}
|
55 |
+
|
56 |
+
void VerifyRead(ReadCompressed &reader) {
|
57 |
+
for (uint32_t i = 0; i < kSize4; ++i) {
|
58 |
+
uint32_t got;
|
59 |
+
ReadLoop(reader, &got, sizeof(uint32_t));
|
60 |
+
BOOST_CHECK_EQUAL(i, got);
|
61 |
+
}
|
62 |
+
|
63 |
+
char ignored;
|
64 |
+
BOOST_CHECK_EQUAL((std::size_t)0, reader.Read(&ignored, 1));
|
65 |
+
// Test double EOF call.
|
66 |
+
BOOST_CHECK_EQUAL((std::size_t)0, reader.Read(&ignored, 1));
|
67 |
+
}
|
68 |
+
|
69 |
+
void TestRandom(const char *compressor) {
|
70 |
+
std::string name(WriteRandom());
|
71 |
+
|
72 |
+
char gzname[] = "tempXXXXXX";
|
73 |
+
scoped_fd gzipped(mkstemp(gzname));
|
74 |
+
|
75 |
+
std::string command(compressor);
|
76 |
+
#ifdef __CYGWIN__
|
77 |
+
command += ".exe";
|
78 |
+
#endif
|
79 |
+
command += " <\"";
|
80 |
+
command += name;
|
81 |
+
command += "\" >\"";
|
82 |
+
command += gzname;
|
83 |
+
command += "\"";
|
84 |
+
BOOST_REQUIRE_EQUAL(0, system(command.c_str()));
|
85 |
+
|
86 |
+
BOOST_CHECK_EQUAL(0, unlink(name.c_str()));
|
87 |
+
BOOST_CHECK_EQUAL(0, unlink(gzname));
|
88 |
+
|
89 |
+
ReadCompressed reader(gzipped.release());
|
90 |
+
VerifyRead(reader);
|
91 |
+
}
|
92 |
+
|
93 |
+
BOOST_AUTO_TEST_CASE(Uncompressed) {
|
94 |
+
TestRandom("cat");
|
95 |
+
}
|
96 |
+
|
97 |
+
#ifdef HAVE_ZLIB
|
98 |
+
BOOST_AUTO_TEST_CASE(ReadGZ) {
|
99 |
+
TestRandom("gzip");
|
100 |
+
}
|
101 |
+
#endif // HAVE_ZLIB
|
102 |
+
|
103 |
+
#ifdef HAVE_BZLIB
|
104 |
+
BOOST_AUTO_TEST_CASE(ReadBZ) {
|
105 |
+
TestRandom("bzip2");
|
106 |
+
}
|
107 |
+
#endif // HAVE_BZLIB
|
108 |
+
|
109 |
+
#ifdef HAVE_XZLIB
|
110 |
+
BOOST_AUTO_TEST_CASE(ReadXZ) {
|
111 |
+
TestRandom("xz");
|
112 |
+
}
|
113 |
+
#endif
|
114 |
+
|
115 |
+
#ifdef HAVE_ZLIB
|
116 |
+
BOOST_AUTO_TEST_CASE(AppendGZ) {
|
117 |
+
}
|
118 |
+
#endif
|
119 |
+
|
120 |
+
BOOST_AUTO_TEST_CASE(IStream) {
|
121 |
+
std::string name(WriteRandom());
|
122 |
+
std::fstream stream(name.c_str(), std::ios::in);
|
123 |
+
BOOST_CHECK_EQUAL(0, unlink(name.c_str()));
|
124 |
+
ReadCompressed reader;
|
125 |
+
reader.Reset(stream);
|
126 |
+
VerifyRead(reader);
|
127 |
+
}
|
128 |
+
|
129 |
+
} // namespace
|
130 |
+
} // namespace util
|
cc-multilingual-main/cc_net/third_party/kenlm/util/spaces.cc
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "spaces.hh"
|
2 |
+
|
3 |
+
namespace util {
|
4 |
+
|
5 |
+
// Sigh this is the only way I could come up with to do a _const_ bool. It has ' ', '\f', '\n', '\r', '\t', and '\v' (same as isspace on C locale).
|
6 |
+
const bool kSpaces[256] = {0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
|
7 |
+
|
8 |
+
} // namespace util
|
cc-multilingual-main/cc_net/third_party/kenlm/util/spaces.hh
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#ifndef UTIL_SPACES_H
|
2 |
+
#define UTIL_SPACES_H
|
3 |
+
|
4 |
+
// bool array of spaces.
|
5 |
+
|
6 |
+
namespace util {
|
7 |
+
|
8 |
+
extern const bool kSpaces[256];
|
9 |
+
|
10 |
+
} // namespace util
|
11 |
+
|
12 |
+
#endif // UTIL_SPACES_H
|