-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.hpp
623 lines (545 loc) · 17.1 KB
/
buffer.hpp
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
#pragma once
namespace jup {
// Forward declaration of Buffer, for the constructor of Buffer_view.
class Buffer;
/**
* A read-write object referencing a continuous memory region of a certain size
* with arbitrary contents. Supports iteration over the bytes. Has no ownership
* of any kind. This is a simple pointer + size combination.
*
* If you want to store a c-style string in here, use the size of the string
* without the terminating zero and call c_str() to extract the string, instead
* of data().
*/
struct Buffer_view_mut {
constexpr Buffer_view_mut(void* data = nullptr, int size = 0):
m_data{data}, m_size{size}
{
assert(data == nullptr ? size == 0 : size >= 0);
}
constexpr Buffer_view_mut(std::nullptr_t): Buffer_view_mut{} {}
Buffer_view_mut(Buffer& buf);
constexpr Buffer_view_mut(char* str):
Buffer_view_mut{str, (int)std::strlen(str)} {}
/**
* Construct from arbitrary object. This is not a constructor due to the
* obvious overloading problems.
*/
template<typename T>
constexpr static Buffer_view_mut from_obj(T& obj) {
return Buffer_view_mut {&obj, sizeof(obj)};
}
constexpr int size() const { return m_size; }
constexpr char* begin() { return (char*)m_data; }
constexpr char* end() { return (char*)m_data + m_size; }
constexpr char* data() { return begin(); }
constexpr char const* begin() const { return (char const*)m_data; }
constexpr char const* end() const { return (char const*)m_data + m_size; }
constexpr char const* data() const { return begin(); }
char& front() { return (*this)[0]; }
char& back() { return (*this)[size() - 1]; }
char front() const { return (*this)[0]; }
char back() const { return (*this)[size() - 1]; }
/**
* Provide access to the bytes, with bounds checking.
*/
char operator[] (int pos) const {
assert(0 <= pos and pos < size());
return data()[pos];
}
char& operator[] (int pos) {
assert(0 <= pos and pos < size());
return data()[pos];
}
/**
* Return a c-style string. Same as data, but asserts that the character
* just behind the last one is zero.
*/
char const* c_str() const {
assert(*(data() + size()) == 0);
return data();
}
/**
* Return whether the pointer is inside the buffer
*/
template <typename T>
bool inside(T const* ptr) const {
// duplicates Buffer::inside
return (void const*)begin() <= (void const*)ptr
and (void const*)(ptr + 1) <= (void const*)end();
}
/**
* Generate a simple hash of the contents of this Buffer_view_mut. An empty
* buffer must have a hash of 0.
*/
u64 get_hash() const;
/**
* Compare for byte-wise equality.
*/
bool operator== (Buffer_view_mut const& buf) const {
if (size() != buf.size()) return false;
return std::memcmp(data(), buf.data(), size()) == 0;
}
bool operator!= (Buffer_view_mut const& buf) const { return !(*this == buf); }
/**
* Return whether the buffer is valid and not empty.
*/
constexpr operator bool() const {
return data() and size();
}
operator std::string() const { return {data(), (std::size_t)size()}; }
void* m_data;
int m_size;
};
/**
* A read only object referencing a continuous memory region of a certain size
* with arbitrary contents. Supports iteration over the bytes. Has no ownership
* of any kind. This is a simple pointer + size combination.
*
* If you want to store a c-style string in here, use the size of the string
* without the terminating zero and call c_str() to extract the string, instead
* of data().
*/
struct Buffer_view {
constexpr Buffer_view(void const* data = nullptr, int size = 0):
m_data{data}, m_size{size}
{
assert(data == nullptr ? size == 0 : size >= 0);
}
constexpr Buffer_view(std::nullptr_t): Buffer_view{} {}
Buffer_view(Buffer_view_mut const& buf): m_data{buf.data()}, m_size{buf.size()} {}
Buffer_view(Buffer const& buf);
template<typename T>
constexpr Buffer_view(std::vector<T> const& vec):
Buffer_view{vec.data(), (int)(vec.size() * sizeof(T))} {}
template<typename T>
constexpr Buffer_view(std::basic_string<T> const& str):
Buffer_view{str.data(), (int)(str.size() * sizeof(T))} {}
constexpr Buffer_view(char const* str):
Buffer_view{str, (int)std::strlen(str)} {}
/**
* Construct from arbitrary object. This is not a constructor due to the
* obvious overloading problems.
*/
template<typename T>
constexpr static Buffer_view from_obj(T const& obj) {
return Buffer_view {&obj, sizeof(obj)};
}
constexpr int size() const { return m_size; }
constexpr char const* begin() const { return (char const*)m_data; }
constexpr char const* end() const { return (char const*)m_data + m_size; }
constexpr char const* data() const { return begin(); }
char front() const { return (*this)[0]; }
char back() const { return (*this)[size() - 1]; }
/**
* Provide access to the bytes, with bounds checking.
*/
char operator[] (int pos) const {
assert(0 <= pos and pos < size());
return data()[pos];
}
/**
* Return a c-style string. Same as data, but asserts that the character
* just behind the last one is zero.
*/
char const* c_str() const {
assert(*(data() + size()) == 0);
return data();
}
/**
* Return whether the pointer is inside the buffer
*/
template <typename T>
bool inside(T const* ptr) const {
// duplicates Buffer::inside
return (void const*)begin() <= (void const*)ptr
and (void const*)(ptr + 1) <= (void const*)end();
}
/**
* Generate a simple hash of the contents of this Buffer_view. An empty
* buffer must have a hash of 0.
*/
u64 get_hash() const;
/**
* Compare for byte-wise equality.
*/
bool operator== (Buffer_view const& buf) const {
if (size() != buf.size()) return false;
return std::memcmp(data(), buf.data(), size()) == 0;
}
bool operator!= (Buffer_view const& buf) const { return !(*this == buf); }
/**
* Compare lexicographically by bytes
*/
int compare(Buffer_view const& buf) const {
auto cmp1 = std::memcmp(data(), buf.data(), std::min(size(), buf.size()));
auto cmp2 = (size() > buf.size()) - (size() < buf.size());
return cmp1 ? cmp1 : cmp2;
}
bool operator< (Buffer_view const& buf) const { return compare(buf) < 0; }
/**
* Return whether the buffer is valid and not empty.
*/
constexpr explicit operator bool() const {
return data() and size();
}
operator std::string() const { return {data(), (std::size_t)size()}; }
void const* m_data;
int m_size;
};
using jup_str = Buffer_view;
inline std::ostream& operator<< (std::ostream& s, Buffer_view buf) {
s.write(buf.data(), buf.size());
return s;
}
struct Buffer_guard {
Buffer* buf;
int size_target;
bool trap_alloc;
Buffer_guard(): buf{nullptr}, size_target{0}, trap_alloc{false} {}
Buffer_guard(Buffer& buf);
Buffer_guard(Buffer& buf, int size_incr);
Buffer_guard(Buffer_guard&& g) {
std::swap(buf, g.buf);
std::swap(size_target, g.size_target);
std::swap(trap_alloc, g.trap_alloc);
}
Buffer_guard& operator= (Buffer_guard&& g) {
std::swap(buf, g.buf);
std::swap(size_target, g.size_target);
std::swap(trap_alloc, g.trap_alloc);
return *this;
}
~Buffer_guard() { free(); }
void free();
};
/**
* A handle for a continuous region of memory that can dynamically expand, if
* necessary. This is like std::vector<char> in many regards. It supports both
* move and copy semantics and has ownership of the managed memory (meaning that
* the memory is free'd an destruction). There are no guarantees made for the
* contents of uninitialized memory.
*
* There are three member variables:
* - the pointer to the memory, data()
* - the size of the allocated memory, capacity()
* - the amount of the memory that is used, size()
* These are used together in the various methods. Of course, you may decide to
* disregard size() completely and just use the block of memory.
*
* In debug mode (NDEBUG not defined) you can trap pointer invalidation due to
* resizing.
*/
class Buffer {
#ifndef NDEBUG
static_assert(sizeof(int) == 4, "Assuming 32bit ints for the bitmasks.");
#endif
public:
/**
* These do what you would expect them to.
*/
Buffer() {}
explicit Buffer(int capacity) {
reserve(capacity);
}
Buffer(Buffer const& buf) { append(buf); }
Buffer(Buffer&& buf) {
m_data = buf.m_data;
m_size = buf.m_size;
m_capacity = buf.m_capacity;
buf.m_data = nullptr;
buf.m_size = 0;
buf.m_capacity = 0;
}
~Buffer() { free(); }
Buffer& operator= (Buffer const& buf) {
reset();
append(buf);
return *this;
}
Buffer& operator= (Buffer&& buf) {
std::swap(m_data, buf.m_data);
std::swap(m_size, buf.m_size);
std::swap(m_capacity, buf.m_capacity);
return *this;
}
/**
* Ensure that the Buffer has a capacity of at least newcap. If the current
* capacity is bigger, this does nothing. Else, new memory is allocated and
* the contents of the current block are moved. The new capacity is at least
* twice the old one.
*/
void reserve(int newcap) {
if (capacity() < newcap) {
assert(not trap_alloc());
newcap = std::max(newcap, capacity() * 2);
if (m_data) {
m_data = (char*)std::realloc(m_data, newcap);
} else {
m_data = (char*)std::malloc(newcap);
}
// the trap_alloc flag is stored in m_capacity, don't disturb it
m_capacity += newcap - capacity();
assert(m_data);
}
}
/**
* Ensure that at least incr space remains in the buffer (as if
* reserve_space(incr) had been called). Returns a guard object that checks,
* upon its destruction, whether the size of buffer has increased by exactly
* incr bytes. Additionally, the trap_alloc flag is set for the lifetime of
* the guard object. Recommended usage:
* {
* auto guard = buffer.reserve_guard(size);
* // Do something that adds exactly size bytes to the buffer while
* // enjoying a lack of reallocation
* }
* // guard goes out of scope, ensuring that exactly size bytes have
* // been inserted.
*/
auto reserve_guard(int incr) {
reserve_space(incr);
return Buffer_guard {*this, incr};
}
/**
* Similar to reserve_guard, but does not check the size increase and only
* sets the trap_alloc flag.
*/
auto alloc_guard() {
return Buffer_guard {*this};
}
/**
* Append the contents of the memory to this buffer.
*/
void append(void const* buf, int buf_size) {
if (!buf_size) return;
assert(buf_size > 0 and buf);
if (capacity() < m_size + buf_size)
reserve(m_size + buf_size);
assert(capacity() >= m_size + buf_size);
std::memcpy(m_data + m_size, buf, buf_size);
m_size += buf_size;
}
void append(Buffer_view buffer) {
append(buffer.data(), buffer.size());
}
void append0(int count = 1) {
if (!count) return;
assert(count > 0);
if (capacity() < m_size + count)
reserve(m_size + count);
assert(capacity() >= count);
std::memset(m_data + m_size, 0, count);
m_size += count;
}
void pop_front(int i) {
m_size -= i;
std::memmove(m_data, m_data + i, m_size);
}
/**
* Change the size of the Buffer. Useful if you write to the memory
* manually.
*/
void resize(int nsize) {
m_size = nsize;
assert(m_size >= 0);
reserve(m_size);
}
void addsize(int incr) {
resize(m_size + incr);
}
/**
* Set the size to 0. Do not confuse this with free(), this does not
* actually release the memory.
*/
void reset() {
m_size = 0;
}
/**
* Free the memory. Leaves the buffer in a valid state.
*/
void free() {
assert(!trap_alloc());
std::free(m_data);
m_data = nullptr;
m_size = 0;
m_capacity = 0;
}
/**
* Release ownership of the memory, and return a Buffer_view of the valid region.
*/
Buffer_view release() {
Buffer_view result {begin(), size()};
m_data = nullptr;
m_size = 0;
m_capacity = 0;
return result;
}
/**
* Take ownership of the memory, free the current memory, if any.
*/
void take(void* memory, int size) {
free();
m_data = (char*)memory;
m_size = 0;
m_capacity = size;
}
int size() const { return m_size; }
int capacity() const {
// If in debug mode, the most-significant bit of m_capacity is serving
// as the trap_alloc flag.
#ifndef NDEBUG
return m_capacity & 0x7fffffff;
#else
return m_capacity;
#endif
}
/**
* Returns whether any pointer invalidation for pointers into the buffer may
* occur. If this is set, the program will abort on reallocation, which is
* useful for debugging.
*/
bool trap_alloc() const {
#ifndef NDEBUG
return ((u32)m_capacity >> 31);
#else
return false;
#endif
}
/**
* Maybe set the trap_alloc() flag and return its value. Consider using the
* reserver_guard or alloc_guard instead.
*/
bool trap_alloc(bool value) {
#ifndef NDEBUG
m_capacity ^= (u32)(trap_alloc() ^ value) << 31;
#endif
return trap_alloc();
}
/**
* space() is the amount of space left in the Buffer (the capacity minus the
* size).
*/
int space() const {return capacity() - size();}
/**
* Ensure, that atleast space is available.
*/
void reserve_space(int atleast) {
reserve(size() + atleast);
}
/**
* A helper to save you some casting. Returns the memory offset by offset
* bytes interpreted as a T. Ensures that that much memory is
* available. This is of course not type-safe in any way, shape, or form.
*/
template <typename T>
T& get(int offset = 0) {
reserve(offset + sizeof(T));
return *(T*)(m_data + offset);
}
template <typename T>
T const& get(int offset = 0) const {
assert(size() >= (int)(offset + sizeof(T)));
return *(T const*)(m_data + offset);
}
/**
* Like get, but constructs the object in-place.
*/
template <typename T, typename... Args>
T& emplace(int offset = 0, Args&&... args) {
int end = offset + sizeof(T);
reserve(end);
if (m_size < end) resize(end);
return *(new(m_data + offset) T {std::forward<Args>(args)...});
}
/**
* Like emplace, but contructs the object at the end.
*/
template <typename T, typename... Args>
T& emplace_back(Args&&... args) {
return emplace<T>(size(), std::forward<Args>(args)...);
}
char* begin() {return m_data;}
char* end() {return m_data + m_size;}
char* data() {return begin();}
char const* begin() const {return m_data;}
char const* end() const {return m_data + m_size;}
char const* data() const {return begin();}
char& front() { return (*this)[0]; }
char& back() { return (*this)[size() - 1]; }
char front() const { return (*this)[0]; }
char back() const { return (*this)[size() - 1]; }
/**
* Provide access to the buffer, with bounds checking.
*/
char& operator[] (int pos) {
assert(0 <= pos and pos < size());
return data()[pos];
}
char operator[] (int pos) const {
assert(0 <= pos and pos < size());
return data()[pos];
}
void write_to_file(Buffer_view filename, bool binary = true) {
std::ofstream o;
auto flags = (binary ? (std::ios::out | std::ios::binary) : std::ios::out);
o.open(filename.c_str(), flags);
o.write(data(), size());
o.close();
}
void read_from_file(Buffer_view filename, bool binary = true, int maxsize = -1) {
std::ifstream i;
auto flags = (binary ? (std::ios::ate | std::ios::binary) : std::ios::ate);
i.open(filename.c_str(), flags);
std::streamsize fsize = i.tellg();
assert(maxsize == -1 or fsize <= (std::streamsize)maxsize);
i.seekg(0, std::ios::beg);
reserve_space(fsize);
i.read(end(), fsize);
assert(binary ? i.gcount() == fsize : i.gcount() <= fsize);
addsize(i.gcount());
i.close();
}
/**
* Return whether the pointer is inside the buffer
*/
// duplicates Buffer_view::inside and Buffer_view::valid
template <typename T>
bool inside(T const* ptr) const {
return inside((char const*)ptr, sizeof(T));
}
bool inside(char const* ptr, int size) const {
return (void const*)begin() <= (void const*)ptr
and (void const*)(ptr + size) <= (void const*)end();
}
template <typename T>
bool valid(T const* ptr) const {
return valid((char const*)ptr, sizeof(T));
}
bool valid(char const* ptr, int size) const {
return (void const*)begin() <= (void const*)ptr
and (void const*)(ptr + size) <= (void const*)(data() + capacity());
}
char* m_data = nullptr;
int m_size = 0, m_capacity = 0;
};
inline Buffer_guard::Buffer_guard(Buffer& buf):
buf{&buf}, size_target{-1}, trap_alloc{buf.trap_alloc()}
{
buf.trap_alloc(true);
}
inline Buffer_guard::Buffer_guard(Buffer& buf, int size_incr):
buf{&buf}, size_target{buf.size() + size_incr}, trap_alloc{buf.trap_alloc()}
{
buf.trap_alloc(true);
}
inline void Buffer_guard::free() {
if (buf) {
assert(size_target == -1 or buf->size() == size_target);
buf->trap_alloc(trap_alloc);
buf = nullptr;
}
}
inline Buffer_view::Buffer_view(Buffer const& buf):
Buffer_view{buf.data(), buf.size()} {}
} /* end of namespace jup */