Repository navigation
Expand file tree
/
Copy pathto_msgpack.cpp
More file actions
563 lines (523 loc) · 17.8 KB
/
Copy pathto_msgpack.cpp
File metadata and controls
563 lines (523 loc) · 17.8 KB
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
// Converts JSON to MessagePack, with simdjson's On-Demand parser.
//
// On-Demand gives the elements of an array or an object one after the other:
// we do not know how many there are when we write the header. So we leave 5
// bytes (the largest header) for each array and object header, note where,
// and once the document is written, move the bytes back to put the smallest
// header in place (one pass over the output). A string is unescaped right
// after one byte left for its header (strings are mostly short), and moved
// forward if it needs a longer header.
#include <algorithm>
#include <atomic>
#include <cstring>
#include <limits>
#include <new>
#include <utility>
#include <vector>
#include "simdjson_msgpack.h"
#include "buffer.h"
#include "parallel.h"
namespace simdjson_msgpack {
namespace {
using namespace simdjson;
simdjson_inline uint8_t* put16(uint8_t* p, uint16_t v) {
p[0] = uint8_t(v >> 8);
p[1] = uint8_t(v);
return p + 2;
}
simdjson_inline uint8_t* put32(uint8_t* p, uint32_t v) {
p[0] = uint8_t(v >> 24);
p[1] = uint8_t(v >> 16);
p[2] = uint8_t(v >> 8);
p[3] = uint8_t(v);
return p + 4;
}
simdjson_inline uint8_t* put64(uint8_t* p, uint64_t v) {
p = put32(p, uint32_t(v >> 32));
return put32(p, uint32_t(v));
}
// Where the header of an array or an object goes: 5 bytes at offset (from
// the start of the document).
struct header {
size_t offset;
uint32_t count;
bool is_map;
};
constexpr size_t header_room = 5;
simdjson_inline uint8_t* put_header(uint8_t* p, const header& h) {
if (h.count < 16) {
*p = uint8_t((h.is_map ? 0x80 : 0x90) | h.count);
return p + 1;
}
if (h.count <= 0xffff) {
*p = h.is_map ? 0xde : 0xdc;
return put16(p + 1, uint16_t(h.count));
}
*p = h.is_map ? 0xdf : 0xdd;
return put32(p + 1, h.count);
}
// Puts the smallest headers in place in the document [begin, end), moving
// back what follows them; returns the new end.
uint8_t* compact(uint8_t* begin, uint8_t* end, const header* headers, size_t count) {
if (count == 0) return end;
uint8_t* out = begin + headers[0].offset;
const uint8_t* in = out;
for (size_t i = 0; i < count; i++) {
const header& h = headers[i];
const uint8_t* at = begin + h.offset;
const size_t n = size_t(at - in);
std::memmove(out, in, n);
out = put_header(out + n, h);
in = at + header_room;
}
const size_t n = size_t(end - in);
std::memmove(out, in, n);
return out + n;
}
// Writes one JSON document as MessagePack. The output must have room for
// max_msgpack_size(the document's length) bytes.
class encoder {
public:
encoder(ondemand::parser& parser, std::vector<header>& headers, const msgpack_options& options)
: parser_(parser), headers_(headers), options_(options) {}
// Writes the document at out; sets *end past the value.
template <typename document>
error_code write(document& doc, uint8_t* out, uint8_t** end) {
begin_ = out_ = out;
count_ = 0;
error_code e = any(doc);
if (e) return e;
*end = compact(begin_, out_, headers_.data(), count_);
return SUCCESS;
}
private:
// A value, of any type: a document, a document_reference or a value.
template <typename V>
simdjson_inline error_code any(V& v) {
ondemand::json_type t;
SIMDJSON_TRY(v.type().get(t));
switch (t) {
case ondemand::json_type::array: {
ondemand::array a;
SIMDJSON_TRY(v.get_array().get(a));
return array(a);
}
case ondemand::json_type::object: {
ondemand::object o;
SIMDJSON_TRY(v.get_object().get(o));
return object(o);
}
default:
return scalar(v, t);
}
}
template <typename V>
simdjson_inline error_code scalar(V& v, ondemand::json_type t) {
switch (t) {
case ondemand::json_type::number:
return number(v);
case ondemand::json_type::string: {
ondemand::raw_json_string s;
SIMDJSON_TRY(v.get_raw_json_string().get(s));
return string(s);
}
case ondemand::json_type::boolean: {
bool b;
SIMDJSON_TRY(v.get_bool().get(b));
*out_++ = uint8_t(0xc2 + b);
return SUCCESS;
}
case ondemand::json_type::null: {
bool is_null;
SIMDJSON_TRY(v.is_null().get(is_null));
if (!is_null) return N_ATOM_ERROR;
*out_++ = 0xc0;
return SUCCESS;
}
default:
return TAPE_ERROR;
}
}
// An element of an array or the value of a field: scalars here, containers
// in a call (most values are scalars).
simdjson_inline error_code element(ondemand::value& v) {
ondemand::json_type t;
SIMDJSON_TRY(v.type().get(t));
if (t == ondemand::json_type::array || t == ondemand::json_type::object) return container(v);
return scalar(v, t);
}
simdjson_never_inline error_code container(ondemand::value& v) { return any(v); }
error_code array(ondemand::array& a) {
const size_t h = open(false);
uint64_t count = 0;
for (auto child : a) {
SIMDJSON_TRY(child.error());
SIMDJSON_TRY(element(in_place(child)));
count++;
}
return close(h, count);
}
error_code object(ondemand::object& o) {
const size_t h = open(true);
uint64_t count = 0;
for (auto f : o) {
SIMDJSON_TRY(f.error());
ondemand::field& field = in_place(f);
SIMDJSON_TRY(string(field.key()));
SIMDJSON_TRY(element(field.value()));
count++;
}
return close(h, count);
}
// The value in a result (which has no error), without a copy: GCC copies
// results through the stack with stores that loads cannot forward from.
template <typename T>
static simdjson_inline T& in_place(simdjson_result<T>& r) {
return const_cast<T&>(r.value_unsafe());
}
simdjson_inline size_t open(bool is_map) {
// We write the fields in place, rather than push a header built on the
// stack (GCC would copy it with a load that cannot be forwarded to).
const size_t h = count_++;
if (simdjson_unlikely(h == headers_.size())) headers_.resize(headers_.empty() ? 64 : 2 * h);
header& slot = headers_[h];
slot.offset = size_t(out_ - begin_);
slot.is_map = is_map;
out_ += header_room;
return h;
}
simdjson_inline error_code close(size_t h, uint64_t count) {
if (count > std::numeric_limits<uint32_t>::max()) return CAPACITY;
headers_[h].count = uint32_t(count);
return SUCCESS;
}
template <typename V>
simdjson_inline error_code number(V& v) {
ondemand::number n;
error_code e = v.get_number().get(n);
if (simdjson_unlikely(e)) {
if (e != BIGINT_ERROR || !options_.big_integers_as_float64) return e;
double d;
SIMDJSON_TRY(v.get_double().get(d));
put_double(d);
return SUCCESS;
}
switch (n.get_number_type()) {
case ondemand::number_type::signed_integer:
put_int(n.get_int64());
break;
case ondemand::number_type::unsigned_integer:
put_uint(n.get_uint64());
break;
default:
put_double(n.get_double());
}
return SUCCESS;
}
simdjson_inline void put_uint(uint64_t x) {
if (x < 128) {
*out_++ = uint8_t(x);
} else if (x <= 0xff) {
out_[0] = 0xcc;
out_[1] = uint8_t(x);
out_ += 2;
} else if (x <= 0xffff) {
*out_ = 0xcd;
out_ = put16(out_ + 1, uint16_t(x));
} else if (x <= 0xffffffff) {
*out_ = 0xce;
out_ = put32(out_ + 1, uint32_t(x));
} else {
*out_ = 0xcf;
out_ = put64(out_ + 1, x);
}
}
simdjson_inline void put_int(int64_t x) {
if (x >= 0) return put_uint(uint64_t(x));
if (x >= -32) {
*out_++ = uint8_t(x); // negative fixint: 0xe0 to 0xff
} else if (x >= -128) {
out_[0] = 0xd0;
out_[1] = uint8_t(x);
out_ += 2;
} else if (x >= -32768) {
*out_ = 0xd1;
out_ = put16(out_ + 1, uint16_t(x));
} else if (x >= -2147483648LL) {
*out_ = 0xd2;
out_ = put32(out_ + 1, uint32_t(x));
} else {
*out_ = 0xd3;
out_ = put64(out_ + 1, uint64_t(x));
}
}
simdjson_inline void put_double(double d) {
if (options_.float32_when_exact) {
const float f = float(d);
if (double(f) == d) {
uint32_t bits;
std::memcpy(&bits, &f, 4);
*out_ = 0xca;
out_ = put32(out_ + 1, bits);
return;
}
}
uint64_t bits;
std::memcpy(&bits, &d, 8);
*out_ = 0xcb;
out_ = put64(out_ + 1, bits);
}
// Unescapes the string after one byte (a fixstr header), then moves it
// forward if it needs a longer header.
simdjson_inline error_code string(ondemand::raw_json_string s) {
uint8_t* const at = out_;
uint8_t* end = at + 1;
// unescape moves end past the string: we take only the error (copying
// the whole result costs GCC a store-forwarding stall).
SIMDJSON_TRY(parser_.unescape(s, end).error());
const size_t n = size_t(end - (at + 1));
if (simdjson_likely(n < 32)) {
*at = uint8_t(0xa0 | n);
} else if (n <= 0xff) {
std::memmove(at + 2, at + 1, n);
at[0] = 0xd9;
at[1] = uint8_t(n);
end += 1;
} else if (n <= 0xffff) {
std::memmove(at + 3, at + 1, n);
at[0] = 0xda;
put16(at + 1, uint16_t(n));
end += 2;
} else {
if (n > std::numeric_limits<uint32_t>::max()) return CAPACITY;
std::memmove(at + 5, at + 1, n);
at[0] = 0xdb;
put32(at + 1, uint32_t(n));
end += 4;
}
out_ = end;
return SUCCESS;
}
ondemand::parser& parser_;
std::vector<header>& headers_; // the first count_ are in use
size_t count_{0};
const msgpack_options& options_;
uint8_t* begin_{nullptr};
uint8_t* out_{nullptr};
};
std::string error_text(error_code e, size_t document) {
std::string message = error_message(e);
if (document != size_t(-1)) message += " (document " + std::to_string(document) + ")";
return message;
}
// The documents of newline-delimited JSON, converted into out by one thread.
struct ndjson_result {
error_code error{SUCCESS};
size_t count{0}; // documents written, or the one that failed
};
} // namespace
struct msgpack_writer::impl {
impl(const msgpack_options& o, const allocator* a) : options(o), out(a) {}
msgpack_options options;
internal::buffer out;
ondemand::parser parser;
std::vector<header> headers;
// Writes the documents of json into into; on error, into keeps what it had
// written (the caller truncates it).
ndjson_result ndjson(padded_string_view json, ondemand::parser& p, std::vector<header>& h,
internal::buffer& into) {
ndjson_result r;
size_t batch = std::max<size_t>(options.block_size, size_t(1) << 16);
for (;;) {
ondemand::document_stream stream;
r.error = p.iterate_many(json.data(), json.size(), std::min(batch, json.size()))
.get(stream);
if (r.error) return r;
encoder enc(p, h, options);
r.count = 0;
const size_t start = into.size();
for (auto it = stream.begin(); it != stream.end(); ++it) {
ondemand::document_reference doc;
r.error = (*it).get(doc);
if (!r.error) {
// The document's text bounds what we write.
const size_t room = max_msgpack_size(it.source().size());
uint8_t* at = reinterpret_cast<uint8_t*>(into.reserve(room));
uint8_t* end;
r.error = enc.write(doc, at, &end);
if (!r.error) into.resize(size_t(reinterpret_cast<char*>(end) - into.data()));
}
if (r.error) break;
r.count++;
}
// A document larger than the batch: once more, with the whole input.
if (r.error == CAPACITY && batch < json.size()) {
into.resize(start);
batch = json.size();
continue;
}
if (!r.error && stream.truncated_bytes() != 0) r.error = TAPE_ERROR;
return r;
}
}
status write_ndjson(padded_string_view json, size_t* count) {
const size_t start = out.size();
try {
if (options.threads > 1 && json.size() > options.block_size) {
if (parallel_ndjson(json, count)) return status{};
out.resize(start);
}
ndjson_result r = ndjson(json, parser, headers, out);
if (r.error) {
out.resize(start);
return status{error_text(r.error, r.count)};
}
if (count != nullptr) *count += r.count;
return status{};
} catch (const std::bad_alloc&) {
out.resize(start);
return status{"out of memory"};
}
}
// What each thread keeps between calls: its parser, and the buffers into
// which it converts blocks before copying them in place.
struct worker {
ondemand::parser parser;
std::vector<header> headers;
std::vector<std::unique_ptr<internal::buffer>> scratch;
worker() {
for (size_t k = 0; k < internal::slots_per_thread; k++) {
scratch.emplace_back(new internal::buffer);
}
}
};
std::vector<std::unique_ptr<worker>> workers;
// Converts blocks of about block_size bytes, cut at line ends, on several
// threads. Returns false if one fails (to convert again in one thread).
bool parallel_ndjson(padded_string_view json, size_t* count) {
const size_t block = std::max<size_t>(options.block_size, 1);
const size_t n = (json.size() + block - 1) / block;
const char* data = json.data();
const size_t length = json.size();
// Block i starts after the first line end at or after i * block.
auto block_start = [&](size_t i) -> size_t {
if (i == 0) return 0;
if (i >= n) return length;
const void* nl = std::memchr(data + i * block, '\n', length - i * block);
return nl == nullptr ? length : size_t(static_cast<const char*>(nl) - data) + 1;
};
const size_t threads = std::min(options.threads, n);
if (workers.size() < threads) workers.resize(threads);
for (auto& w : workers) {
if (!w) w.reset(new worker);
}
// MessagePack is seldom larger than its JSON: one allocation, usually.
out.reserve(length);
internal::ordered_output placed(out, n);
std::vector<size_t> counts(n, 0);
std::atomic<bool> failed{false};
std::atomic<size_t> next{0};
internal::run_threads(threads, [&](size_t w) {
try {
worker& me = *workers[w];
internal::ordered_slots slots(placed, me.scratch);
for (;;) {
internal::buffer* into = slots.take(failed); // before the block
if (into == nullptr) return;
const size_t i = next++;
if (i >= n || failed) break;
const size_t begin = block_start(i);
const size_t end = std::max(begin, block_start(i + 1));
if (begin != end) {
padded_string_view part(data + begin, end - begin, json.capacity() - begin);
ndjson_result r = ndjson(part, me.parser, me.headers, *into);
if (r.error) {
failed = true;
return;
}
counts[i] = r.count;
}
slots.converted(i, into); // an empty block too, for the blocks after it
}
slots.flush(failed);
} catch (...) { // std::bad_alloc: the others stop, we convert in one thread
failed = true;
}
});
if (placed.lost()) throw std::bad_alloc(); // the output itself: no second try
if (failed) return false;
placed.finish(n);
size_t documents = 0;
for (size_t c : counts) documents += c;
if (count != nullptr) *count += documents;
return true;
}
};
msgpack_writer::msgpack_writer(const msgpack_options& options)
: impl_(new impl(options, nullptr)) {}
msgpack_writer::msgpack_writer(const msgpack_options& options, const allocator& a)
: impl_(new impl(options, &a)) {}
msgpack_writer::~msgpack_writer() = default;
status msgpack_writer::write_json(padded_string_view json) {
impl& m = *impl_;
const size_t start = m.out.size();
try {
uint8_t* at = reinterpret_cast<uint8_t*>(m.out.reserve(max_msgpack_size(json.size())));
ondemand::document doc;
error_code e = m.parser.iterate(json).get(doc);
uint8_t* end = at;
encoder enc(m.parser, m.headers, m.options);
if (!e) e = enc.write(doc, at, &end);
if (!e && !doc.at_end()) e = TRAILING_CONTENT;
if (e) return status{error_text(e, size_t(-1))};
m.out.resize(size_t(reinterpret_cast<char*>(end) - m.out.data()));
return status{};
} catch (const std::bad_alloc&) {
m.out.resize(start);
return status{"out of memory"};
}
}
status msgpack_writer::write_json(const char* json, size_t length) {
try {
padded_string copy(json, length);
return write_json(padded_string_view(copy));
} catch (const std::bad_alloc&) {
return status{"out of memory"};
}
}
status msgpack_writer::write_ndjson(padded_string_view json, size_t* count) {
return impl_->write_ndjson(json, count);
}
status msgpack_writer::write_ndjson(const char* json, size_t length, size_t* count) {
try {
padded_string copy(json, length);
return write_ndjson(padded_string_view(copy), count);
} catch (const std::bad_alloc&) {
return status{"out of memory"};
}
}
std::string_view msgpack_writer::view() const { return impl_->out.view(); }
char* msgpack_writer::release(size_t* size) { return impl_->out.release(size); }
void msgpack_writer::clear() { impl_->out.resize(0); }
namespace {
template <typename F>
status append_to(std::string* out, const msgpack_options& options, F write) {
msgpack_writer writer(options);
status s = write(writer);
if (!s.ok()) return s;
try {
out->append(writer.view());
} catch (const std::bad_alloc&) {
return status{"out of memory"};
}
return s;
}
} // namespace
status json_to_msgpack(padded_string_view json, std::string* out, const msgpack_options& options) {
return append_to(out, options, [&](msgpack_writer& w) { return w.write_json(json); });
}
status ndjson_to_msgpack(padded_string_view json, std::string* out,
const msgpack_options& options) {
return append_to(out, options, [&](msgpack_writer& w) { return w.write_ndjson(json); });
}
} // namespace simdjson_msgpack