-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathpackage.d
3070 lines (2695 loc) · 84.2 KB
/
package.d
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
// Written in the D programming language.
/**
High-level interface for allocators. Implements bundled allocation/creation
and destruction/deallocation of data including `struct`s and `class`es,
and also array primitives related to allocation. This module is the entry point
for both making use of allocators and for their documentation.
$(SCRIPT inhibitQuickIndex = 1;)
$(BOOKTABLE,
$(TR $(TH Category) $(TH Functions))
$(TR $(TD Make) $(TD
$(LREF make)
$(LREF makeArray)
$(LREF makeMultidimensionalArray)
))
$(TR $(TD Dispose) $(TD
$(LREF dispose)
$(LREF disposeMultidimensionalArray)
))
$(TR $(TD Modify) $(TD
$(LREF expandArray)
$(LREF shrinkArray)
))
$(TR $(TD Global) $(TD
$(LREF processAllocator)
$(LREF theAllocator)
))
$(TR $(TD Class interface) $(TD
$(LREF allocatorObject)
$(LREF CAllocatorImpl)
$(LREF IAllocator)
))
)
Synopsis:
---
// Allocate an int, initialize it with 42
int* p = theAllocator.make!int(42);
assert(*p == 42);
// Destroy and deallocate it
theAllocator.dispose(p);
// Allocate using the global process allocator
p = processAllocator.make!int(100);
assert(*p == 100);
// Destroy and deallocate
processAllocator.dispose(p);
// Create an array of 50 doubles initialized to -1.0
double[] arr = theAllocator.makeArray!double(50, -1.0);
// Append two zeros to it
theAllocator.expandArray(arr, 2, 0.0);
// On second thought, take that back
theAllocator.shrinkArray(arr, 2);
// Destroy and deallocate
theAllocator.dispose(arr);
---
$(H2 Layered Structure)
D's allocators have a layered structure in both implementation and documentation:
$(OL
$(LI A high-level, dynamically-typed layer (described further down in this
module). It consists of an interface called $(LREF IAllocator), which concret;
allocators need to implement. The interface primitives themselves are oblivious
to the type of the objects being allocated; they only deal in `void[]`, by
necessity of the interface being dynamic (as opposed to type-parameterized).
Each thread has a current allocator it uses by default, which is a thread-local
variable $(LREF theAllocator) of type $(LREF IAllocator). The process has a
global _allocator called $(LREF processAllocator), also of type $(LREF
IAllocator). When a new thread is created, $(LREF processAllocator) is copied
into $(LREF theAllocator). An application can change the objects to which these
references point. By default, at application startup, $(LREF processAllocator)
refers to an object that uses D's garbage collected heap. This layer also
include high-level functions such as $(LREF make) and $(LREF dispose) that
comfortably allocate/create and respectively destroy/deallocate objects. This
layer is all needed for most casual uses of allocation primitives.)
$(LI A mid-level, statically-typed layer for assembling several allocators into
one. It uses properties of the type of the objects being created to route
allocation requests to possibly specialized allocators. This layer is relatively
thin and implemented and documented in the $(MREF
std,experimental,_allocator,typed) module. It allows an interested user to e.g.
use different allocators for arrays versus fixed-sized objects, to the end of
better overall performance.)
$(LI A low-level collection of highly generic $(I heap building blocks)$(MDASH)
Lego-like pieces that can be used to assemble application-specific allocators.
The real allocation smarts are occurring at this level. This layer is of
interest to advanced applications that want to configure their own allocators.
A good illustration of typical uses of these building blocks is module $(MREF
std,experimental,_allocator,showcase) which defines a collection of frequently-
used preassembled allocator objects. The implementation and documentation entry
point is $(MREF std,experimental,_allocator,building_blocks). By design, the
primitives of the static interface have the same signatures as the $(LREF
IAllocator) primitives but are for the most part optional and driven by static
introspection. The parameterized class $(LREF CAllocatorImpl) offers an
immediate and useful means to package a static low-level _allocator into an
implementation of $(LREF IAllocator).)
$(LI Core _allocator objects that interface with D's garbage collected heap
($(MREF std,experimental,_allocator,gc_allocator)), the C `malloc` family
($(MREF std,experimental,_allocator,mallocator)), and the OS ($(MREF
std,experimental,_allocator,mmap_allocator)). Most custom allocators would
ultimately obtain memory from one of these core allocators.)
)
$(H2 Idiomatic Use of $(D stdx._allocator))
As of this time, $(D stdx._allocator) is not integrated with D's
built-in operators that allocate memory, such as `new`, array literals, or
array concatenation operators. That means $(D stdx._allocator) is
opt-in$(MDASH)applications need to make explicit use of it.
For casual creation and disposal of dynamically-allocated objects, use $(LREF
make), $(LREF dispose), and the array-specific functions $(LREF makeArray),
$(LREF expandArray), and $(LREF shrinkArray). These use by default D's garbage
collected heap, but open the application to better configuration options. These
primitives work either with `theAllocator` but also with any allocator obtained
by combining heap building blocks. For example:
----
void fun(size_t n)
{
// Use the current allocator
int[] a1 = theAllocator.makeArray!int(n);
scope(exit) theAllocator.dispose(a1);
...
}
----
To experiment with alternative allocators, set $(LREF theAllocator) for the
current thread. For example, consider an application that allocates many 8-byte
objects. These are not well supported by the default _allocator, so a
$(MREF_ALTTEXT free list _allocator,
std,experimental,_allocator,building_blocks,free_list) would be recommended.
To install one in `main`, the application would use:
----
void main()
{
import stdx.allocator.building_blocks.free_list
: FreeList;
theAllocator = allocatorObject(FreeList!8());
...
}
----
$(H3 Saving the `IAllocator` Reference For Later Use)
As with any global resource, setting `theAllocator` and `processAllocator`
should not be done often and casually. In particular, allocating memory with
one allocator and deallocating with another causes undefined behavior.
Typically, these variables are set during application initialization phase and
last through the application.
To avoid this, long-lived objects that need to perform allocations,
reallocations, and deallocations relatively often may want to store a reference
to the _allocator object they use throughout their lifetime. Then, instead of
using `theAllocator` for internal allocation-related tasks, they'd use the
internally held reference. For example, consider a user-defined hash table:
----
struct HashTable
{
private IAllocator _allocator;
this(size_t buckets, IAllocator allocator = theAllocator) {
this._allocator = allocator;
...
}
// Getter and setter
IAllocator allocator() { return _allocator; }
void allocator(IAllocator a) { assert(empty); _allocator = a; }
}
----
Following initialization, the `HashTable` object would consistently use its
$(D _allocator) object for acquiring memory. Furthermore, setting
$(D HashTable._allocator) to point to a different _allocator should be legal but
only if the object is empty; otherwise, the object wouldn't be able to
deallocate its existing state.
$(H3 Using Allocators without `IAllocator`)
Allocators assembled from the heap building blocks don't need to go through
`IAllocator` to be usable. They have the same primitives as `IAllocator` and
they work with $(LREF make), $(LREF makeArray), $(LREF dispose) etc. So it
suffice to create allocator objects wherever fit and use them appropriately:
----
void fun(size_t n)
{
// Use a stack-installed allocator for up to 64KB
StackFront!65536 myAllocator;
int[] a2 = myAllocator.makeArray!int(n);
scope(exit) myAllocator.dispose(a2);
...
}
----
In this case, `myAllocator` does not obey the `IAllocator` interface, but
implements its primitives so it can work with `makeArray` by means of duck
typing.
One important thing to note about this setup is that statically-typed assembled
allocators are almost always faster than allocators that go through
`IAllocator`. An important rule of thumb is: "assemble allocator first, adapt
to `IAllocator` after". A good allocator implements intricate logic by means of
template assembly, and gets wrapped with `IAllocator` (usually by means of
$(LREF allocatorObject)) only once, at client level.
Copyright: Andrei Alexandrescu 2013-.
License: $(HTTP boost.org/LICENSE_1_0.txt, Boost License 1.0).
Authors: $(HTTP erdani.com, Andrei Alexandrescu)
Source: $(PHOBOSSRC std/experimental/_allocator)
*/
module stdx.allocator;
version (D_BetterC) {} else version = HasDRuntime;
version (HasDRuntime):
public import stdx.allocator.common,
stdx.allocator.typed;
// Example in the synopsis above
@system unittest
{
import mir.utility : min, max;
import stdx.allocator.building_blocks.allocator_list
: AllocatorList;
import stdx.allocator.building_blocks.bitmapped_block
: BitmappedBlock;
import stdx.allocator.building_blocks.bucketizer : Bucketizer;
import stdx.allocator.building_blocks.free_list : FreeList;
import stdx.allocator.building_blocks.segregator : Segregator;
import stdx.allocator.gc_allocator : GCAllocator;
alias FList = FreeList!(GCAllocator, 0, unbounded);
alias A = Segregator!(
8, FreeList!(GCAllocator, 0, 8),
128, Bucketizer!(FList, 1, 128, 16),
256, Bucketizer!(FList, 129, 256, 32),
512, Bucketizer!(FList, 257, 512, 64),
1024, Bucketizer!(FList, 513, 1024, 128),
2048, Bucketizer!(FList, 1025, 2048, 256),
3584, Bucketizer!(FList, 2049, 3584, 512),
4072u * 1024, AllocatorList!(
(n) => BitmappedBlock!(4096)(
cast(ubyte[])(GCAllocator.instance.allocate(
max(n, 4072u * 1024))))),
GCAllocator
);
A tuMalloc;
auto b = tuMalloc.allocate(500);
assert(b.length == 500);
auto c = tuMalloc.allocate(113);
assert(c.length == 113);
assert(tuMalloc.expand(c, 14));
tuMalloc.deallocate(b);
tuMalloc.deallocate(c);
}
import std.range.primitives;
import std.traits;
import stdx.allocator.internal : Ternary;
import std.typecons : Flag, Yes, No;
/**
Dynamic allocator interface. Code that defines allocators ultimately implements
this interface. This should be used wherever a uniform type is required for
encapsulating various allocator implementations.
Composition of allocators is not recommended at this level due to
inflexibility of dynamic interfaces and inefficiencies caused by cascaded
multiple calls. Instead, compose allocators using the static interface defined
in $(A std_experimental_allocator_building_blocks.html,
`stdx.allocator.building_blocks`), then adapt the composed
allocator to `IAllocator` (possibly by using $(LREF CAllocatorImpl) below).
Methods returning $(D Ternary) return $(D Ternary.yes) upon success,
$(D Ternary.no) upon failure, and $(D Ternary.unknown) if the primitive is not
implemented by the allocator instance.
*/
interface IAllocator
{
/**
Returns the alignment offered.
*/
@property uint alignment();
/**
Returns the good allocation size that guarantees zero internal
fragmentation.
*/
size_t goodAllocSize(size_t s);
/**
Allocates `n` bytes of memory.
*/
void[] allocate(size_t, TypeInfo ti = null);
/**
Allocates `n` bytes of memory with specified alignment `a`. Implementations
that do not support this primitive should always return `null`.
*/
void[] alignedAllocate(size_t n, uint a);
/**
Allocates and returns all memory available to this allocator.
Implementations that do not support this primitive should always return
`null`.
*/
void[] allocateAll();
/**
Expands a memory block in place and returns `true` if successful.
Implementations that don't support this primitive should always return
`false`.
*/
bool expand(ref void[], size_t);
/// Reallocates a memory block.
bool reallocate(ref void[], size_t);
/// Reallocates a memory block with specified alignment.
bool alignedReallocate(ref void[] b, size_t size, uint alignment);
/**
Returns $(D Ternary.yes) if the allocator owns $(D b), $(D Ternary.no) if
the allocator doesn't own $(D b), and $(D Ternary.unknown) if ownership
cannot be determined. Implementations that don't support this primitive
should always return `Ternary.unknown`.
*/
Ternary owns(void[] b);
/**
Resolves an internal pointer to the full block allocated. Implementations
that don't support this primitive should always return `Ternary.unknown`.
*/
Ternary resolveInternalPointer(const void* p, ref void[] result);
/**
Deallocates a memory block. Implementations that don't support this
primitive should always return `false`. A simple way to check that an
allocator supports deallocation is to call $(D deallocate(null)).
*/
bool deallocate(void[] b);
/**
Deallocates all memory. Implementations that don't support this primitive
should always return `false`.
*/
bool deallocateAll();
/**
Returns $(D Ternary.yes) if no memory is currently allocated from this
allocator, $(D Ternary.no) if some allocations are currently active, or
$(D Ternary.unknown) if not supported.
*/
Ternary empty();
}
/**
Dynamic shared allocator interface. Code that defines allocators shareable
across threads ultimately implements this interface. This should be used
wherever a uniform type is required for encapsulating various allocator
implementations.
Composition of allocators is not recommended at this level due to
inflexibility of dynamic interfaces and inefficiencies caused by cascaded
multiple calls. Instead, compose allocators using the static interface defined
in $(A std_experimental_allocator_building_blocks.html,
`stdx.allocator.building_blocks`), then adapt the composed
allocator to `ISharedAllocator` (possibly by using $(LREF CSharedAllocatorImpl) below).
Methods returning $(D Ternary) return $(D Ternary.yes) upon success,
$(D Ternary.no) upon failure, and $(D Ternary.unknown) if the primitive is not
implemented by the allocator instance.
*/
interface ISharedAllocator
{
/**
Returns the alignment offered.
*/
@property uint alignment() shared;
/**
Returns the good allocation size that guarantees zero internal
fragmentation.
*/
size_t goodAllocSize(size_t s) shared;
/**
Allocates `n` bytes of memory.
*/
void[] allocate(size_t, TypeInfo ti = null) shared;
/**
Allocates `n` bytes of memory with specified alignment `a`. Implementations
that do not support this primitive should always return `null`.
*/
void[] alignedAllocate(size_t n, uint a) shared;
/**
Allocates and returns all memory available to this allocator.
Implementations that do not support this primitive should always return
`null`.
*/
void[] allocateAll() shared;
/**
Expands a memory block in place and returns `true` if successful.
Implementations that don't support this primitive should always return
`false`.
*/
bool expand(ref void[], size_t) shared;
/// Reallocates a memory block.
bool reallocate(ref void[], size_t) shared;
/// Reallocates a memory block with specified alignment.
bool alignedReallocate(ref void[] b, size_t size, uint alignment) shared;
/**
Returns $(D Ternary.yes) if the allocator owns $(D b), $(D Ternary.no) if
the allocator doesn't own $(D b), and $(D Ternary.unknown) if ownership
cannot be determined. Implementations that don't support this primitive
should always return `Ternary.unknown`.
*/
Ternary owns(void[] b) shared;
/**
Resolves an internal pointer to the full block allocated. Implementations
that don't support this primitive should always return `Ternary.unknown`.
*/
Ternary resolveInternalPointer(const void* p, ref void[] result) shared;
/**
Deallocates a memory block. Implementations that don't support this
primitive should always return `false`. A simple way to check that an
allocator supports deallocation is to call $(D deallocate(null)).
*/
bool deallocate(void[] b) shared;
/**
Deallocates all memory. Implementations that don't support this primitive
should always return `false`.
*/
bool deallocateAll() shared;
/**
Returns $(D Ternary.yes) if no memory is currently allocated from this
allocator, $(D Ternary.no) if some allocations are currently active, or
$(D Ternary.unknown) if not supported.
*/
Ternary empty() shared;
}
private shared ISharedAllocator _processAllocator;
private IAllocator _threadAllocator;
private IAllocator setupThreadAllocator()() nothrow @nogc @safe
{
/*
Forwards the `_threadAllocator` calls to the `processAllocator`
*/
static class ThreadAllocator : IAllocator
{
override @property uint alignment()
{
return processAllocator.alignment();
}
override size_t goodAllocSize(size_t s)
{
return processAllocator.goodAllocSize(s);
}
override void[] allocate(size_t n, TypeInfo ti = null)
{
return processAllocator.allocate(n, ti);
}
override void[] alignedAllocate(size_t n, uint a)
{
return processAllocator.alignedAllocate(n, a);
}
override void[] allocateAll()
{
return processAllocator.allocateAll();
}
override bool expand(ref void[] b, size_t size)
{
return processAllocator.expand(b, size);
}
override bool reallocate(ref void[] b, size_t size)
{
return processAllocator.reallocate(b, size);
}
override bool alignedReallocate(ref void[] b, size_t size, uint alignment)
{
return processAllocator.alignedReallocate(b, size, alignment);
}
override Ternary owns(void[] b)
{
return processAllocator.owns(b);
}
override Ternary resolveInternalPointer(const void* p, ref void[] result)
{
return processAllocator.resolveInternalPointer(p, result);
}
override bool deallocate(void[] b)
{
return processAllocator.deallocate(b);
}
override bool deallocateAll()
{
return processAllocator.deallocateAll();
}
override Ternary empty()
{
return processAllocator.empty();
}
}
assert(!_threadAllocator);
import mir.conv : emplace;
static ulong[stateSize!(ThreadAllocator).divideRoundUp(ulong.sizeof)] _threadAllocatorState;
_threadAllocator = () @trusted { return emplace!(ThreadAllocator)(_threadAllocatorState[]); } ();
return _threadAllocator;
}
/**
Gets/sets the allocator for the current thread. This is the default allocator
that should be used for allocating thread-local memory. For allocating memory
to be shared across threads, use $(D processAllocator) (below). By default,
$(D theAllocator) ultimately fetches memory from $(D processAllocator), which
in turn uses the garbage collected heap.
*/
nothrow @safe @nogc @property IAllocator theAllocator()
{
auto p = _threadAllocator;
return p !is null ? p : setupThreadAllocator();
}
/// Ditto
nothrow @safe @nogc @property void theAllocator(IAllocator a)
{
assert(a);
_threadAllocator = a;
}
///
@system unittest
{
// Install a new allocator that is faster for 128-byte allocations.
import stdx.allocator.building_blocks.free_list : FreeList;
import stdx.allocator.gc_allocator : GCAllocator;
auto oldAllocator = theAllocator;
scope(exit) theAllocator = oldAllocator;
theAllocator = allocatorObject(FreeList!(GCAllocator, 128)());
// Use the now changed allocator to allocate an array
const ubyte[] arr = theAllocator.makeArray!ubyte(128);
assert(arr.ptr);
//...
}
/**
Gets/sets the allocator for the current process. This allocator must be used
for allocating memory shared across threads. Objects created using this
allocator can be cast to $(D shared).
*/
@property shared(ISharedAllocator) processAllocator()
{
import stdx.allocator.gc_allocator : GCAllocator;
import std.concurrency : initOnce;
return initOnce!_processAllocator(
sharedAllocatorObject(GCAllocator.instance));
}
/// Ditto
@property void processAllocator(shared ISharedAllocator a)
{
assert(a);
_processAllocator = a;
}
@system unittest
{
import core.exception : AssertError;
import std.exception : assertThrown;
import stdx.allocator.building_blocks.free_list : SharedFreeList;
import stdx.allocator.mallocator : Mallocator;
assert(processAllocator);
assert(theAllocator);
testAllocatorObject(processAllocator);
testAllocatorObject(theAllocator);
shared SharedFreeList!(Mallocator, chooseAtRuntime, chooseAtRuntime) sharedFL;
shared ISharedAllocator sharedFLObj = sharedAllocatorObject(sharedFL);
assert(sharedFLObj);
testAllocatorObject(sharedFLObj);
// Test processAllocator setter
shared ISharedAllocator oldProcessAllocator = processAllocator;
processAllocator = sharedFLObj;
assert(processAllocator is sharedFLObj);
testAllocatorObject(processAllocator);
testAllocatorObject(theAllocator);
assertThrown!AssertError(processAllocator = null);
// Restore initial processAllocator state
processAllocator = oldProcessAllocator;
assert(processAllocator is oldProcessAllocator);
shared ISharedAllocator indirectShFLObj = sharedAllocatorObject(&sharedFL);
testAllocatorObject(indirectShFLObj);
IAllocator indirectMallocator = allocatorObject(Mallocator.instance);
testAllocatorObject(indirectMallocator);
}
/**
Dynamically allocates (using $(D alloc)) and then creates in the memory
allocated an object of type $(D T), using $(D args) (if any) for its
initialization. Initialization occurs in the memory allocated and is otherwise
semantically the same as $(D T(args)).
(Note that using $(D alloc.make!(T[])) creates a pointer to an (empty) array
of $(D T)s, not an array. To use an allocator to allocate and initialize an
array, use $(D alloc.makeArray!T) described below.)
Params:
T = Type of the object being created.
alloc = The allocator used for getting the needed memory. It may be an object
implementing the static interface for allocators, or an $(D IAllocator)
reference.
args = Optional arguments used for initializing the created object. If not
present, the object is default constructed.
Returns: If $(D T) is a class type, returns a reference to the created $(D T)
object. Otherwise, returns a $(D T*) pointing to the created object. In all
cases, returns $(D null) if allocation failed.
Throws: If $(D T)'s constructor throws, deallocates the allocated memory and
propagates the exception.
*/
auto make(T, Allocator, A...)(auto ref Allocator alloc, auto ref A args)
{
import mir.utility : max;
import mir.conv : emplace, emplaceRef;
auto m = alloc.allocate(max(stateSize!T, size_t(1)));
if (!m.ptr) return null;
// make can only be @safe if emplace or emplaceRef is `pure`
auto construct()
{
static if (is(T == class))
{
return emplace!T(m, args);
}
else
{
// Assume cast is safe as allocation succeeded for `stateSize!T`
auto p = () @trusted { return cast(T*) m.ptr; }();
emplaceRef(*p, args);
return p;
}
}
scope(failure)
{
static if (is(typeof(() pure { return construct(); })))
{
// Assume deallocation is safe because:
// 1) in case of failure, `m` is the only reference to this memory
// 2) `m` is known to originate from `alloc`
() @trusted { alloc.deallocate(m); }();
}
else
{
alloc.deallocate(m);
}
}
return construct();
}
///
@system unittest
{
// Dynamically allocate one integer
const int* p1 = theAllocator.make!int;
// It's implicitly initialized with its .init value
assert(*p1 == 0);
// Dynamically allocate one double, initialize to 42.5
const double* p2 = theAllocator.make!double(42.5);
assert(*p2 == 42.5);
// Dynamically allocate a struct
static struct Point
{
int x, y, z;
}
// Use the generated constructor taking field values in order
const Point* p = theAllocator.make!Point(1, 2);
assert(p.x == 1 && p.y == 2 && p.z == 0);
// Dynamically allocate a class object
static class Customer
{
uint id = uint.max;
this() {}
this(uint id) { this.id = id; }
// ...
}
Customer cust = theAllocator.make!Customer;
assert(cust.id == uint.max); // default initialized
cust = theAllocator.make!Customer(42);
assert(cust.id == 42);
// explicit passing of outer pointer
static class Outer
{
int x = 3;
class Inner
{
auto getX() { return x; }
}
}
auto outer = theAllocator.make!Outer();
auto inner = theAllocator.make!(Outer.Inner)(outer);
assert(outer.x == inner.getX);
}
@system unittest // bugzilla 15639 & 15772
{
abstract class Foo {}
class Bar: Foo {}
static assert(!is(typeof(theAllocator.make!Foo)));
static assert( is(typeof(theAllocator.make!Bar)));
}
@system unittest
{
void test(Allocator)(auto ref Allocator alloc)
{
const int* a = alloc.make!int(10);
assert(*a == 10);
struct A
{
int x;
string y;
double z;
}
A* b = alloc.make!A(42);
assert(b.x == 42);
assert(b.y is null);
import std.math : isNaN;
assert(b.z.isNaN);
b = alloc.make!A(43, "44", 45);
assert(b.x == 43);
assert(b.y == "44");
assert(b.z == 45);
static class B
{
int x;
string y;
double z;
this(int _x, string _y = null, double _z = double.init)
{
x = _x;
y = _y;
z = _z;
}
}
B c = alloc.make!B(42);
assert(c.x == 42);
assert(c.y is null);
assert(c.z.isNaN);
c = alloc.make!B(43, "44", 45);
assert(c.x == 43);
assert(c.y == "44");
assert(c.z == 45);
const parray = alloc.make!(int[]);
assert((*parray).empty);
}
import stdx.allocator.gc_allocator : GCAllocator;
test(GCAllocator.instance);
test(theAllocator);
}
// Attribute propagation
nothrow @safe @nogc unittest
{
import stdx.allocator.mallocator : Mallocator;
alias alloc = Mallocator.instance;
void test(T, Args...)(auto ref Args args)
{
auto k = alloc.make!T(args);
() @trusted { alloc.dispose(k); }();
}
test!int;
test!(int*);
test!int(0);
test!(int*)(null);
}
// should be pure with the GCAllocator
/*pure nothrow*/ @safe unittest
{
import stdx.allocator.gc_allocator : GCAllocator;
alias alloc = GCAllocator.instance;
void test(T, Args...)(auto ref Args args)
{
auto k = alloc.make!T(args);
(a) @trusted { a.dispose(k); }(alloc);
}
test!int();
test!(int*);
test!int(0);
test!(int*)(null);
}
// Verify that making an object by calling an impure constructor is not @safe
nothrow @safe @nogc unittest
{
import stdx.allocator.mallocator : Mallocator;
static struct Pure { this(int) pure nothrow @nogc @safe {} }
cast(void) Mallocator.instance.make!Pure(0);
static int g = 0;
static struct Impure { this(int) nothrow @nogc @safe {
g++;
} }
static assert(!__traits(compiles, cast(void) Mallocator.instance.make!Impure(0)));
}
// test failure with a pure, failing struct
@safe unittest
{
import std.exception : assertThrown, enforce;
// this struct can't be initialized
struct InvalidStruct
{
this(int b)
{
enforce(1 == 2);
}
}
import stdx.allocator.mallocator : Mallocator;
assertThrown(make!InvalidStruct(Mallocator.instance, 42));
}
// test failure with an impure, failing struct
@system unittest
{
import std.exception : assertThrown, enforce;
static int g;
struct InvalidImpureStruct
{
this(int b)
{
g++;
enforce(1 == 2);
}
}
import stdx.allocator.mallocator : Mallocator;
assertThrown(make!InvalidImpureStruct(Mallocator.instance, 42));
}
/++
+/
T[] uninitializedFillDefault(T)(T[] array) nothrow @nogc
{
static if (__VERSION__ < 2083)
{
static if (is(Unqual!T == char) || is(Unqual!T == wchar))
{
import core.stdc.string : memset;
if (array !is null)
memset(array.ptr, 0xff, T.sizeof * array.length);
return array;
}
else
{
pragma(inline, false);
import mir.conv : emplaceInitializer;
foreach(ref e; array)
emplaceInitializer(e);
return array;
}
}
else
{
static if (__traits(isZeroInit, T))
{
import core.stdc.string : memset;
if (array !is null)
memset(array.ptr, 0, T.sizeof * array.length);
return array;
}
else static if (is(Unqual!T == char) || is(Unqual!T == wchar))
{
import core.stdc.string : memset;
if (array !is null)
memset(array.ptr, 0xff, T.sizeof * array.length);
return array;
}
else
{
pragma(inline, false);
import mir.conv : emplaceInitializer;
foreach(ref e; array)
emplaceInitializer(e);
return array;
}
}
}
///
pure nothrow @nogc
@system unittest
{
static struct S { int x = 42; @disable this(this); }
int[5] expected = [42, 42, 42, 42, 42];
S[5] arr = void;
uninitializedFillDefault(arr);
assert((cast(int*) arr.ptr)[0 .. arr.length] == expected);
}
@system unittest
{
int[] a = [1, 2, 4];
uninitializedFillDefault(a);
assert(a == [0, 0, 0]);
}
/**
Create an array of $(D T) with $(D length) elements using $(D alloc). The array is either default-initialized, filled with copies of $(D init), or initialized with values fetched from `range`.
Params:
T = element type of the array being created
alloc = the allocator used for getting memory
length = length of the newly created array
init = element used for filling the array
range = range used for initializing the array elements
Returns:
The newly-created array, or $(D null) if either $(D length) was $(D 0) or
allocation failed.
Throws:
The first two overloads throw only if `alloc`'s primitives do. The
overloads that involve copy initialization deallocate memory and propagate the
exception if the copy operation throws.
*/
T[] makeArray(T, Allocator)(auto ref Allocator alloc, size_t length)
{
if (!length) return null;
auto m = alloc.allocate(T.sizeof * length);
if (!m.ptr) return null;
alias U = Unqual!T;
return () @trusted { return cast(T[]) uninitializedFillDefault(cast(U[]) m); }();
}