-
Notifications
You must be signed in to change notification settings - Fork 0
/
string_utils.js
234 lines (215 loc) · 7.79 KB
/
string_utils.js
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*jslint node: true */
"use strict";
var STRING_JOIN_CHAR = "\x00";
/**
* Converts the argument into a string by mapping data types to a prefixed string and concatenating all fields together.
* @param obj the value to be converted into a string
* @returns {string} the string version of the value
*/
function getSourceString(obj) {
var arrComponents = [];
function extractComponents(variable){
if (variable === null)
throw Error("null value in "+JSON.stringify(obj));
switch (typeof variable){
case "string":
arrComponents.push("s", variable);
break;
case "number":
if (!isFinite(variable))
throw Error("invalid number: " + variable);
arrComponents.push("n", variable.toString());
break;
case "boolean":
arrComponents.push("b", variable.toString());
break;
case "object":
if (Array.isArray(variable)){
if (variable.length === 0)
throw Error("empty array in "+JSON.stringify(obj));
arrComponents.push('[');
for (var i=0; i<variable.length; i++)
extractComponents(variable[i]);
arrComponents.push(']');
}
else{
var keys = Object.keys(variable).sort();
if (keys.length === 0)
throw Error("empty object in "+JSON.stringify(obj));
keys.forEach(function(key){
if (typeof variable[key] === "undefined")
throw Error("undefined at "+key+" of "+JSON.stringify(obj));
arrComponents.push(key);
extractComponents(variable[key]);
});
}
break;
default:
throw Error("getSourceString: unknown type="+(typeof variable)+" of "+variable+", object: "+JSON.stringify(obj));
}
}
extractComponents(obj);
return arrComponents.join(STRING_JOIN_CHAR);
}
function encodeMci(mci){
return (0xFFFFFFFF - mci).toString(16).padStart(8, '0'); // reverse order for more efficient sorting as we always need the latest
}
function getMciFromDataFeedKey(key){
var arrParts = key.split('\n');
var strReversedMci = arrParts[arrParts.length-1];
var reversed_mci = parseInt(strReversedMci, 16);
var mci = 0xFFFFFFFF - reversed_mci;
return mci;
}
// df:address:feed_name:type:value:strReversedMci
function getValueFromDataFeedKey(key){
var m = key.split('\n');
if (m.length !== 6)
throw Error("wrong number of elements in data feed "+key);
var type = m[3];
var value = m[4];
return (type === 's') ? value : decodeLexicographicToDouble(value);
}
// returns a number if the value looks like a valid float
function toNumber(value, bLimitedPrecision) {
if (typeof value === 'number')
return value;
if (bLimitedPrecision)
return getNumericFeedValue(value);
if (typeof value !== 'string')
throw Error("toNumber of not a string: "+value);
var m = value.match(/^[+-]?(\d+(\.\d+)?)([eE][+-]?(\d+))?$/);
if (!m)
return null;
var f = parseFloat(value);
if (!isFinite(f))
return null;
var mantissa = m[1];
var abs_exp = m[4];
if (f === 0 && mantissa > 0 && abs_exp > 0) // too small number out of range such as 1.23e-700
return null;
return f;
}
function getNumericFeedValue(value, bBySignificantDigits){
if (typeof value !== 'string')
throw Error("getNumericFeedValue of not a string: "+value);
var m = value.match(/^[+-]?(\d+(\.\d+)?)([eE][+-]?(\d+))?$/);
if (!m)
return null;
var f = parseFloat(value);
if (!isFinite(f))
return null;
var mantissa = m[1];
var abs_exp = m[4];
if (f === 0 && mantissa > 0 && abs_exp > 0) // too small number out of range such as 1.23e-700
return null;
if (bBySignificantDigits) {
var significant_digits = mantissa.replace(/^0+/, '');
if (significant_digits.indexOf('.') >= 0)
significant_digits = significant_digits.replace(/0+$/, '').replace('.', '');
if (significant_digits.length > 16)
return null;
}
else {
// mantissa can also be 123.456, 00.123, 1.2300000000, 123000000000, anyway too long number indicates we want to keep it as a string
if (mantissa.length > 15) // including the point (if any), including 0. in 0.123
return null;
}
return f;
}
// transformss the value to number is possible
function getFeedValue(value, bLimitedPrecision){
var numValue = toNumber(value, bLimitedPrecision);
return (numValue === null) ? value : numValue;
}
function encodeDoubleInLexicograpicOrder(float){
if (float === -0) // it is actually true for both 0's
float = 0; // we always assign a positive 0
var buf = Buffer.allocUnsafe(8);
buf.writeDoubleBE(float, 0);
if (float >= 0)
buf[0] ^= 0x80; // flip the sign bit
else
for (var i=0; i<buf.length; i++)
buf[i] ^= 0xff; // flip the sign bit and reverse the ordering
return buf.toString('hex');
}
function decodeLexicographicToDouble(hex){
var buf = Buffer.from(hex, 'hex');
if (buf[0] & 0x80) // first bit set: positive
buf[0] ^= 0x80; // flip the sign bit
else
for (var i=0; i<buf.length; i++)
buf[i] ^= 0xff; // flip the sign bit and reverse the ordering
var float = buf.readDoubleBE(0);
if (float === -0)
float = 0;
return float;
}
// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
String.prototype.padStart = function padStart(targetLength, padString) {
targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
padString = String(typeof padString !== 'undefined' ? padString : ' ');
if (this.length >= targetLength) {
return String(this);
} else {
targetLength = targetLength - this.length;
if (targetLength > padString.length) {
padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
}
return padString.slice(0, targetLength) + String(this);
}
};
}
// node 12+ implements well-formed JSON.stringify(), earlier versions could generate invalid UTF
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Well-formed_JSON.stringify()
var bWellFormedJsonStringify = (JSON.stringify("\uD800") === '"\\ud800"');
function toWellFormedJsonStringify(obj) {
var str = JSON.stringify(obj);
// we used to replace all such symbols, not just lone surrogates
return /*bWellFormedJsonStringify ? str :*/ str.replace(/[\ud800-\udfff]/g, chr => "\\u" + chr.codePointAt(0).toString(16));
}
function getJsonSourceString(obj, bAllowEmpty) {
function stringify(variable){
if (variable === null)
throw Error("null value in "+JSON.stringify(obj));
switch (typeof variable){
case "string":
return toWellFormedJsonStringify(variable);
case "number":
if (!isFinite(variable))
throw Error("invalid number: " + variable);
case "boolean":
return variable.toString();
case "object":
if (Array.isArray(variable)){
if (variable.length === 0 && !bAllowEmpty)
throw Error("empty array in "+JSON.stringify(obj));
return '[' + variable.map(stringify).join(',') + ']';
}
else{
var keys = Object.keys(variable).sort();
if (keys.length === 0 && !bAllowEmpty)
throw Error("empty object in "+JSON.stringify(obj));
return '{' + keys.map(function(key){ return toWellFormedJsonStringify(key)+':'+stringify(variable[key]) }).join(',') + '}';
}
break;
default:
throw Error("getJsonSourceString: unknown type="+(typeof variable)+" of "+variable+", object: "+JSON.stringify(obj));
}
}
return stringify(obj);
}
exports.STRING_JOIN_CHAR = STRING_JOIN_CHAR; // for tests
exports.getSourceString = getSourceString;
exports.encodeMci = encodeMci;
exports.getMciFromDataFeedKey = getMciFromDataFeedKey;
exports.getValueFromDataFeedKey = getValueFromDataFeedKey;
exports.toNumber = toNumber;
exports.getNumericFeedValue = getNumericFeedValue;
exports.getFeedValue = getFeedValue;
exports.encodeDoubleInLexicograpicOrder = encodeDoubleInLexicograpicOrder;
exports.decodeLexicographicToDouble = decodeLexicographicToDouble;
exports.getJsonSourceString = getJsonSourceString;