forked from ciphrex/mSIGNA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnumberformats.cpp
118 lines (102 loc) · 2.83 KB
/
numberformats.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
///////////////////////////////////////////////////////////////////////////////
//
// mSIGNA
//
// numberformats.cpp
//
// Copyright (c) 2013-2014 Eric Lombrozo
//
// All Rights Reserved.
#include "numberformats.h"
#include <sstream>
#include <stdint.h>
#include <stdexcept>
using namespace std;
string getDecimalRegExpString(uint64_t maxAmount, unsigned int maxDecimals, char decimalSymbol)
{
stringstream ss;
ss << "(([1-9]\\d{0,6}|1\\d{7}|20\\d{6}|0|)(\\" << decimalSymbol << "\\d{0,8})?|21000000(\\" << decimalSymbol << "0{0,8})?)";
return ss.str();
}
// Example for maxValue = 21000000 and maxDecimals = 8
// const QRegExp AMOUNT_REGEXP("((|0|[1-9]\\d{0,6}|1\\d{7}|20\\d{6})(\\.\\d{0,8})?|21000000(\\.0{0,8})?)");
/*
string nDigitsRegExpString(unsigned int n)
{
if (n == 0) return "";
if (n == 1) return "\\d";
stringstream ss;
ss << "\\d{" << n << "};
return ss.str();
}
string zeroToNDigitsRegExp(unsigned n)
{
if (n == 0) return "";
stringstream ss;
ss << "\\d{0," << n << "}";
return ss.str();
}
string getDecimalRegExpString(uint64_t maxAmount, unsigned int maxDecimals)
{
stringstream ssRegExp;
if (maxAmount > 0 && maxDecimals > 0) { ssRegExp << "("; }
ssRegExp << "(";
uint64_t i = maxAmount;
if (i > 1 && i % 10 != 0)
{
if (maxDecimals > 0) { i--; }
ssRegExp << i << "|";
}
i = maxAmount / 10;
unsigned int trailingDigits = 1;
while (i > 10)
{
if (i % 10 != 0)
{
ssRegExp << (maxAmount - 1) << nDigitsRegExpString(trailingDigits) << "|";
}
i /= 10;
trailingDigits++;
}
if (
return ssRegExp.str();
}
*/
// Constrain input to valid values
uint64_t decimalStringToInteger(const string& decimalString, uint64_t maxAmount, uint64_t divisor, unsigned int maxDecimals)
{
uint64_t whole = 0;
uint64_t frac = 0;
unsigned int decimals = 0;
bool stateWhole = true;
for (auto& c: decimalString) {
if (stateWhole) {
if (c == '.') {
stateWhole = false;
continue;
}
else if (whole > maxAmount || c < '0' || c > '9') {
throw std::runtime_error("Invalid amount.");
}
whole *= 10;
whole += (uint64_t)(c - '0');
}
else {
decimals++;
if (decimals > maxDecimals || c < '0' || c > '9') {
throw std::runtime_error("Invalid amount.");
}
frac *= 10;
frac += (uint64_t)(c - '0');
}
}
if (frac > 0) {
while (decimals < maxDecimals) {
decimals++;
frac *= 10;
}
}
uint64_t value = (uint64_t)whole * divisor + frac;
if (value > (maxAmount * divisor)) throw std::runtime_error("Invalid amount.");
return value;
}