-
Notifications
You must be signed in to change notification settings - Fork 167
/
serializer.cpp
459 lines (416 loc) · 12.5 KB
/
serializer.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
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
/*************************************************************************
*
* Copyright 2016 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
#include <realm/util/serializer.hpp>
#include <realm/binary_data.hpp>
#include <realm/geospatial.hpp>
#include <realm/keys.hpp>
#include <realm/null.hpp>
#include <realm/query_expression.hpp>
#include <realm/string_data.hpp>
#include <realm/table.hpp>
#include <realm/timestamp.hpp>
#include <realm/util/base64.hpp>
#include <cctype>
#include <cmath>
#include <iomanip>
namespace realm {
/* Uses Fliegel & Van Flandern algorithm */
static constexpr long date_to_julian(int y, int m, int d)
{
return (1461 * (y + 4800 + (m - 14) / 12)) / 4 + (367 * (m - 2 - 12 * ((m - 14) / 12))) / 12 -
(3 * ((y + 4900 + (m - 14) / 12) / 100)) / 4 + d - 32075;
}
static void julian_to_date(int jd, int* y, int* m, int* d)
{
uint64_t L = jd + 68569;
uint64_t n = (4 * L) / 146097;
uint64_t i, j;
L = L - (146097 * n + 3) / 4;
i = (4000 * (L + 1)) / 1461001;
L = L - (1461 * i) / 4 + 31;
j = (80 * L) / 2447;
*d = static_cast<int>(L - (2447 * j) / 80);
L = j / 11;
*m = static_cast<int>(j + 2 - (12 * L));
*y = static_cast<int>(100 * (n - 49) + i + L);
}
// Confirmed to work for all val < 16389
static void out_dec(char** buffer, unsigned val, int width)
{
int w = width;
char* p = *buffer;
while (width > 0) {
width--;
unsigned div10 = (val * 6554) >> 16;
p[width] = char(val - div10 * 10) + '0';
val = div10;
}
*buffer += w;
}
static constexpr long epoc_julian_days = date_to_julian(1970, 1, 1); // 2440588
static constexpr int seconds_in_a_day = 24 * 60 * 60;
const char* Timestamp::to_string(std::array<char, 32>& buffer) const
{
if (is_null()) {
return "null";
}
int64_t seconds = get_seconds();
int32_t nano = get_nanoseconds();
if (nano < 0) {
nano += Timestamp::nanoseconds_per_second;
seconds--;
}
int64_t days = seconds / seconds_in_a_day;
int julian_days = int(days + epoc_julian_days);
int seconds_in_day = int(seconds - days * seconds_in_a_day);
if (seconds_in_day < 0) {
seconds_in_day += seconds_in_a_day;
julian_days--;
}
int year;
int month;
int day;
int hours = seconds_in_day / 3600;
int remainingSeconds = seconds_in_day - hours * 3600;
int minutes = remainingSeconds / 60;
int secs = remainingSeconds - minutes * 60;
julian_to_date(julian_days, &year, &month, &day);
char* p = buffer.data();
if (year < 0) {
*p++ = '-';
year = -year;
}
out_dec(&p, year, 4);
*p++ = '-';
out_dec(&p, month, 2);
*p++ = '-';
out_dec(&p, day, 2);
*p++ = ' ';
out_dec(&p, hours, 2);
*p++ = ':';
out_dec(&p, minutes, 2);
*p++ = ':';
out_dec(&p, secs, 2);
*p = '\0';
if (nano) {
snprintf(p, 32 - (p - buffer.data()), ".%09d", nano);
}
return buffer.data();
}
namespace util {
namespace serializer {
template <>
std::string print_value<>(BinaryData data)
{
if (data.is_null()) {
return "NULL";
}
return util::format("binary(%1)", print_value<StringData>(StringData(data.data(), data.size())));
}
template <>
std::string print_value<>(bool b)
{
if (b) {
return "true";
}
return "false";
}
template <typename T>
inline std::string print_with_nan_check(T val)
{
// we standardize NaN because some implementations (windows) will
// print the different types of NaN such as "nan(ind)" to indicate "indefinite"
if (std::isnan(val)) {
// preserving the sign of nan is not strictly required but is good etiquette
if (std::signbit(val)) {
return "-nan";
}
return "nan";
}
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<T>::max_digits10) << val;
return ss.str();
}
template <>
std::string print_value<>(float val)
{
return print_with_nan_check(val);
}
template <>
std::string print_value<>(double val)
{
return print_with_nan_check(val);
}
template <>
std::string print_value<>(realm::null)
{
return "NULL";
}
static bool contains_invalids(StringData data)
{
// the custom whitelist is different from std::isprint because it doesn't include quotations
const static std::string whitelist = " {|}~:;<=>?@!#$%&()*+,-./[]^_`";
const char* ptr = data.data();
const char* end = ptr + data.size();
while (ptr < end) {
using unsigned_char_t = unsigned char;
char c = *ptr;
size_t len = sequence_length(c);
if (len == 1) {
// std::isalnum takes an int, but is undefined for negative values so we must pass an unsigned char
if (!std::isalnum(unsigned_char_t(c)) && whitelist.find(c) == std::string::npos) {
return true;
}
}
else {
// multibyte utf8, check if subsequent bytes have the upper bit set
for (size_t i = 1; i < len; i++) {
++ptr;
if (ptr == end || (*ptr & 0x80) == 0) {
return true;
}
}
}
++ptr;
}
return false;
}
template <>
std::string print_value<>(StringData data)
{
if (data.is_null()) {
return "NULL";
}
std::string out;
const char* start = data.data();
const size_t len = data.size();
if (contains_invalids(data)) {
std::string encode_buffer;
encode_buffer.resize(util::base64_encoded_size(len));
util::base64_encode(data, encode_buffer);
out = "B64\"" + encode_buffer + "\"";
}
else {
out.reserve(len + 2);
out += '"';
for (const char* i = start; i != start + len; ++i) {
out += *i;
}
out += '"';
}
return out;
}
template <>
std::string print_value<>(realm::Timestamp t)
{
if (t.is_null()) {
return "NULL";
}
std::stringstream ss;
if (t.is_null()) {
ss << "null";
}
else {
ss << "T" << t.get_seconds() << ":" << t.get_nanoseconds();
}
return ss.str();
}
template <>
std::string print_value<>(realm::ObjectId oid)
{
return "oid(" + oid.to_string() + ")";
}
template <>
std::string print_value<>(realm::ObjKey k)
{
std::stringstream ss;
if (!k) {
ss << "NULL";
}
else {
ss << "O" << k.value;
}
return ss.str();
}
std::string print_value(realm::ObjLink link, Group* g)
{
if (!link) {
return "NULL";
}
else {
TableRef target_table = g ? g->get_table(link.get_table_key()) : TableRef();
if (ColKey pk_col = target_table ? target_table->get_primary_key_column() : ColKey{}) {
if (auto obj = target_table->try_get_object(link.get_obj_key())) {
auto pk_val = obj.get_any(pk_col);
std::ostringstream ostr;
ostr << "obj(" << util::serializer::print_value(target_table->get_name()) << "," << pk_val << ')';
return ostr.str();
}
}
}
std::stringstream ss;
ss << "L" << link.get_table_key().value << ":" << link.get_obj_key().value;
return ss.str();
}
template <>
std::string print_value<>(realm::UUID uuid)
{
return "uuid(" + uuid.to_string() + ")";
}
template <>
std::string print_value<>(realm::TypeOfValue type)
{
return '"' + type.to_string() + '"';
}
#if REALM_ENABLE_GEOSPATIAL
template <>
std::string print_value<>(const realm::Geospatial& geo)
{
return geo.to_string();
}
#endif
// The variable name must be unique with respect to the already chosen variables at
// this level of subquery nesting and with respect to the names of the columns in the table.
// This assumes that columns can start with '$' and that we might one day want to support
// referencing the parent table columns in the subquery. This is currently disabled by an assertion in the
// core SubQuery constructor.
std::string SerialisationState::get_variable_name(ConstTableRef table)
{
std::string guess_prefix = "$";
const char start_char = 'x';
char add_char = start_char;
auto next_guess = [&]() {
add_char = (((add_char + 1) - 'a') % ('z' - 'a' + 1)) + 'a';
if (add_char == start_char) {
guess_prefix += add_char;
}
};
while (true) {
std::string guess = guess_prefix + add_char;
bool found_duplicate = false;
for (size_t i = 0; i < subquery_prefix_list.size(); ++i) {
if (guess == subquery_prefix_list[i]) {
found_duplicate = true;
break;
}
}
if (found_duplicate) {
next_guess();
continue;
}
if (table->get_column_key(guess) != ColKey()) {
next_guess();
continue;
}
return guess;
}
}
std::string SerialisationState::get_column_name(ConstTableRef table, ColKey col_key)
{
ColumnType col_type = table->get_real_column_type(col_key);
if (col_type == col_type_BackLink) {
const Table::BacklinkOrigin origin = table->find_backlink_origin(col_key);
REALM_ASSERT(origin);
StringData source_table_name = origin->first->get_class_name();
std::string source_col_name = get_column_name(origin->first, origin->second);
return format("@links.%1.%2", source_table_name, source_col_name);
}
else if (col_key != ColKey()) {
std::string col_name = table->get_column_name(col_key);
size_t pos = col_name.find_first_of(" \t\r\n");
while (pos != std::string::npos) {
switch (col_name[pos]) {
case ' ':
// space is unchanged
break;
case '\t':
col_name[pos] = 't';
break;
case '\r':
col_name[pos] = 'r';
break;
case '\n':
col_name[pos] = 'n';
break;
}
col_name = col_name.substr(0, pos) + "\\" + col_name.substr(pos);
pos += 2;
pos = col_name.find_first_of(" \t\r\n", pos);
}
return col_name;
}
return "";
}
std::string SerialisationState::describe_column(ConstTableRef table, ColKey col_key)
{
if (table && col_key) {
std::string desc;
if (!subquery_prefix_list.empty()) {
desc += subquery_prefix_list.back() + value_separator;
}
desc += get_column_name(table, col_key);
return desc;
}
return "";
}
std::string SerialisationState::get_backlink_column_name(ConstTableRef from, ColKey col_key)
{
ColumnType col_type = col_key.get_type();
REALM_ASSERT_EX(col_type == col_type_Link, col_type);
auto target_table = from->get_opposite_table(col_key);
auto backlink_col = from->get_opposite_column(col_key);
return get_column_name(target_table, backlink_col);
}
std::string SerialisationState::describe_columns(const LinkMap& link_map, ColKey target_col_key)
{
std::string desc;
if (!subquery_prefix_list.empty()) {
desc += subquery_prefix_list.back();
}
if (link_map.links_exist()) {
if (!desc.empty()) {
desc += util::serializer::value_separator;
}
desc += link_map.description(*this);
}
ConstTableRef target = link_map.get_target_table();
if (target && target_col_key) {
if (!desc.empty()) {
desc += util::serializer::value_separator;
}
desc += get_column_name(target, target_col_key);
}
return desc;
}
std::string SerialisationState::describe_expression_type(util::Optional<ExpressionComparisonType> type)
{
if (type) {
switch (*type) {
case ExpressionComparisonType::Any:
return "ANY ";
case ExpressionComparisonType::All:
return "ALL ";
case ExpressionComparisonType::None:
return "NONE ";
}
}
return "";
}
} // namespace serializer
} // namespace util
} // namespace realm