-
Notifications
You must be signed in to change notification settings - Fork 0
/
compact_vector.h
905 lines (747 loc) · 19 KB
/
compact_vector.h
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
#pragma once
#include <cstddef>
#include <memory>
#include <utility>
#include <limits>
#include <type_traits>
#include <algorithm>
template <
class T,
int compact_max_size = -1,
class allocator_type = std::allocator<T>>
class compact_vector
{
public:
struct full_storage
{
T* begin = nullptr;
size_t capacity = 0;
T* get(size_t i) noexcept
{
return begin + i;
}
const T* get(size_t i) const noexcept
{
return begin + i;
}
};
static constexpr size_t compact_default_capacity = sizeof(full_storage) / sizeof(T);
static constexpr size_t compact_default_capacity_nonzero = compact_default_capacity == 0 ? 1 : compact_default_capacity;
static constexpr size_t compact_capacity = compact_max_size <= 0 ? compact_default_capacity_nonzero : compact_max_size;
static constexpr size_t vector_max_size = std::numeric_limits<size_t>::max() >> 1;
struct compact_storage
{
T buffer[compact_capacity];
T* get(size_t i) noexcept
{
return &buffer[i];
}
const T* get(size_t i) const noexcept
{
return &buffer[i];
}
};
// Empty Base Optimization
struct size_allocator_pair : public allocator_type
{
// bitset 1000...000
static const size_t zero_compact = size_t(1) << (8 * sizeof(size_t) - 1);
size_allocator_pair(const allocator_type& base) :
allocator_type(base)
{}
size_allocator_pair(allocator_type&& base) :
allocator_type(base)
{}
size_allocator_pair() :
allocator_type(allocator_type())
{}
allocator_type* get_allocator()
{
return this;
}
const allocator_type* get_allocator() const
{
return this;
}
size_t get_size() const noexcept
{
return size & vector_max_size;
}
bool is_compact() const noexcept
{
return size & zero_compact;
}
void set_size(size_t new_size, bool is_compact)
{
#ifdef COMPACT_VECTOR_DEBUG
if (new_size > vector_max_size)
throw std::exception(u8"попытка создать вектор больше max_size");
#endif
if (is_compact)
size = zero_compact | new_size;
else
size = new_size;
}
private:
size_t size = zero_compact;
};
union
{
compact_storage compact;
full_storage full;
};
size_allocator_pair size_allocaltor;
public:
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = T*; // todo
using const_reverse_iterator = const T*; // todo
using this_type = compact_vector<T, compact_max_size, allocator_type>;
/// constructor: default
/*!
Constructs an empty container, with no elements.
*/
explicit compact_vector(const allocator_type& alloc = allocator_type()) :
size_allocaltor(alloc)
{}
/// constructor: fill
/*!
Constructs a container with n elements.
*/
explicit compact_vector(size_t n) :
size_allocaltor()
{
resize(n);
}
/// constructor: fill
/*!
Constructs a container with n elements. Each element is a copy of val.
*/
compact_vector(size_t n, const T& val, const allocator_type& alloc = allocator_type()) :
size_allocaltor(alloc)
{
resize(n, val);
}
/// constructor:: range
/*!
Constructs a container with as many elements as the range [first,last),
with each element emplace-constructed from its corresponding element in that range, in the same order.
*/
template <class InputIterator>
compact_vector(InputIterator first, InputIterator last, const allocator_type& alloc = allocator_type()) :
size_allocaltor(alloc)
{
assign(first, last);
}
/// constructor: copy
/*!
Constructs a container with a copy of each of the elements in x, in the same order.
*/
compact_vector(const this_type& x) :
size_allocaltor(x.get_allocator())
{
reserve(x.size());
copy_data(x.begin(), x.end(), begin());
}
/// constructor: copy
/*!
Constructs a container with a copy of each of the elements in x, in the same order.
*/
compact_vector(const this_type& x, const allocator_type& alloc) :
size_allocaltor(alloc)
{
reserve(x.size());
copy_data(x.begin(), x.end(), begin());
}
/// constructor: move
/*!
Constructs a container that acquires the elements of x.
If alloc is specified and is different from x's allocator, the elements are moved.
Otherwise, no elements are constructed (their ownership is directly transferred).
x is left in an unspecified but valid state.
*/
compact_vector(this_type&& x) :
size_allocaltor(x.get_allocator())
{
swap(x);
}
/// constructor: move
/*!
Constructs a container that acquires the elements of x.
If alloc is specified and is different from x's allocator, the elements are moved.
Otherwise, no elements are constructed (their ownership is directly transferred).
x is left in an unspecified but valid state.
*/
compact_vector(this_type&& x, const allocator_type& alloc) :
size_allocaltor(alloc)
{
swap(x);
}
/// constructor: initializer list
/*!
Constructs a container with a copy of each of the elements in il, in the same order.
*/
compact_vector(std::initializer_list<T> il, const allocator_type& alloc = allocator_type()) :
size_allocaltor(alloc)
{
assign(il);
}
/// destructor
~compact_vector()
{
destruct();
}
/// assign: range
template <class InputIterator>
void assign(InputIterator first, InputIterator last)
{
clear();
insert(begin(), first, last);
}
/// assign: fill
void assign(size_t n, const T& val)
{
clear();
resize(n, val);
}
/// assign: initializer list
void assign(std::initializer_list<T> il)
{
clear();
insert(begin(), il);
}
T& at(size_t n)
{
if (n >= size())
throw std::out_of_range(u8"compact_vector out of range");
return (*this)[n];
}
const T& at(size_t n) const
{
if (n >= size())
throw std::out_of_range(u8"compact_vector out of range");
return (*this)[n];
}
T& back()
{
return (*this)[size() - 1];
}
const T& back() const
{
return (*this)[size() - 1];
}
iterator begin() noexcept
{
if (is_compact())
return compact.get(0);
else
return full.get(0);
}
const_iterator begin() const noexcept
{
if (is_compact())
return compact.get(0);
else
return full.get(0);
}
size_t capacity() const noexcept
{
if (is_compact())
return compact_capacity;
return full.capacity;
}
const_iterator cbegin() const noexcept
{
if (is_compact())
return compact.get(0);
else
return full.get(0);
}
const_iterator cend() const noexcept
{
if (is_compact())
return compact.get(size() - 1);
else
return full.get(size() - 1);
}
void clear() noexcept
{
call_destructors(begin(), end());
size_allocaltor.set_size(0, is_compact());
}
const_reverse_iterator crbegin() const noexcept; // todo
const_reverse_iterator crend() const noexcept; // todo
T* data() noexcept
{
return begin();
}
const T* data() const noexcept
{
return begin();
}
template <class... Args>
iterator emplace(const_iterator position, Args&&... args); // todo
template <class... Args>
void emplace_back(Args&&... args)
{
static const size_t args_size = sizeof...(Args);
size_t c = capacity();
size_t required_size = size() + args_size;
while (required_size > c) c = 2 * c;
reserve(c);
::new(end()) value_type(std::forward<Args>(args)...);
set_new_size(required_size);
}
bool empty() const noexcept
{
return size() == 0;
}
iterator end() noexcept
{
if (is_compact())
return compact.get(size());
else
return full.get(size());
}
const_iterator end() const noexcept
{
if (is_compact())
return compact.get(size() - 1);
else
return full.get(size() - 1);
}
iterator erase(const_iterator position)
{
iterator p = const_cast<iterator>(position);
iterator e = end();
if (p <= e)
copy_data(p + 1, e, p);
e--;
e->~T();
set_new_size(size() - 1);
return p;
}
iterator erase(const_iterator first, const_iterator last)
{
iterator f = const_cast<iterator>(first);
iterator l = const_cast<iterator>(last);
iterator e = end();
if (f > l)
return nullptr;
if (l <= e)
copy_data(l, e, f);
call_destructors(f + (e - l), e);
set_new_size(size() - (e - l));
return f;
}
T& front()
{
return *begin();
}
const T& front() const
{
return *begin();
}
allocator_type get_allocator() const noexcept
{
return *size_allocaltor.get_allocator();
}
/// insert: single element
iterator insert(const_iterator position, const T& val)
{
return insert(position, 1, val);
}
/// insert: fill
iterator insert(const_iterator position, size_t n, const T& val)
{
size_t p = end() - position;
resize(size() + n, val);
iterator i = end() - n - 1;
iterator j = end() - 1;
for (; p > 0; p--, i--, j--)
std::iter_swap(i, j);
return i;
}
/// insert: range
template <class InputIterator>
iterator insert(const_iterator position, InputIterator first, InputIterator last)
{
size_t n = 0;
for (InputIterator i = first; i != last; i++, n++);
if (n == 0)
return end();
size_t p = end() - position;
resize(size() + n, *first);
iterator i = end() - n - 1;
iterator j = end() - 1;
for (size_t counter = p; counter > 0; counter--, i--, j--)
std::iter_swap(i, j);
i = begin() + p;
for (InputIterator j = first; j != last; j++, i++)
*i = *j;
return begin() + p;
}
/// insert: move
iterator insert(const_iterator position, T&& val)
{
return emplace(position, std::move(value));
}
/// initializer list
iterator insert(const_iterator position, std::initializer_list<T> il)
{
if (il.size() == 0)
return end();
size_t p = end() - position;
resize(size() + il.size(), *il.begin());
iterator i = end() - il.size() - 1;
iterator j = end() - 1;
for (size_t counter = p; counter > 0; counter--, i--, j--)
std::iter_swap(i, j);
i = begin() + p;
for (auto& e : il)
{
*i = e;
i++;
}
return begin() + p;
}
size_t max_size() const noexcept
{
return vector_max_size;
}
// operator=, copy
compact_vector& operator= (const compact_vector& x)
{
if (this != &x)
{
clear();
reserve(x.size());
copy_data(x.begin(), x.end(), begin());
}
return *this;
}
// operator=, move
compact_vector& operator= (compact_vector&& x)
{
if (this != &x)
{
destruct();
swap(x);
}
return *this;
}
// operator=, initializer list
compact_vector& operator= (std::initializer_list<T> il)
{
clear();
reserve(il.size());
copy_data(il.begin(), il.end(), begin());
return *this;
}
T& operator[] (size_t n)
{
if (is_compact())
return *compact.get(n);
else
return *full.get(n);
}
const T& operator[] (size_t n) const
{
if (is_compact())
return *compact.get(n);
else
return *full.get(n);
}
void pop_back()
{
resize(size() - 1);
}
void push_back(const T& val)
{
auto size = size() + 1;
if (size > capacity())
reserve(2 * capacity());
::new(end()) T(val);
set_new_size(size);
}
void push_back(T&& val)
{
auto size = size() + 1;
if (size > capacity())
reserve(2 * capacity());
::new(end()) T(std::move(val));
set_new_size(size);
}
reverse_iterator rbegin() noexcept; // todo
const_reverse_iterator rbegin() const noexcept; // todo
reverse_iterator rend() noexcept; // todo
const_reverse_iterator rend() const noexcept; // todo
void reserve(size_t n)
{
if (n <= capacity())
return;
if (n > max_size())
std::length_error(u8"попытка выделить памяти больше чем max_size()");
grow(n);
}
void resize(size_t n)
{
if (n > size())
{
size_t c = capacity();
while (n > c) c = 2 * c;
reserve(c);
add_to_end(n);
}
else
{
call_destructors(begin() + n, end());
set_new_size(n);
}
}
void resize(size_t n, const T& val)
{
if (n > size())
{
size_t c = capacity();
while (n > c) c = 2 * c;
reserve(c);
add_to_end(n, val);
}
else
{
call_destructors(begin() + n, end());
set_new_size(n);
}
}
void shrink_to_fit()
{
if (is_compact())
return;
if (size() >= compact_capacity)
{
size_t new_capacity = size();
auto ptr_begin = get_allocator().allocate(new_capacity);
move_data(begin(), end(), ptr_begin);
get_allocator().deallocate(full.begin, full.capacity);
full.begin = ptr_begin;
full.capacity = new_capacity;
}
else
{
auto b = full.begin;
auto c = full.capacity;
move_data(b, b + c, compact.get(0));
get_allocator().deallocate(b, c);
size_allocaltor.set_size(size(), true);
}
}
size_t size() const noexcept
{
return this->size_allocaltor.get_size();
}
void swap(compact_vector& x)
{
if (is_compact())
{
if (x.is_compact())
swap_compact_compact(x);
else
swap_compact_full(x);
}
else
{
if (x.is_compact())
swap_full_compact(x);
else
swap_full_full(x);
}
}
#ifdef COMPACT_VECTOR_DEBUG
public:
#else
private:
#endif
bool is_compact() const noexcept
{
return size_allocaltor.is_compact();
}
void destruct()
{
call_destructors(begin(), end());
if (!is_compact())
get_allocator().deallocate(full.begin, full.capacity);
size_allocaltor.set_size(0, true);
}
// swap для случая, когда this->is_compact() == false && x.is_compact() == false
void swap_full_full(this_type& x)
{
#ifdef COMPACT_VECTOR_DEBUG
if (is_compact() != false || x.is_compact() != false)
throw std::exception(u8"неправильный вызов swap_full_full");
#endif // COMPACT_VECTOR_DEBUG
std::swap(size_allocaltor, x.size_allocaltor);
std::swap(full.begin, x.full.begin);
std::swap(full.capacity, x.full.capacity);
}
// swap для случая, когда this->is_compact() == true && x.is_compact() == false
void swap_compact_full(this_type& x)
{
#ifdef COMPACT_VECTOR_DEBUG
if (is_compact() != true || x.is_compact() != false)
throw std::exception(u8"неправильный вызов swap_compact_full");
#endif // COMPACT_VECTOR_DEBUG
auto x_begin = x.full.begin;
auto x_capacity = x.full.capacity;
move_data(begin(), end(), x.compact.get(0));
full.begin = x_begin;
full.capacity = x_capacity;
std::swap(size_allocaltor, x.size_allocaltor);
}
// swap для случая, когда this->is_compact() == false && x.is_compact() == true
void swap_full_compact(this_type& x)
{
#ifdef COMPACT_VECTOR_DEBUG
if (is_compact() != false || x.is_compact() != true)
throw std::exception(u8"неправильный вызов swap_full_compact");
#endif // COMPACT_VECTOR_DEBUG
auto this_begin = full.begin;
auto this_capacity = full.capacity;
move_data(x.begin(), x.end(), compact.get(0));
x.full.begin = x_begin;
x.full.capacity = x_capacity;
std::swap(size_allocaltor, x.size_allocaltor);
}
// swap для случая, когда this->is_compact() == true && x.is_compact() == true
void swap_compact_compact(this_type& x)
{
#ifdef COMPACT_VECTOR_DEBUG
if (is_compact() != true || x.is_compact() != true)
throw std::exception(u8"неправильный вызов swap_compact_compact");
#endif // COMPACT_VECTOR_DEBUG
swap_compact_compact(x, std::is_trivially_copyable<T>::type());
}
void swap_compact_compact(this_type& x, std::integral_constant<bool, true>)
{
compact_storage tmp;
std::memcpy(&tmp, &compact, sizeof(compact_storage));
std::memcpy(&compact, &x.compact, sizeof(compact_storage));
std::memcpy(&x.compact, &tmp, sizeof(compact_storage));
std::swap(size_allocaltor, x.size_allocaltor);
}
void swap_compact_compact(this_type& x, std::integral_constant<bool, false>)
{
size_t s1 = size();
size_t s2 = x.size();
size_t s = std::max(s1, s2);
for (size_t i = 0; i < s; i++)
{
if (i < s1 && i < s2)
{
std::iter_swap(compact.get(i), x.compact.get(i));
}
else if (i < s2)
{
::new(compact.get(i)) T(std::move(*x.compact.get(i)));
x.compact.get(i)->~T();
}
else
{
::new(x.compact.get(i)) T(std::move(*compact.get(i)));
compact.get(i)->~T();
}
}
std::swap(size_allocaltor, x.size_allocaltor);
}
template<typename InputIterator>
static void call_destructors(InputIterator first, InputIterator last)
{
call_destructors(first, last, std::is_trivial<T>::type());
}
// для тривиальных типов деструктор вызывать не нужно
template<typename InputIterator>
static void call_destructors(InputIterator first, InputIterator last, std::integral_constant<bool, true>)
{
}
// для нетривиальных типов вызывается деструктор
template<typename InputIterator>
static void call_destructors(InputIterator first, InputIterator last, std::integral_constant<bool, false>)
{
for (; first != last; first++)
first->~T();
}
void grow(size_t new_size)
{
#ifdef COMPACT_VECTOR_DEBUG
if (new_size <= capacity())
throw std::exception(u8"попытка уменьшить размер вектора");
#endif // COMPACT_VECTOR_DEBUG
auto ptr_begin = get_allocator().allocate(new_size);
move_data(begin(), end(), ptr_begin);
if (!is_compact())
get_allocator().deallocate(full.begin, full.capacity);
full.begin = ptr_begin;
full.capacity = new_size;
if (is_compact())
this->size_allocaltor.set_size(size(), false);
}
void add_to_end(size_t n)
{
#ifdef COMPACT_VECTOR_DEBUG
if (size() > n)
throw new std::exception(u8"попытка увеличить вектор на отрицательное число");
#endif // COMPACT_VECTOR_DEBUG
auto end_ptr = end();
for (auto i = n - size(); i > 0; i--, end_ptr++)
::new (end_ptr) T();
set_new_size(n);
}
void add_to_end(size_t n, const T& val)
{
#ifdef COMPACT_VECTOR_DEBUG
if (size() > n)
throw new std::exception(u8"попытка увеличить вектор на отрицательное число");
#endif // COMPACT_VECTOR_DEBUG
auto end_ptr = end();
for (auto i = n - size(); i > 0; i--, end_ptr++)
::new (end_ptr) T(val);
set_new_size(n);
}
void set_new_size(size_t new_size)
{
this->size_allocaltor.set_size(new_size, is_compact());
}
static void move_data(iterator first, iterator last, iterator target)
{
move_data(first, last, target, std::is_trivially_copyable<T>::type());
}
// для тривиальных типов можно использовать memcpy
static void move_data(iterator first, iterator last, iterator target, std::integral_constant<bool, true>)
{
std::memcpy(target, first, last - first);
}
// для нетривиальных типов вызывается std::move
static void move_data(iterator first, iterator last, iterator target, std::integral_constant<bool, false>)
{
for (; first != last; first++, target++)
::new(target) T(std::move(*first));
call_destructors(first, last);
}
static void copy_data(const_iterator first, const_iterator last, iterator target)
{
copy_data(first, last, target, std::is_trivially_copyable<T>::type());
}
// для тривиальных типов можно использовать memcpy
static void copy_data(const_iterator first, const_iterator last, iterator target, std::integral_constant<bool, true>)
{
std::memcpy(target, first, last - first);
}
// для нетривиальных типов вызывается поэлементное копирование
static void copy_data(const_iterator first, const_iterator last, iterator target, std::integral_constant<bool, false>)
{
for (; first != last; first++, target++)
{
*target = *first;
}
}
};