forked from microsoft/SEAL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ztools.cpp
791 lines (665 loc) · 32.8 KB
/
ztools.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
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "seal/util/defines.h"
#if defined(SEAL_USE_ZLIB) || defined(SEAL_USE_ZSTD)
#include "seal/dynarray.h"
#include "seal/memorymanager.h"
#include "seal/serialization.h"
#include "seal/util/pointer.h"
#include "seal/util/ztools.h"
#include <cstddef>
#include <cstring>
#include <ios>
#include <iostream>
#include <limits>
#include <sstream>
#include <unordered_map>
using namespace std;
namespace seal
{
namespace util
{
namespace ztools
{
namespace
{
// Size for an internal buffer allocated for inflate and deflate
constexpr size_t buffer_size = 256 * 1024;
class PointerStorage
{
public:
PointerStorage(MemoryPoolHandle pool) : pool_(move(pool))
{}
void *allocate(size_t size)
{
auto ptr = util::allocate<seal_byte>(size, pool_);
void *addr = reinterpret_cast<void *>(ptr.get());
ptr_storage_[addr] = move(ptr);
return addr;
}
void free(void *addr)
{
ptr_storage_.erase(addr);
}
private:
MemoryPoolHandle pool_;
unordered_map<void *, Pointer<seal_byte>> ptr_storage_;
};
} // namespace
} // namespace ztools
} // namespace util
} // namespace seal
#endif
#ifdef SEAL_USE_ZLIB
#include "zlib.h"
namespace seal
{
namespace util
{
namespace ztools
{
namespace
{
// The output size in a single deflate round cannot exceed 4 GB so we need to invert the deflateBound
// inequality to find an upper bound for the input size.
constexpr size_t zlib_process_bytes_out_max = static_cast<size_t>(numeric_limits<uInt>::max());
// If input size is at most zlib_process_bytes_in_max, we can complete the deflate algorithm in a single
// call to deflate (deflateBound(zlib_process_bytes_in_max) is at most 4 GB).
constexpr size_t zlib_process_bytes_in_max =
zlib_process_bytes_out_max - (zlib_process_bytes_out_max >> 10) - 17;
// Custom allocator for ZLIB
void *zlib_alloc_impl(voidpf ptr_storage, uInt items, uInt size)
{
try
{
size_t total_size = safe_cast<size_t>(mul_safe(items, size));
return reinterpret_cast<PointerStorage *>(ptr_storage)->allocate(total_size);
}
catch (const invalid_argument &)
{
// Allocation failed due to too large allocation size
return Z_NULL;
}
catch (const bad_alloc &)
{
// Allocation failed due to out of memory error
return Z_NULL;
}
catch (const logic_error &)
{
// Allocation failed due to data type overflow
return Z_NULL;
}
catch (const runtime_error &)
{
// Allocation failed due to too many pools allocated
return Z_NULL;
}
}
// Custom free implementation for ZLIB
void zlib_free_impl(voidpf ptr_storage, void *addr)
{
reinterpret_cast<PointerStorage *>(ptr_storage)->free(addr);
}
} // namespace
int zlib_deflate_array_inplace(DynArray<seal_byte> &in, MemoryPoolHandle pool)
{
if (!pool)
{
throw invalid_argument("pool is uninitialized");
}
// We need size_t to be at least as large as uInt
static_assert(numeric_limits<uInt>::max() <= numeric_limits<size_t>::max(), "");
int result, flush;
int level = Z_DEFAULT_COMPRESSION;
int pending_bits;
unsigned pending_bytes;
z_stream zstream;
zstream.data_type = Z_BINARY;
PointerStorage ptr_storage(pool);
zstream.zalloc = zlib_alloc_impl;
zstream.zfree = zlib_free_impl;
zstream.opaque = reinterpret_cast<voidpf>(&ptr_storage);
result = deflateInit(&zstream, level);
if (result != Z_OK)
{
deflateEnd(&zstream);
return result;
}
// How much data was finally produced
size_t bytes_written_to_in = 0;
size_t bytes_read_from_in = 0;
// Allocate a temporary buffer for output
auto temp_out = DynArray<seal_byte>(buffer_size, pool);
// Where we are writing output now; start writing to the temporary buffer
seal_byte *out_head = temp_out.begin();
// How much of input do we have left to process
size_t in_size = in.size();
// Size of the current output buffer
size_t out_size = buffer_size;
// Are we overwriting in at this time?
bool out_is_in = false;
// Set the input and output pointers for the initial block
zstream.next_in = reinterpret_cast<unsigned char *>(const_cast<seal_byte *>(in.cbegin()));
zstream.next_out = reinterpret_cast<unsigned char *>(out_head);
do
{
// The number of bytes we can read at a time is capped by process_bytes_in_max
size_t process_bytes_in = min<size_t>(in_size, zlib_process_bytes_in_max);
zstream.avail_in = static_cast<uInt>(process_bytes_in);
// Number of bytes left after this round; if we are at the end set flush accordingly
in_size -= process_bytes_in;
flush = in_size ? Z_NO_FLUSH : Z_FINISH;
// Loop while we have input left
do
{
// First ensure we have output space
while (!out_size)
{
// We are out of output buffer
if (!out_is_in)
{
// If we have been writing to the temporary buffer, then see if we can copy to in
size_t temp_out_size = temp_out.size();
if (bytes_read_from_in >= bytes_written_to_in + temp_out_size)
{
// All is good; we can copy over the buffer to in
out_head = in.begin() + bytes_written_to_in;
memcpy(out_head, temp_out.cbegin(), temp_out_size);
out_head += temp_out_size;
bytes_written_to_in += temp_out_size;
// For next writes, try to write to in
out_is_in = true;
// Reset out_size
out_size = bytes_read_from_in - bytes_written_to_in;
// Reset temp_out to have size buffer_size
temp_out.resize(buffer_size, false);
}
else
{
// We don't have enough room to copy to in; instead, resize temp_out and continue
// using it, hoping that the situation will change
out_size = temp_out_size + buffer_size;
temp_out.resize(out_size, false);
out_size = buffer_size;
out_head = temp_out.begin() + temp_out_size;
}
}
else
{
// We are writing to in but are out of space; switch to temp_out for the moment
out_is_in = false;
// Set size and pointer
out_size = temp_out.size();
out_head = temp_out.begin();
}
}
// Set the stream output
zstream.next_out = reinterpret_cast<unsigned char *>(out_head);
// Cap the out size to zlib_process_bytes_out_max
size_t process_bytes_out = min<size_t>(out_size, zlib_process_bytes_out_max);
zstream.avail_out = static_cast<uInt>(process_bytes_out);
result = deflate(&zstream, flush);
#ifdef SEAL_DEBUG
// Intermediate rounds should return Z_OK and last should return Z_STREAM_END
if (result != Z_OK && result != Z_STREAM_END)
{
// Something went wrong so finish up here
deflateEnd(&zstream);
return result;
}
#endif
// True number of bytes written
process_bytes_out =
static_cast<size_t>(reinterpret_cast<seal_byte *>(zstream.next_out) - out_head);
out_size -= process_bytes_out;
out_head += process_bytes_out;
// Number of bytes read
bytes_read_from_in += process_bytes_in - zstream.avail_in;
if (out_is_in)
{
// Update number of bytes written to in
bytes_written_to_in += process_bytes_out;
}
// Is there pending output in the internal buffers? If so, we need to call deflate again
deflatePending(&zstream, &pending_bytes, &pending_bits);
} while ((flush == Z_FINISH && result == Z_OK) ||
(!zstream.avail_out && (pending_bits || pending_bytes)));
} while (in_size);
if (!out_is_in)
{
// We are done but the last writes were to temp_out
size_t bytes_in_temp_out = temp_out.size() - out_size;
// Resize in to fit the remaining data
in.resize(bytes_written_to_in + bytes_in_temp_out);
// Copy over the buffer to in
out_head = in.begin() + bytes_written_to_in;
memcpy(out_head, temp_out.cbegin(), bytes_in_temp_out);
bytes_written_to_in += bytes_in_temp_out;
}
else
{
// Just resize in to the right size
in.resize(bytes_written_to_in);
}
deflateEnd(&zstream);
return Z_OK;
}
int zlib_inflate_stream(istream &in_stream, streamoff in_size, ostream &out_stream, MemoryPoolHandle pool)
{
// Clear the exception masks; this function returns an error code
// on failure rather than throws an IO exception.
auto in_stream_except_mask = in_stream.exceptions();
in_stream.exceptions(ios_base::goodbit);
auto out_stream_except_mask = out_stream.exceptions();
out_stream.exceptions(ios_base::goodbit);
auto in_stream_start_pos = in_stream.tellg();
auto in_stream_end_pos = in_stream_start_pos + in_size;
int result;
size_t have;
auto in(allocate<unsigned char>(buffer_size, pool));
auto out(allocate<unsigned char>(buffer_size, pool));
z_stream zstream;
zstream.data_type = Z_BINARY;
PointerStorage ptr_storage(pool);
zstream.zalloc = zlib_alloc_impl;
zstream.zfree = zlib_free_impl;
zstream.opaque = reinterpret_cast<voidpf>(&ptr_storage);
zstream.avail_in = 0;
zstream.next_in = Z_NULL;
result = inflateInit(&zstream);
if (result != Z_OK)
{
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return result;
}
do
{
if (!in_stream.read(
reinterpret_cast<char *>(in.get()),
min(static_cast<streamoff>(buffer_size), in_stream_end_pos - in_stream.tellg())))
{
inflateEnd(&zstream);
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return Z_ERRNO;
}
if (0 == (zstream.avail_in = static_cast<decltype(zstream.avail_in)>(in_stream.gcount())))
{
break;
}
zstream.next_in = in.get();
do
{
zstream.avail_out = buffer_size;
zstream.next_out = out.get();
result = inflate(&zstream, Z_NO_FLUSH);
switch (result)
{
case Z_NEED_DICT:
result = Z_DATA_ERROR;
/* fall through */
case Z_DATA_ERROR:
/* fall through */
case Z_MEM_ERROR:
inflateEnd(&zstream);
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return result;
}
have = buffer_size - static_cast<size_t>(zstream.avail_out);
if (!out_stream.write(reinterpret_cast<const char *>(out.get()), static_cast<streamsize>(have)))
{
inflateEnd(&zstream);
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return Z_ERRNO;
}
} while (!zstream.avail_out);
} while (result != Z_STREAM_END);
inflateEnd(&zstream);
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return result == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
void zlib_write_header_deflate_buffer(
DynArray<seal_byte> &in, void *header_ptr, ostream &out_stream, MemoryPoolHandle pool)
{
Serialization::SEALHeader &header = *reinterpret_cast<Serialization::SEALHeader *>(header_ptr);
auto ret = zlib_deflate_array_inplace(in, move(pool));
if (Z_OK != ret)
{
stringstream ss;
ss << "ZLIB compression failed with error code ";
ss << ret;
throw logic_error(ss.str());
}
// Populate the header
header.compr_mode = compr_mode_type::zlib;
header.size = static_cast<uint64_t>(add_safe(sizeof(Serialization::SEALHeader), in.size()));
auto old_except_mask = out_stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
out_stream.exceptions(ios_base::badbit | ios_base::failbit);
// Write the header and the data
out_stream.write(reinterpret_cast<const char *>(&header), sizeof(Serialization::SEALHeader));
out_stream.write(reinterpret_cast<const char *>(in.cbegin()), safe_cast<streamsize>(in.size()));
}
catch (...)
{
out_stream.exceptions(old_except_mask);
throw;
}
out_stream.exceptions(old_except_mask);
}
} // namespace ztools
} // namespace util
} // namespace seal
#endif
#ifdef SEAL_USE_ZSTD
#if (SEAL_COMPILER == SEAL_COMPILER_GCC)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wsign-conversion"
#elif (SEAL_COMPILER == SEAL_COMPILER_CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wsign-conversion"
#endif
#define ZSTD_STATIC_LINKING_ONLY
#include "zstd.h"
#include "zstd_errors.h"
#if (SEAL_COMPILER == SEAL_COMPILER_GCC)
#pragma GCC diagnostic pop
#elif (SEAL_COMPILER == SEAL_COMPILER_CLANG)
#pragma clang diagnostic pop
#endif
namespace seal
{
namespace util
{
namespace ztools
{
namespace
{
// We cap the output size in a single compression round to 4 GB so we need to invert the deflateBound
// inequality to find an upper bound for the input size. Unlike for ZLIB, for Zstandard this is not
// a required bound. However, it can help keep the memory footprint smaller when very large objects are
// compressed.
constexpr size_t zstd_process_bytes_out_max = static_cast<size_t>(numeric_limits<uint32_t>::max());
// If input size is at most zstd_process_bytes_in_max, we can complete the deflate algorithm in a single
// call to deflate (deflateBound(zstd_process_bytes_in_max) is at most 4 GB).
constexpr size_t zstd_process_bytes_in_max =
zstd_process_bytes_out_max - (zstd_process_bytes_out_max >> 8) - 64;
// Custom allocator for Zstandard
void *zstd_alloc_impl(void *ptr_storage, size_t size)
{
try
{
return reinterpret_cast<PointerStorage *>(ptr_storage)->allocate(size);
}
catch (const invalid_argument &)
{
// Allocation failed due to too large allocation size
return nullptr;
}
catch (const bad_alloc &)
{
// Allocation failed due to out of memory error
return nullptr;
}
catch (const logic_error &)
{
// Allocation failed due to data type overflow
return nullptr;
}
catch (const runtime_error &)
{
// Allocation failed due to too many pools allocated
return nullptr;
}
}
// Custom free implementation for Zstandard
void zstd_free_impl(void *ptr_storage, void *addr)
{
reinterpret_cast<PointerStorage *>(ptr_storage)->free(addr);
}
} // namespace
unsigned zstd_deflate_array_inplace(DynArray<seal_byte> &in, MemoryPoolHandle pool)
{
if (!pool)
{
throw invalid_argument("pool is uninitialized");
}
PointerStorage ptr_storage(pool);
// Set up the custom allocator
ZSTD_customMem mem;
mem.customAlloc = zstd_alloc_impl;
mem.customFree = zstd_free_impl;
mem.opaque = &ptr_storage;
ZSTD_CCtx *cctx = ZSTD_createCCtx_advanced(mem);
if (!cctx)
{
// Failed to set up the context; there is something wrong with the allocator
return ZSTD_error_GENERIC;
}
// How much data was finally produced
size_t bytes_written_to_in = 0;
size_t bytes_read_from_in = 0;
// Allocate a temporary buffer for output
auto temp_out = DynArray<seal_byte>(buffer_size, pool);
// Where we are writing output now; start writing to the temporary buffer
seal_byte *out_head = temp_out.begin();
// How much of input do we have left to process
size_t in_size = in.size();
// Size of the current output buffer
size_t out_size = buffer_size;
// Are we overwriting in at this time?
bool out_is_in = false;
// Holds the return value of the stream compression call. This is either the amount of data that remains
// to be flushed from internal buffers, or an error code.
size_t pending = 0;
do
{
// The number of bytes we can read at a time is capped by zstd_process_bytes_in_max
size_t process_bytes_in = min<size_t>(in_size, zstd_process_bytes_in_max);
ZSTD_inBuffer input = { in.cbegin() + bytes_read_from_in, process_bytes_in, 0 };
size_t prev_pos = 0;
// Number of bytes left after this round; if we are at the end set flush accordingly
in_size -= process_bytes_in;
ZSTD_EndDirective flush = in_size ? ZSTD_e_continue : ZSTD_e_end;
// Loop while we have input left
do
{
// First ensure we have output space
while (!out_size)
{
// We are out of output buffer
if (!out_is_in)
{
// If we have been writing to the temporary buffer, then see if we can copy to in
size_t temp_out_size = temp_out.size();
if (bytes_read_from_in >= bytes_written_to_in + temp_out_size)
{
// All is good; we can copy over the buffer to in
out_head = in.begin() + bytes_written_to_in;
memcpy(out_head, temp_out.cbegin(), temp_out_size);
out_head += temp_out_size;
bytes_written_to_in += temp_out_size;
// For next writes, try to write to in
out_is_in = true;
// Reset out_size
out_size = bytes_read_from_in - bytes_written_to_in;
// Reset temp_out to have size buffer_size
temp_out.resize(buffer_size, false);
}
else
{
// We don't have enough room to copy to in; instead, resize temp_out and continue
// using it, hoping that the situation will change
out_size = temp_out_size + buffer_size;
temp_out.resize(out_size, false);
out_size = buffer_size;
out_head = temp_out.begin() + temp_out_size;
}
}
else
{
// We are writing to in but are out of space; switch to temp_out for the moment
out_is_in = false;
// Set size and pointer
out_size = temp_out.size();
out_head = temp_out.begin();
}
}
// Cap the out size to zstd_process_bytes_out_max
size_t process_bytes_out = min<size_t>(out_size, zstd_process_bytes_out_max);
ZSTD_outBuffer output = { out_head, process_bytes_out, 0 };
// Call the stream compression; the return value indicates remaining data in internal buffers,
// or an error code, which we need to check.
pending = ZSTD_compressStream2(cctx, &output, &input, flush);
if (ZSTD_isError(pending))
{
// Something went wrong; return the error code
return static_cast<unsigned>(pending);
}
// True number of bytes written
process_bytes_out = output.pos;
out_size -= process_bytes_out;
out_head += process_bytes_out;
// Number of bytes read
bytes_read_from_in += input.pos - prev_pos;
prev_pos = input.pos;
if (out_is_in)
{
// Update number of bytes written to in
bytes_written_to_in += process_bytes_out;
}
// Continue while not all input has been read, or while there is data pending in the internal
// buffers
} while (pending || (input.pos != input.size));
} while (in_size);
if (!out_is_in)
{
// We are done but the last writes were to temp_out
size_t bytes_in_temp_out = temp_out.size() - out_size;
// Resize in to fit the remaining data
in.resize(bytes_written_to_in + bytes_in_temp_out);
// Copy over the buffer to in
out_head = in.begin() + bytes_written_to_in;
memcpy(out_head, temp_out.cbegin(), bytes_in_temp_out);
bytes_written_to_in += bytes_in_temp_out;
}
else
{
// Just resize in to the right size
in.resize(bytes_written_to_in);
}
ZSTD_freeCCtx(cctx);
return ZSTD_error_no_error;
}
unsigned zstd_inflate_stream(
istream &in_stream, streamoff in_size, ostream &out_stream, MemoryPoolHandle pool)
{
// Clear the exception masks; this function returns an error code
// on failure rather than throws an IO exception.
auto in_stream_except_mask = in_stream.exceptions();
in_stream.exceptions(ios_base::goodbit);
auto out_stream_except_mask = out_stream.exceptions();
out_stream.exceptions(ios_base::goodbit);
auto in_stream_start_pos = in_stream.tellg();
auto in_stream_end_pos = in_stream_start_pos + in_size;
auto in(allocate<unsigned char>(buffer_size, pool));
auto out(allocate<unsigned char>(buffer_size, pool));
PointerStorage ptr_storage(pool);
ZSTD_customMem mem;
mem.customAlloc = zstd_alloc_impl;
mem.customFree = zstd_free_impl;
mem.opaque = &ptr_storage;
ZSTD_DCtx *dctx = ZSTD_createDCtx_advanced(mem);
if (!dctx)
{
// Failed to set up the context; there is something wrong with the allocator
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return ZSTD_error_GENERIC;
}
// Holds the return value of the decompression call. This is either the amount of data that remains to
// be flushed from internal buffers, or an error code.
size_t pending = 0;
while (true)
{
if (!in_stream.read(
reinterpret_cast<char *>(in.get()),
min(static_cast<streamoff>(buffer_size), in_stream_end_pos - in_stream.tellg())))
{
// Failed to read from stream
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return ZSTD_error_GENERIC;
}
ZSTD_inBuffer input = { in.get(), static_cast<size_t>(in_stream.gcount()), 0 };
if (!input.size)
{
break;
}
while (input.pos < input.size)
{
ZSTD_outBuffer output = { out.get(), buffer_size, 0 };
pending = ZSTD_decompressStream(dctx, &output, &input);
if (ZSTD_isError(pending))
{
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return static_cast<unsigned>(pending);
}
if (!out_stream.write(
reinterpret_cast<const char *>(out.get()), static_cast<streamsize>(output.pos)))
{
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return ZSTD_error_GENERIC;
}
}
}
ZSTD_freeDCtx(dctx);
in_stream.exceptions(in_stream_except_mask);
out_stream.exceptions(out_stream_except_mask);
return ZSTD_error_no_error;
}
void zstd_write_header_deflate_buffer(
DynArray<seal_byte> &in, void *header_ptr, ostream &out_stream, MemoryPoolHandle pool)
{
Serialization::SEALHeader &header = *reinterpret_cast<Serialization::SEALHeader *>(header_ptr);
auto ret = zstd_deflate_array_inplace(in, move(pool));
if (ZSTD_error_no_error != ret)
{
stringstream ss;
ss << "Zstandard compression failed with error code ";
ss << ret;
ss << " (" << ZSTD_getErrorName(ret) << ")";
throw logic_error(ss.str());
}
// Populate the header
header.compr_mode = compr_mode_type::zstd;
header.size = static_cast<uint64_t>(add_safe(sizeof(Serialization::SEALHeader), in.size()));
auto old_except_mask = out_stream.exceptions();
try
{
// Throw exceptions on ios_base::badbit and ios_base::failbit
out_stream.exceptions(ios_base::badbit | ios_base::failbit);
// Write the header and the data
out_stream.write(reinterpret_cast<const char *>(&header), sizeof(Serialization::SEALHeader));
out_stream.write(reinterpret_cast<const char *>(in.cbegin()), safe_cast<streamsize>(in.size()));
}
catch (...)
{
out_stream.exceptions(old_except_mask);
throw;
}
out_stream.exceptions(old_except_mask);
}
} // namespace ztools
} // namespace util
} // namespace seal
#endif