File: shared_object.h

package info (click to toggle)
polymake 4.14-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 35,888 kB
  • sloc: cpp: 168,933; perl: 43,407; javascript: 31,575; ansic: 3,007; java: 2,654; python: 632; sh: 268; xml: 117; makefile: 61
file content (1305 lines) | stat: -rw-r--r-- 42,423 bytes parent folder | download | duplicates (2)
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
/* Copyright (c) 1997-2024
   Ewgenij Gawrilow, Michael Joswig, and the polymake team
   Technische Universität Berlin, Germany
   https://polymake.org

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
--------------------------------------------------------------------------------
*/

#pragma once

#include "polymake/internal/iterators.h"
#include "polymake/internal/operations.h"

#include <algorithm>
#include <memory>
#include <cstring>
#include <limits>
#include <cassert>

namespace pm {

template <typename> class CopyOnWriteTag;
template <typename> class PrefixDataTag;
template <typename> class AliasHandlerTag;
template <typename> class DivorceHandlerTag;

class nop_shared_alias_handler {
protected:
   template <typename Master> static
   void CoW(Master *me, Int)
   {
      me->divorce();
   }

   static bool preCoW(Int) { return false; }
   static bool need_postCoW() { return false; }

   template <typename Master> static
   void postCoW(Master*,bool) {}

   static bool is_owner() { return true; }
public:
   void swap(nop_shared_alias_handler&) {}
   friend void relocate(nop_shared_alias_handler*, nop_shared_alias_handler*) {}
};

struct nop_divorce_handler {
   template <typename Rep, bool copied>
   Rep* operator() (Rep *body, bool_constant<copied>) const { return body; }
   void swap(nop_divorce_handler&) {}
   friend void relocate(nop_divorce_handler*, nop_divorce_handler*) {}
};

class shared_alias_handler {
protected:
   struct AliasSet {
      struct alias_array {
         Int n_alloc;
         AliasSet* aliases[1];
      };
      union {
         alias_array* set;
         AliasSet* owner;
      };
      Int n_aliases;

      static alias_array* allocate(size_t n)
      {
         allocator alloc;
         alias_array* a = (alias_array*)alloc.allocate(sizeof(alias_array) + (n-1)*sizeof(AliasSet*));
         a->n_alloc = n;
         return a;
      }
      static alias_array* reallocate(alias_array* a)
      {
         alias_array* n = allocate(a->n_alloc+3);
         std::memcpy(n->aliases, a->aliases, a->n_alloc * sizeof(AliasSet*));
         deallocate(a);
         return n;
      }
      static void deallocate(alias_array* a)
      {
         allocator alloc;
         alloc.deallocate(a, sizeof(alias_array) + (a->n_alloc-1)*sizeof(AliasSet*));
      }

      void remove(AliasSet* alias)
      {
         --n_aliases;
         for (AliasSet **s = set->aliases, **end = s+n_aliases; s < end; ++s)
            if (*s == alias) {
               *s = set->aliases[n_aliases];
               break;
            }
      }

      void forget()
      {
         if (n_aliases > 0) {
            for (AliasSet **s = set->aliases, **end = s+n_aliases; s < end; ++s)
               (*s)->owner = nullptr;
            n_aliases = 0;
         }
      }

      AliasSet() : set(nullptr), n_aliases(0) {}

      ~AliasSet()
      {
         if (set) {
            if (n_aliases >= 0) {
               forget();
               deallocate(set);
            } else {
               owner->remove(this);
            }
         }
      }

      AliasSet(const AliasSet& s2)
      {
         if (__builtin_expect(s2.n_aliases < 0, 0)) {
            if (s2.owner) {
               enter(*s2.owner);
            } else {
               // even if the original owner has gone, we can still copy the aliases
               n_aliases = -1;
               owner = nullptr;
            }
         } else {
            set = nullptr;
            n_aliases = 0;
         }
      }

   private:
      void operator=(const AliasSet&) = delete;
   public:
      void enter(AliasSet& ow)
      {
         n_aliases = -1;
         owner = &ow;
         if (!ow.set)
            ow.set = allocate(3);
         else if (ow.n_aliases == ow.set->n_alloc)
            ow.set = reallocate(ow.set);
         ow.set->aliases[ow.n_aliases++] = this;
      }

      bool is_owner() const { return n_aliases >= 0; }

      typedef AliasSet** iterator;
      iterator begin() const { return set->aliases; }
      iterator end() const { return set->aliases + n_aliases; }

      friend void relocate(AliasSet* from, AliasSet* to)
      {
         to->set = from->set;
         to->n_aliases = from->n_aliases;
         to->relocated(from);
      }

      void swap(AliasSet& s)
      {
         std::swap(set, s.set);
         std::swap(n_aliases, s.n_aliases);
         relocated(&s);
         s.relocated(this);
      }

      shared_alias_handler* to_handler() { return reverse_cast(this, &shared_alias_handler::al_set); }

   protected:
      void relocated(AliasSet* from)
      {
         if (set) {
            if (is_owner()) {
               for (auto alias_ptr : *this) alias_ptr->owner = this;
            } else {
               AliasSet** it = owner->set->aliases;
               while (*it != from) ++it;
               *it = this;
            }
         }
      }
   };

   AliasSet al_set;

   template <typename Master>
   void CoW(Master* me, Int refc);

   bool preCoW(Int refc) const
   {
      return is_owner() || al_set.owner && refc > al_set.owner->n_aliases+1;
   }

   bool need_postCoW() const
   {
      return al_set.n_aliases > 0;
   }

   template <typename Master>
   void postCoW(Master* me, bool owner_checked = false);

   template <typename Master>
   void divorce_aliases(Master* me)
   {
      me->divorce(al_set.owner->to_handler());
      for (auto alias_ptr : *al_set.owner)
         if (alias_ptr != &al_set) me->divorce(alias_ptr->to_handler());
   }

   bool is_owner() const { return al_set.is_owner(); }

public:
   void make_mutable_alias(shared_alias_handler& owner)
   {
      if (al_set.n_aliases == 0)
         al_set.enter(owner.al_set);
   }

   friend void relocate(shared_alias_handler* from, shared_alias_handler* to)
   {
      relocate(&from->al_set, &to->al_set);
   }

   void swap(shared_alias_handler& s) { al_set.swap(s.al_set); }

   void drop()
   {
      assert(al_set.n_aliases < 0);
      al_set.owner->remove(&al_set);
      al_set.owner = nullptr;
      al_set.n_aliases = 0;
   }
};

class shared_object_secrets {
protected:
   template <typename prefix_type=nothing>
   struct rep {
      // reference counter: number of hosts
      Int refc;
      // number of objects
      std::pair<size_t, prefix_type> size_and_prefix;

      // prevent from being ever destroyed
      rep() : refc(1) { size_and_prefix.first = 0; }

      rep(const prefix_type& p) : refc(1), size_and_prefix(0, p) {}
   };

   static rep<> empty_rep;
};

/** Automatic pointer to shared data

    This class implements an automatic pointer to a data object that can be shared
    among several hosts. The data instance remains shared as far as all hosts it is attached to
    don't attempt to change it (read-only access). The host that wants to get read-write access
    to the data automatically obtains a new copy, while its former partners continue
    sharing the old one.

    In that way, a copy of the host always shares the data instance with the original host.
    Assignment to a host causes it to detach the old data instance and share the new one with
    the host being assigned from.

    The data instance is destroyed together with the last host is is attached to.

    @tmplparam Object type of the attached object
    @index tools Automatic Pointers
*/
template <typename Object, typename... TParams>
class shared_object
   : public mtagged_list_extract<typename mlist_wrap<TParams...>::type, AliasHandlerTag, nop_shared_alias_handler>::type
   , protected shared_object_secrets {
   friend class nop_shared_alias_handler;
   friend class shared_alias_handler;
protected:
   typedef typename mlist_wrap<TParams...>::type params;
   typedef typename mtagged_list_extract<params, AliasHandlerTag, nop_shared_alias_handler>::type alias_handler;
   typedef typename mtagged_list_extract<params, DivorceHandlerTag, nop_divorce_handler>::type divorce_handler;

   static constexpr bool copy_on_write = tagged_list_extract_integral<params, CopyOnWriteTag>(true);

   struct rep {
      /// the attached object itself
      Object obj;
      /// reference counter: number of hosts
      Int refc;
   private:
      static rep* allocate()
      {
         allocator alloc;
         rep* r = (rep*)alloc.allocate(sizeof(rep));
         r->refc = 1;
         return r;
      }

      static void deallocate(rep* r)
      {
         allocator alloc;
         alloc.deallocate(r, sizeof(rep));
      }

      static void empty(shared_object* owner)
      {
         if (owner) {
            rep* r = reverse_cast(&empty_rep.refc, &rep::refc);
            ++r->refc;
            owner->body = r;
         }
      }

      template <typename PointedObject>
      static void destroy(PointedObject* o)
      {
         destroy_at(o);
      }

   public:
      template <typename... Args>
      static rep* init(shared_object* owner, rep* r, std::true_type, Args&&... args)
      {
         construct_at(&r->obj, std::forward<Args>(args)...);
         return r;
      }

      template <typename... Args>
      static rep* init(shared_object* owner, rep* r, std::false_type, Args&&... args)
      {
         try {
            construct_at(&r->obj, std::forward<Args>(args)...);
         } catch (...) {
            deallocate(r);
            empty(owner);
            throw;
         }
         return r;
      }

      template <typename Operation>
      rep* apply(shared_object* owner, const Operation& op)
      {
         rep *r=allocate();
         try {
            op(&r->obj, obj);
         } catch (...) {
            deallocate(r);
            empty(owner);
            throw;
         }
         return r;
      }

      template <typename... Args>
      static rep* construct(shared_object* owner, Args&&... args)
      {
         return init(owner, allocate(), std::is_nothrow_constructible<Object, Args...>(), std::forward<Args>(args)...);
      }

      void destroy()
      {
         destroy(&obj);
      }

      static void destruct(rep *r)
      {
         r->destroy();
         deallocate(r);
      }
   };

   rep *body;
   divorce_handler divorce_hook;

   // Detache the object or delete it.
   void leave()
   {
      if (! --body->refc) rep::destruct(body);
   }

   // Create an own object instance and decrease the reference counter of the old one.
   void divorce()
   {
      --body->refc;
      body=divorce_hook(rep::construct(this, const_cast<const Object&>(body->obj)), std::true_type());
   }

   void divorce(alias_handler* al)
   {
      shared_object* o=static_cast<shared_object*>(al);
      o->body->refc--;
      o->body=body;
      body->refc++;
   }

   shared_object(rep* p) : body(p) {}
public:
   /// Create the attached object with its default constructor.
   shared_object()
      : body(rep::construct(nullptr)) {}

   /// Create the attached object from given arguments.
   template <typename... Args>
   explicit shared_object(Args&&... args)
      : body(rep::construct(nullptr, std::forward<Args>(args)...)) {}

   /// Share the object attached to @c s.
   shared_object(const shared_object& s)
      : alias_handler(s), body(s.body) { ++body->refc; }

   // overrule the greedy constructor template
   shared_object(shared_object& s)
      : shared_object(const_cast<const shared_object&>(s)) {}

   // no moves
   shared_object(shared_object&& s) = delete;

   ~shared_object() { leave(); }

   /// Detach or delete the old instance, share the one attached to @c s.
   shared_object& operator= (const shared_object& s)
   {
      ++s.body->refc;
      leave();
      body=divorce_hook(s.body, std::false_type());
      return *this;
   }

   shared_object& operator= (shared_object&& s) = delete;

   /// Detach or delete the old instance, create a new one from given arguments
   template <typename... Args>
   shared_object& replace(Args&&... args)
   {
      if (__builtin_expect(body->refc>1, 0)) {
         --body->refc;
         body=rep::construct(this, std::forward<Args>(args)...);
      } else {
         body->destroy();
         rep::init(this, body, std::is_nothrow_constructible<Object, Args...>(), std::forward<Args>(args)...);
      }
      return *this;
   }

   /// Enforce an own copy of the given object
   shared_object& assign_copy(const shared_object& s)
   {
      if (__builtin_expect(this != &s, 1)) {
         if (__builtin_expect(body->refc>1, 0)) {
            --body->refc;
            body=divorce_hook(rep::construct(this, const_cast<const Object&>(s.body->obj)), std::true_type());
         } else {
            body->obj=s.body->obj;
         }
      }
      return *this;
   }

   template <typename Operation>
   void apply(const Operation& op)
   {
      if (__builtin_expect(body->refc>1,0)) {
         --body->refc;
         body=divorce_hook(body->apply(this, op), std::true_type());
      } else {
         op(body->obj);
      }
   }

   void swap(shared_object& o)
   {
      static_cast<alias_handler&>(*this).swap(o);
      divorce_hook.swap(o.divorce_hook);
      std::swap(body,o.body);
   }

   friend void relocate(shared_object* from, shared_object* to)
   {
      to->body=from->body;
      relocate(static_cast<alias_handler*>(from), static_cast<alias_handler*>(to));
      relocate(&from->divorce_hook, &to->divorce_hook);
   }

   divorce_handler& get_divorce_handler() const
   {
      return const_cast<divorce_handler&>(divorce_hook);
   }

   static const shared_object* from_divorce_handler(const divorce_handler* h)
   {
      return reverse_cast(h, &shared_object::divorce_hook);
   }

   bool is_shared() const { return body->refc>1; }

   shared_object& enforce_unshared()
   {
      if (copy_on_write && __builtin_expect(body->refc>1,0))
         alias_handler::CoW(this,body->refc);
      return *this;
   }

   Object* operator-> ()
   {
      enforce_unshared();
      return &body->obj;
   }
   Object& operator* ()
   {
      enforce_unshared();
      return body->obj;
   }
   Object* get() const { return &body->obj; }

   const Object* operator-> () const { return &body->obj; }
   const Object& operator* () const { return body->obj; }
};


class shared_array_placement {
public:
   explicit shared_array_placement(void* addr=nullptr)
      : p(addr) {}

   void* get() const { return p; }
   void set(void* addr) { p=addr; }
private:
   void* p;
};


/** Automatic pointer to a shared data array

    It has the same semantics as @see shared_object, with the main difference that
    there are several data objects packed in the array instance that is being shared.

    @tmplparam Object type of the object in the array
*/
template <typename Object, typename... TParams>
class shared_array
   : public mtagged_list_extract<typename mlist_wrap<TParams...>::type, AliasHandlerTag, nop_shared_alias_handler>::type
   , protected shared_object_secrets {
   friend class nop_shared_alias_handler;
   friend class shared_alias_handler;
protected:
   typedef typename mlist_wrap<TParams...>::type params;
   typedef typename mtagged_list_extract<params, AliasHandlerTag, nop_shared_alias_handler>::type alias_handler;
   static const bool copy_on_write=tagged_list_extract_integral<params, CopyOnWriteTag>(true);
   typedef typename mtagged_list_extract<params, PrefixDataTag, nothing>::type prefix_type;
   typedef typename mtagged_list_extract<params, DivorceHandlerTag, nop_divorce_handler>::type divorce_handler;

   /// Attached objects plus housekeeping
   struct rep : shared_object_secrets::rep<prefix_type> {
      /// data objects
      Object obj[1];

      static size_t total_size(size_t n)
      {
         return sizeof(rep)-sizeof(Object)+n*sizeof(Object);
      }
   private:
      typedef shared_object_secrets::rep<prefix_type> super;
      typedef typename std::conditional<std::is_same<prefix_type, nothing>::value, mlist<nothing>, prefix_type>::type prefix_init_arg;

      static rep* allocate(size_t n, const nothing&)
      {
         allocator alloc;
         rep* r = (rep*)alloc.allocate(total_size(n));
         r->refc=1;
         r->size_and_prefix.first=n;
         return r;
      }

      static rep* allocate(size_t n, const prefix_init_arg& p)
      {
         rep* r=allocate(n, nothing());
         construct_at(&r->size_and_prefix.second, p);
         return r;
      }

      static rep* allocate_copy(size_t n, const rep* src)
      {
         return allocate(n, src->size_and_prefix.second);
      }

      static rep* allocate(const shared_array_placement& place, size_t n, const nothing&)
      {
         rep* r = reinterpret_cast<rep*>(place.get());
         r->refc = -std::numeric_limits<Int>::max();     // must always stay negative
         r->size_and_prefix.first = n;
         return r;
      }

      static rep* allocate(const shared_array_placement& place, size_t n, const prefix_init_arg& p)
      {
         rep* r = allocate(place, n, nothing());
         construct_at(&r->size_and_prefix.second, p);
         return r;
      }

      static void deallocate(rep* r)
      {
         if (!std::is_trivially_destructible<prefix_type>::value)
            destroy_at(&r->size_and_prefix.second);
         if (__builtin_expect(r->refc >= 0, 1)) {
            allocator alloc;
            alloc.deallocate(r, total_size(r->size_and_prefix.first));
         }
      }

      static void destroy(Object* end, Object* first)
      {
         if (!std::is_trivially_destructible<Object>::value) {
            while (end > first)
               destroy_at(--end);
         }
      }

      static void empty(shared_array* owner)
      {
         if (owner) owner->body=construct(nullptr, 0);
      }

      // dummy tag for constructors copying values or creating them from scratch
      struct copy { };

      /// initialize all array elements from a given value
      template <typename... Args>
      static void init_from_value(shared_array* owner, rep* r, Object*& dst, Object* end, std::true_type, Args&&... args)
      {
         for (; dst != end; ++dst)
            construct_at(dst, std::forward<Args>(args)...);
      }

      template <typename... Args>
      static void init_from_value(shared_array* owner, rep* r, Object*& dst, Object* end, std::false_type, Args&&... args)
      {
         try {
            init_from_value(owner, r, dst, end, std::true_type(), std::forward<Args>(args)...);
         }
         catch (...) {
            destroy(dst, r->obj);
            deallocate(r);
            empty(owner);
            throw;
         }
      }

      static void init(shared_array* owner, rep* r, Object* dst, Object* end, copy = copy())
      {
         init_from_value(owner, r, dst, end, std::is_nothrow_default_constructible<Object>());
      }

      template <typename Arg1, typename... Args>
      static
      std::enable_if_t<std::is_constructible<Object, Arg1, Args...>::value &&
                       !(sizeof...(Args)==0 && looks_like_iterator<Arg1>::value)>
      init(shared_array* owner, rep* r, Object* dst, Object* end, Arg1&& arg1, Args&&... args)
      {
         init_from_value(owner, r, dst, end, std::is_nothrow_constructible<Object, Arg1, Args...>(), std::forward<Arg1>(arg1), std::forward<Args>(args)...);
      }

      template <typename Iterator>
      static bool go_on(Object* dst, Object* end, const Iterator& src, std::true_type)
      {
#if POLYMAKE_DEBUG
         if (!src.at_end()) {
            if (end && dst >= end) throw std::runtime_error("input sequence is longer than the allocated storage");
            return true;
         }
         return false;
#else
         return !src.at_end();
#endif
      }

      template <typename Iterator>
      static bool go_on(Object* dst, Object* end, const Iterator& src, std::false_type)
      {
         return dst != end;
      }

      template <typename Iterator>
      static bool go_on(Object* dst, Object* end, const Iterator& src)
      {
         return go_on(dst, end, src, bool_constant<check_iterator_feature<Iterator, end_sensitive>::value>());
      }

      /// Initialize array elements with values from a sequence
      template <typename Iterator>
      static void init_from_sequence(shared_array* owner, rep* r, Object*& dst, Object* end, Iterator&& src,
                                     std::enable_if_t<std::is_nothrow_constructible<Object, decltype(*src)>::value, copy>)
      {
         for (; go_on(dst, end, src); ++src, ++dst)
            construct_at(dst, *src);
      }

      template <typename Iterator>
      static void init_from_sequence(shared_array* owner, rep* r, Object*& dst, Object* end, Iterator&& src,
                                     std::enable_if_t<!std::is_nothrow_constructible<Object, decltype(*src)>::value, copy>)
      {
         try {
            for (; go_on(dst, end, src); ++src, ++dst)
               construct_at(dst, *src);
         }
         catch (...) {
            destroy(dst, r->obj);
            deallocate(r);
            empty(owner);
            throw;
         }
      }

      template <typename Iterator>
      static
      void init_from_sequence(shared_array* owner, rep* r, Object*& dst, Object* end, Iterator&& src, polymake::operations::move)
      {
         auto&& src_moving=enforce_movable_values(std::forward<Iterator>(src));
         init_from_sequence(owner, r, dst, end, src_moving, copy());
      }

      template <typename Iterator, typename CopyOrMove>
      static
      std::enable_if_t<assess_iterator_value<Iterator, can_initialize, Object>::value>
      init_from_iterator(shared_array* owner, rep* r, Object*& dst, Object* end, Iterator&& src, CopyOrMove)
      {
         init_from_sequence(owner, r, dst, end, std::forward<Iterator>(src), CopyOrMove());
      }

      template <typename Iterator, typename CopyOrMove>
      static
      std::enable_if_t<looks_like_iterator<Iterator>::value && !assess_iterator_value<Iterator, can_initialize, Object>::value>
      init_from_iterator(shared_array* owner, rep* r, Object*& dst, Object* end, Iterator&& src, CopyOrMove)
      {
         for (; go_on(dst, end, src); ++src)
            init_from_iterator(owner, r, dst, nullptr, entire_range<dense>(*src), CopyOrMove());
      }

      template <typename Iterator>
      static
      std::enable_if_t<assess_iterator_value<Iterator, can_assign_to, Object>::value>
      assign_from_iterator(Object*& dst, Object* end, Iterator&& src)
      {
         for (; go_on(dst, end, src); ++src, ++dst)
            *dst = *src;
      }

      template <typename Iterator>
      static
      std::enable_if_t<looks_like_iterator<Iterator>::value && !assess_iterator_value<Iterator, can_assign_to, Object>::value>
      assign_from_iterator(Object*& dst, Object* end, Iterator&& src)
      {
         for (; go_on(dst, end, src); ++src)
            assign_from_iterator(dst, nullptr, entire_range<dense>(*src));
      }

      template <typename Iterator, typename Operation>
      static
      std::enable_if_t<assess_iterator_value<Iterator, isomorphic_types, Object>::value>
      init_from_iterator_with_binop(shared_array* owner, rep* r, Object*& dst, Object* end, const Object*& src_obj, Iterator&& src2, const Operation& op)
      {
         const Object* dst_start=dst;
         init_from_sequence(owner, r, dst, end, make_binary_transform_iterator(src_obj, std::forward<Iterator>(src2), op), copy());
         src_obj += dst-dst_start;
      }

      template <typename Iterator, typename Operation>
      static
      std::enable_if_t<looks_like_iterator<Iterator>::value &&
                       !assess_iterator_value<Iterator, isomorphic_types, Object>::value>
      init_from_iterator_with_binop(shared_array* owner, rep* r, Object*& dst, Object* end, const Object*& src_obj, Iterator&& src2, const Operation& op)
      {
         for (; go_on(dst, end, src2); ++src2)
            init_from_iterator_with_binop(owner, r, dst, nullptr, src_obj, entire_range<dense>(*src2), op);
      }

      template <typename Iterator, typename Operation>
      static
      std::enable_if_t<assess_iterator_value<Iterator, isomorphic_types, Object>::value &&
                       check_iterator_feature<pure_type_t<Iterator>, end_sensitive>::value>
      assign_with_binop(Object*& dst, Object* end, Iterator&& src2, const Operation& op)
      {
         perform_assign(dst, src2, op);
      }

      template <typename Iterator, typename Operation>
      static
      std::enable_if_t<assess_iterator_value<Iterator, isomorphic_types, Object>::value &&
                       !check_iterator_feature<pure_type_t<Iterator>, end_sensitive>::value>
      assign_with_binop(Object*& dst, Object* end, Iterator&& src2, const Operation& op)
      {
         perform_assign(make_iterator_range(dst, end), src2, op);
      }

      template <typename Iterator, typename Operation>
      static
      std::enable_if_t<looks_like_iterator<Iterator>::value &&
                       !assess_iterator_value<Iterator, isomorphic_types, Object>::value>
      assign_with_binop(Object*& dst, Object* end, Iterator&& src2, const Operation& op)
      {
         for (; go_on(dst, end, src2); ++src2)
            assign_with_binop(dst, nullptr, entire_range<dense>(*src2), op);
      }

      template <typename Iterator>
      static
      std::enable_if_t<assess_iterator_value<Iterator, can_initialize, Object>::value>
      init_from_iterator_one_step(shared_array* owner, rep* r, Object*& dst, Iterator&& src)
      {
#if POLYMAKE_DEBUG
         if (!go_on(dst, nullptr, src))
            throw std::runtime_error("shared_array weave error: input sequence ends prematurely");
#endif
         init_from_value(owner, r, dst, dst+1, std::is_nothrow_constructible<Object, decltype(*src)>(), *src);
         ++src;
      }

      template <typename Iterator>
      static
      std::enable_if_t<looks_like_iterator<Iterator>::value && !assess_iterator_value<Iterator, can_initialize, Object>::value>
      init_from_iterator_one_step(shared_array* owner, rep* r, Object*& dst, Iterator& src)
      {
#if POLYMAKE_DEBUG
         if (!go_on(dst, nullptr, src))
            throw std::runtime_error("shared_array weave error: input sequence ends prematurely");
#endif
         init_from_iterator(owner, r, dst, nullptr, entire_range<dense>(*src), copy());
         ++src;
      }

      template <typename... Iterator>
      static constexpr void check_input_iterators(mlist<Iterator...>)
      {
         static_assert(mlist_and<check_iterator_feature<Iterator, end_sensitive>...>::value,
                       "all iterators but the last one must be end-sensitive");
      }

      template <typename CopyOrMove, typename... Iterator>
      static
      std::enable_if_t<is_among<CopyOrMove, copy, polymake::operations::move>::value &&
                       mlist_and_nonempty<looks_like_iterator<Iterator>...>::value>
      init(shared_array* owner, rep* r, Object* dst, Object* end, CopyOrMove, Iterator&&... src)
      {
         check_input_iterators(typename mlist_slice<mlist<Iterator...>, 0, int(sizeof...(Iterator))-1>::type());
         (void)std::initializer_list<bool>{ (init_from_iterator(owner, r, dst, end, std::forward<Iterator>(src), CopyOrMove()), true)... };
#if POLYMAKE_DEBUG
         if (dst && dst != end) throw std::runtime_error("shared_array construction error: input sequence ends prematurely");
#endif
      }

      template <typename... Iterator>
      static
      std::enable_if_t<mlist_and_nonempty<looks_like_iterator<Iterator>...>::value>
      init(shared_array* owner, rep* r, Object* dst, Object* end, Iterator&&... src)
      {
         init(owner, r, dst, end, copy(), std::forward<Iterator>(src)...);
      }

      static rep* construct_empty(std::true_type) PmNoSanitize(object-size)
      {
         return static_cast<rep*>(&empty_rep);
      }
      static rep* construct_empty(std::false_type) PmNoSanitize(object-size)
      {
         static super empty;
         return static_cast<rep*>(&empty);
      }

   public:
      template <typename... Args>
      static rep* construct(shared_array* owner, size_t n, Args&&... args)
      {
         rep* r;
         if (__builtin_expect(n != 0, 1)) {
            r=allocate(n, prefix_type());
            init(owner, r, r->obj, r->obj+n, std::forward<Args>(args)...);
         } else {
            r=construct_empty(std::is_same<prefix_type, nothing>());
            ++r->refc;
         }
         return r;
      }

      template <typename... Args>
      static rep* construct(shared_array* owner, const prefix_type& p, size_t n, Args&&... args)
      {
         rep* r=allocate(n, p);
         init(owner, r, r->obj, r->obj+n, std::forward<Args>(args)...);
         return r;
      }

      template <typename... Args>
      static rep* construct_copy(shared_array* owner, const rep* src, size_t n, Args&&... args)
      {
         rep* r=allocate_copy(n, src);
         init(owner, r, r->obj, r->obj+n, std::forward<Args>(args)...);
         return r;
      }

      template <typename Iterator, typename Operation>
      static rep* construct_copy_with_binop(shared_array* owner, const rep* src, size_t n, Iterator&& src2, const Operation& op)
      {
         rep* r=allocate_copy(n, src);
         Object* dst=r->obj;
         const Object* src_obj=src->obj;
         init_from_iterator_with_binop(owner, r, dst, dst+n, src_obj, std::forward<Iterator>(src2), op);
         return r;
      }

      template <typename Iterator, typename Operation>
      void assign_with_binop(Int n, Iterator&& src2, const Operation& op)
      {
         Object* dst=obj;
         assign_with_binop(dst, dst+n, std::forward<Iterator>(src2), op);
      }

      template <typename... Args>
      static rep* construct(shared_array* owner, const shared_array_placement& place, size_t n, Args&&... args)
      {
         rep* r=allocate(place, n, prefix_type());
         init(owner, r, r->obj, r->obj+n, std::forward<Args>(args)...);
         return r;
      }

      template <typename... Args>
      static rep* construct(shared_array* owner, const shared_array_placement& place, const prefix_type& p, size_t n, Args&&... args)
      {
         rep* r=allocate(place, n, p);
         init(owner, r, r->obj, r->obj+n, std::forward<Args>(args)...);
         return r;
      }

      // relocate or copy
      template <typename... Args>
      static rep* resize(shared_array *owner, rep* old, size_t n, Args&&... args)
      {
         rep* r=allocate_copy(n, old);
         const size_t n_copy=std::min(n, old->size_and_prefix.first);
         Object* dst=r->obj;
         Object* middle=dst+n_copy;
         Object* end=dst+n;
         Object* src_copy=nullptr;
         Object* src_end=nullptr;

         if (old->refc > 0) {
            init_from_sequence(owner, r, dst, middle, ptr_wrapper<const Object, false>(old->obj), copy());
         } else {
            src_copy=old->obj;
            src_end=src_copy+old->size_and_prefix.first;
            for (; dst!=middle;  ++src_copy, ++dst)
               relocate(src_copy, dst);
         }
         init(owner, r, middle, end, std::forward<Args>(args)...);
         if (old->refc <= 0) {
            destroy(src_end, src_copy);
            deallocate(old);
         }

         return r;
      }

      template <typename... Args>
      static rep* weave(shared_array *owner, rep *old, size_t n, size_t slice, Args&&... args)
      {
         rep* r=allocate_copy(n, old);
         Object* dst=r->obj;
         Object* end=dst+n;

         if (old->refc > 0) {
            ptr_wrapper<const Object, false> src_copy(old->obj);
            while (dst != end) {
               init_from_sequence(owner, r, dst, dst+slice, src_copy, copy());
               (void)std::initializer_list<bool>{ (init_from_iterator_one_step(owner, r, dst, args), true)... };
            }
         } else {
            Object* src_copy=old->obj;
            while (dst != end) {
               for (Object* slice_end=dst+slice; dst!=slice_end; ++src_copy, ++dst)
                  relocate(src_copy, dst);
               (void)std::initializer_list<bool>{ (init_from_iterator_one_step(owner, r, dst, args), true)... };
            }
            deallocate(old);
         }
#if POLYMAKE_DEBUG
         (void)std::initializer_list<bool>{ go_on(dst, end, args)... };
#endif
         return r;
      }

      template <typename Value>
      static
      std::enable_if_t<isomorphic_types<Value, Object>::value && can_assign_to<Value, Object>::value>
      assign(Object* dst, Object* end, const Value& val)
      {
         for (; dst != end; ++dst)
            *dst = val;
      }

      template <typename... Iterator>
      static
      std::enable_if_t<mlist_and_nonempty<looks_like_iterator<Iterator>...>::value>
      assign(Object* dst, Object* end, Iterator&&... src)
      {
         check_input_iterators(typename mlist_slice<mlist<Iterator...>, 0, int(sizeof...(Iterator))-1>::type());
         (void)std::initializer_list<bool>{ (assign_from_iterator(dst, end, std::forward<Iterator>(src)), true)... };
#if POLYMAKE_DEBUG
         if (dst && dst != end) throw std::runtime_error("shared_array assign error: input sequence ends prematurely");
#endif
      }

      static void destruct(rep *r)
      {
         destroy(r->obj+r->size_and_prefix.first, r->obj);
         deallocate(r);
      }
   };

   rep *body;
   divorce_handler divorce_hook;

   void leave()
   {
      if (--body->refc<=0) rep::destruct(body);
   }

   void divorce()
   {
      --body->refc;
      const Object* src=body->obj;
      body=divorce_hook(rep::construct(this, body->size_and_prefix.second, body->size_and_prefix.first, src), std::true_type());
   }

   void divorce(alias_handler *al)
   {
      shared_array *o=static_cast<shared_array*>(al);
      o->body->refc--;
      o->body=body;
      body->refc++;
   }
public:
   /// Create an empty array.
   shared_array()
      : body(rep::construct(nullptr, 0)) {}

   explicit shared_array(const prefix_type& p)
      : body(rep::construct(nullptr, p, 0)) {}

   /// Create an array with @a n value-initialized elements
   explicit shared_array(size_t n)
      : body(rep::construct(nullptr, n)) {}

   shared_array(const prefix_type& p, size_t n)
      : body(rep::construct(nullptr, p, n)) {}

   /// Create an array in a preallocated storage
   explicit shared_array(const shared_array_placement& place, size_t n)
      : body(rep::construct(nullptr, place, n)) {}

   shared_array(const shared_array_placement& place, const prefix_type& p, size_t n)
      : body(rep::construct(nullptr, place, p, n)) {}

   /// Create an array with @n elements initialized from given data.
   /// args either can be a list of arguments suitable for construction of a single element,
   /// in which case all elements are constructed identically,
   /// or it can be an iterator over a sequence of input values or nested containers thereof,
   /// in which case the array elements are constructed by copying or conversion, whatever applies.
   /// Note that the input iterator is passed down by reference where it's advanced towards the end of the sequence.
   template <typename... Args>
   shared_array(size_t n, Args&&... args)
      : body(rep::construct(nullptr, n, std::forward<Args>(args)...)) {}

   template <typename... Args>
   shared_array(const prefix_type& p, size_t n, Args&&... args)
      : body(rep::construct(nullptr, p, n, std::forward<Args>(args)...)) {}

   template <typename... Args>
   shared_array(const shared_array_placement& place, size_t n, Args&&... args)
      : body(rep::construct(nullptr, place, n, std::forward<Args>(args)...)) {}

   template <typename... Args>
   shared_array(const shared_array_placement& place, const prefix_type& p, size_t n, Args&&... args)
      : body(rep::construct(nullptr, place, p, n, std::forward<Args>(args)...)) {}

   shared_array(const shared_array& s)
      : alias_handler(s) , body(s.body) { ++body->refc; }

   static size_t alloc_size(Int n) { return rep::total_size(n); }
   
   /// the size of the object
   size_t size() const { return body->size_and_prefix.first; }

   ~shared_array() { leave(); }

   /// Detach or destroy the old array, attach the new one.
   shared_array& operator= (const shared_array& s)
   {
      ++s.body->refc;
      leave();
      body=divorce_hook(s.body, std::true_type());
      return *this;
   }

   void swap(shared_array& o)
   {
      static_cast<alias_handler&>(*this).swap(o);
      divorce_hook.swap(o.divorce_hook);
      std::swap(body,o.body);
   }

   friend void relocate(shared_array* from, shared_array* to)
   {
      to->body=from->body;
      relocate(static_cast<alias_handler*>(from), static_cast<alias_handler*>(to));
      relocate(&from->divorce_hook, &to->divorce_hook);
   }

   void clear()
   {
      if (size()) {
         leave();
         body=rep::construct(nullptr, 0);
      }
   }

   void resize(size_t n)
   {
      if (n != size()) {
         --body->refc;
         body=rep::resize(this, body, n);
      }
   }

   void resize(const shared_array_placement& place, size_t n)
   {
      leave();
      body=rep::construct(this, place, n);
   }

   template <typename... Args>
   void append(size_t n, Args&&... args)
   {
      assert(alias_handler::is_owner());
      if (n) {
         --body->refc;
         body=rep::resize(this, body, n+size(), std::forward<Args>(args)...);
         if (__builtin_expect(alias_handler::need_postCoW(), 0))
            alias_handler::postCoW(this,true);
      }
   }

   template <typename... Args>
   void weave(size_t n, size_t slice, Args&&... args)
   {
      assert(alias_handler::is_owner());
      if (n) {
         --body->refc;
         body=rep::weave(this, body, n+size(), slice, std::forward<Args>(args)...);
         if (__builtin_expect(alias_handler::need_postCoW(), 0))
            alias_handler::postCoW(this,true);
      }
   }

   divorce_handler& get_divorce_handler() const { return const_cast<divorce_handler&>(divorce_hook); }
   static const shared_array* from_divorce_handler(const divorce_handler *h)
   {
      return reverse_cast(h, &shared_array::divorce_hook);
   }

   bool is_shared() const { return body->refc>1; }

   /* Assign the values from an input dense sequence.
      If the attached array instance is shared or its size is not equal to n,
      it is detached rsp. destroyed and a new one is created and initialized from the
      input sequence. Otherwise assigns the input data to the array elements.
   */
   template <typename... Args>
   void assign(size_t n, Args&&... args)
   {
      const bool isCoW = copy_on_write && body->refc>1 && alias_handler::preCoW(body->refc);
      if (isCoW || size() != n) {
         rep* newbody=rep::construct_copy(this, body, n, std::forward<Args>(args)...);
         leave();
         body=newbody;
         if (isCoW) alias_handler::postCoW(this);
      } else {
         rep::assign(body->obj, body->obj+n, std::forward<Args>(args)...);
      }
   }

   template <typename Operation>
   void assign_op(const Operation& op)
   {
      if (copy_on_write && __builtin_expect(body->refc>1,0) && alias_handler::preCoW(body->refc)) {
         rep* newbody=rep::construct_copy(this, body, size(), make_unary_transform_iterator(body->obj+0, op));
         leave();
         body=newbody;
         alias_handler::postCoW(this);
      } else {
         perform_assign(make_iterator_range(body->obj+0, body->obj+size()), op);
      }
   }

   template <typename Iterator, typename Operation>
   void assign_op(Iterator&& src2, const Operation& op)
   {
      if (copy_on_write && __builtin_expect(body->refc>1,0) && alias_handler::preCoW(body->refc)) {
         rep *newbody=rep::construct_copy_with_binop(this, body, size(), std::forward<Iterator>(src2), op);
         leave();
         body=newbody;
         alias_handler::postCoW(this);
      } else {
         body->assign_with_binop(size(), std::forward<Iterator>(src2), op);
      }
   }

   shared_array& enforce_unshared()
   {
      if (copy_on_write && __builtin_expect(body->refc>1,0))
         alias_handler::CoW(this,body->refc);
      return *this;
   }

   Object* operator* ()
   {
      enforce_unshared();
      return body->obj;
   }
   const Object* operator* () const { return body->obj; }

   prefix_type& get_prefix()
   {
      return body->size_and_prefix.second;
   }
   const prefix_type& get_prefix() const
   {
      return body->size_and_prefix.second;
   }
   static prefix_type& get_prefix(Object* obj, Int i = 0)
   {
      return reverse_cast(obj, i, &rep::obj)->size_and_prefix.second;
   }
   static const prefix_type& get_prefix(const Object* obj, Int i = 0)
   {
      return reverse_cast(obj, i, &rep::obj)->size_and_prefix.second;
   }
};

template <typename Master>
void shared_alias_handler::CoW(Master* me, Int refc)
{
   if (is_owner()) {
      me->divorce();
      al_set.forget();
   } else if (al_set.owner && refc > al_set.owner->n_aliases+1) {
      me->divorce();
      divorce_aliases(me);
   }
}

template <typename Master>
void shared_alias_handler::postCoW(Master *me, bool owner_checked)
{
   if (owner_checked || is_owner())
      al_set.forget();
   else
      divorce_aliases(me);
}

struct shared_clear {
   template <typename Object>
   void operator() (void *p, const Object&) const { new(p) Object; }
   template <typename Object>
   void operator() (Object& obj) const { obj.clear(); }
};

} // end namespace pm

namespace std {
   template <typename Object, typename... TParams> inline
   void swap(pm::shared_object<Object, TParams...>& s1, pm::shared_object<Object, TParams...>& s2) { s1.swap(s2); }

   template <typename Object, typename... TParams> inline
   void swap(pm::shared_array<Object, TParams...>& a1, pm::shared_array<Object, TParams...>& a2) { a1.swap(a2); }
} // end namespace std

#include "polymake/internal/alias.h"


// Local Variables:
// mode:C++
// c-basic-offset:3
// indent-tabs-mode:nil
// End: