It 0/46(0%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
330
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
3790
3800
3810
3820
3830
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
12090
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13650
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
14120
14130
14140
14150
14160
14170
14180
14190
14200
14210
14220
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
14360
14370
14380
14390
14400
14410
14420
14430
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16130
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
16440
16450
16460
16470
16480
16490
16500
16510
16520
16530
16540
16550
16560
16570
16580
16590
16600
16610
16620
16630
16640
16650
16660
16670
16680
16690
16700
16710
16720
16730
16740
16750
16760
16770
16780
16790
16800
16810
16820
16830
16840
16850
16860
16870
16880
16890
16900
16910
16920
16930
16940
16950
16960
16970
16980
16990
17000
17010
17020
17030
17040
17050
17060
17070
17080
17090
17100
17110
17120
17130
17140
17150
17160
17170
17180
17190
17200
17210
17220
17230
17240
17250
17260
17270
17280
17290
17300
17310
17320
17330
17340
17350
17360
17370
17380
17390
17400
17410
17420
17430
17440
17450
17460
17470
17480
17490
17500
17510
17520
17530
17540
17550
17560
17570
17580
17590
17600
17610
17620
17630
17640
17650
17660
17670
17680
17690
17700
17710
17720
17730
17740
17750
17760
17770
17780
17790
17800
17810
17820
17830
17840
17850
17860
17870
17880
17890
17900
17910
17920
17930
17940
17950
17960
17970
17980
17990
18000
18010
18020
18030
18040
18050
18060
18070
18080
18090
18100
18110
18120
18130
18140
18150
18160
18170
18180
18190
18200
18210
18220
18230
18240
18250
18260
18270
18280
18290
18300
18310
18320
18330
18340
18350
18360
18370
18380
18390
18400
18410
18420
18430
18440
18450
18460
18470
18480
18490
18500
18510
18520
18530
18540
18550
18560
18570
18580
18590
18600
18610
18620
18630
18640
18650
18660
18670
18680
18690
18700
18710
18720
18730
18740
18750
18760
18770
18780
18790
18800
18810
18820
18830
18840
18850
18860
18870
18880
18890
18900
18910
18920
18930
18940
18950
18960
18970
18980
18990
19000
19010
19020
19030
19040
19050
19060
19070
19080
19090
19100
19110
19120
19130
19140
19150
19160
19170
19180
19190
19200
19210
19220
19230
19240
19250
19260
19270
19280
19290
19300
19310
19320
19330
19340
19350
19360
19370
19380
19390
19400
19410
19420
19430
19440
19450
19460
19470
19480
19490
19500
19510
19520
19530
19540
19550
19560
19570
19580
19590
19600
19610
19620
19630
19640
19650
19660
19670
19680
19690
19700
19710
19720
19730
19740
19750
19760
19770
19780
19790
19800
19810
19820
19830
19840
19850
19860
19870
19880
19890
19900
19910
19920
19930
19940
19950
19960
19970
19980
19990
20000
20010
20020
20030
20040
20050
20060
20070
20080
20090
20100
20110
20120
20130
20140
20150
20160
20170
20180
20190
20200
20210
20220
20230
20240
20250
20260
20270
20280
20290
20300
20310
20320
20330
20340
20350
20360
20370
20380
20390
20400
20410
20420
20430
20440
20450
20460
20470
20480
20490
20500
20510
20520
20530
20540
20550
20560
20570
20580
20590
20600
20610
20620
20630
20640
20650
20660
20670
20680
20690
20700
20710
20720
20730
20740
20750
20760
20770
20780
20790
20800
20810
20820
20830
20840
20850
20860
20870
20880
20890
20900
20910
20920
20930
20940
20950
20960
20970
20980
20990
21000
21010
21020
21030
21040
21050
21060
21070
21080
21090
21100
21110
21120
21130
21140
21150
21160
21170
21180
21190
21200
21210
21220
21230
21240
21250
21260
21270
21280
21290
21300
21310
21320
21330
21340
21350
21360
21370
21380
21390
21400
21410
21420
21430
21440
21450
21460
21470
21480
21490
21500
21510
21520
21530
21540
21550
21560
21570
21580
21590
21600
21610
21620
21630
21640
21650
21660
21670
21680
21690
21700
21710
21720
21730
21740
21750
21760
21770
21780
21790
21800
21810
21820
21830
21840
21850
21860
21870
21880
21890
21900
21910
21920
21930
21940
21950
21960
21970
21980
21990
22000
22010
22020
22030
22040
22050
22060
22070
22080
22090
22100
22110
22120
22130
22140
22150
22160
22170
22180
22190
22200
22210
22220
22230
22240
22250
22260
22270
22280
22290
22300
22310
22320
22330
22340
22350
22360
22370
22380
22390
22400
22410
22420
22430
22440
22450
22460
22470
22480
22490
22500
22510
22520
22530
22540
22550
22560
22570
22580
22590
22600
22610
22620
22630
22640
22650
22660
22670
22680
22690
22700
22710
22720
22730
22740
22750
22760
22770
22780
22790
22800
22810
22820
22830
22840
22850
22860
22870
22880
22890
22900
22910
22920
22930
22940
22950
22960
22970
22980
22990
23000
23010
23020
23030
23040
23050
23060
23070
23080
23090
23100
23110
23120
23130
23140
23150
23160
23170
23180
23190
23200
23210
23220
23230
23240
23250
23260
23270
23280
23290
23300
23310
23320
23330
23340
23350
23360
23370
23380
23390
23400
23410
23420
23430
23440
23450
23460
23470
23480
23490
23500
23510
23520
23530
23540
23550
23560
23570
23580
23590
23600
23610
23620
23630
23640
23650
23660
23670
23680
23690
23700
23710
23720
23730
23740
23750
23760
23770
23780
23790
23800
23810
23820
23830
23840
23850
23860
23870
23880
23890
23900
23910
23920
23930
23940
23950
23960
23970
23980
23990
24000
24010
24020
24030
24040
24050
24060
24070
24080
24090
24100
24110
24120
24130
24140
24150
24160
24170
24180
24190
24200
24210
24220
24230
24240
24250
24260
24270
24280
24290
24300
24310
24320
24330
24340
24350
24360
24370
24380
24390
24400
24410
24420
24430
24440
24450
24460
24470
24480
24490
24500
24510
24520
24530
24540
24550
24560
24570
24580
24590
24600
24610
24620
24630
24640
24650
24660
24670
24680
24690
24700
24710
24720
24730
24740
24750
24760
24770
24780
24790
24800
24810
24820
24830
24840
24850
24860
24870
24880
24890
24900
24910
24920
24930
24940
24950
24960
24970
24980
24990
25000
25010
25020
25030
25040
25050
25060
25070
25080
25090
25100
25110
25120
25130
25140
25150
25160
25170
25180
25190
25200
25210
25220
25230
25240
25250
25260
25270
25280
25290
25300
25310
25320
25330
25340
25350
25360
25370
25380
25390
25400
25410
25420
25430
25440
25450
25460
// 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; public import stdx.allocator.common, stdx.allocator.typed; // Example in the synopsis above @system unittest { import std.algorithm.comparison : 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), 4072 * 1024, AllocatorList!( (n) => BitmappedBlock!(4096)( cast(ubyte[])(GCAllocator.instance.allocate( max(n, 4072 * 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 std.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 std.algorithm.comparison : max; import stdx.allocator.internal : emplace, emplaceRef; auto m = alloc.allocate(max(stateSize!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)); } private void fillWithMemcpy(T)(void[] array, auto ref T filler) nothrow { import core.stdc.string : memcpy; import std.algorithm.comparison : min; if (!array.length) return; memcpy(array.ptr, &filler, T.sizeof); // Fill the array from the initialized portion of itself exponentially. for (size_t offset = T.sizeof; offset < array.length; ) { size_t extent = min(offset, array.length - offset); memcpy(array.ptr + offset, array.ptr, extent); offset += extent; } } @system unittest { int[] a; fillWithMemcpy(a, 42); assert(a.length == 0); a = [ 1, 2, 3, 4, 5 ]; fillWithMemcpy(a, 42); assert(a == [ 42, 42, 42, 42, 42]); } private T[] uninitializedFillDefault(T)(T[] array) nothrow { T t = T.init; fillWithMemcpy(array, t); 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); }(); } @system unittest { void test1(A)(auto ref A alloc) { int[] a = alloc.makeArray!int(0); assert(a.length == 0 && a.ptr is null); a = alloc.makeArray!int(5); assert(a.length == 5); static immutable cheatsheet = [0, 0, 0, 0, 0]; assert(a == cheatsheet); } void test2(A)(auto ref A alloc) { static struct S { int x = 42; @disable this(this); } S[] arr = alloc.makeArray!S(5); assert(arr.length == 5); int[] arrInt = () @trusted { return (cast(int*) arr.ptr)[0 .. 5]; }(); static immutable res = [42, 42, 42, 42, 42]; assert(arrInt == res); } import stdx.allocator.gc_allocator : GCAllocator; import stdx.allocator.mallocator : Mallocator; (alloc) /*pure nothrow*/ @safe { test1(alloc); test2(alloc);} (GCAllocator.instance); (alloc) nothrow @safe @nogc { test1(alloc); test2(alloc);} (Mallocator.instance); test2(theAllocator); } @system unittest { import std.algorithm.comparison : equal; auto a = theAllocator.makeArray!(shared int)(5); static assert(is(typeof(a) == shared(int)[])); assert(a.length == 5); assert(a.equal([0, 0, 0, 0, 0])); auto b = theAllocator.makeArray!(const int)(5); static assert(is(typeof(b) == const(int)[])); assert(b.length == 5); assert(b.equal([0, 0, 0, 0, 0])); auto c = theAllocator.makeArray!(immutable int)(5); static assert(is(typeof(c) == immutable(int)[])); assert(c.length == 5); assert(c.equal([0, 0, 0, 0, 0])); } private enum hasPurePostblit(T) = !hasElaborateCopyConstructor!T || is(typeof(() pure { T.init.__xpostblit(); })); private enum hasPureDtor(T) = !hasElaborateDestructor!T || is(typeof(() pure { T.init.__xdtor(); })); // `true` when postblit and destructor of T cannot escape references to itself private enum canSafelyDeallocPostRewind(T) = hasPurePostblit!T && hasPureDtor!T; /// Ditto T[] makeArray(T, Allocator)(auto ref Allocator alloc, size_t length, auto ref T init) { if (!length) return null; auto m = alloc.allocate(T.sizeof * length); if (!m.ptr) return null; auto result = () @trusted { return cast(T[]) m; } (); import std.traits : hasElaborateCopyConstructor; static if (hasElaborateCopyConstructor!T) { scope(failure) { static if (canSafelyDeallocPostRewind!T) () @trusted { alloc.deallocate(m); } (); else alloc.deallocate(m); } size_t i = 0; static if (hasElaborateDestructor!T) { scope (failure) { foreach (j; 0 .. i) { destroy(result[j]); } } } import std.conv : emplace; for (; i < length; ++i) { emplace!T(&result[i], init); } } else { alias U = Unqual!T; () @trusted { fillWithMemcpy(cast(U[]) result, *(cast(U*) &init)); }(); } return result; } /// @system unittest { import std.algorithm.comparison : equal; static void test(T)() { T[] a = theAllocator.makeArray!T(2); assert(a.equal([0, 0])); a = theAllocator.makeArray!T(3, 42); assert(a.equal([42, 42, 42])); import std.range : only; a = theAllocator.makeArray!T(only(42, 43, 44)); assert(a.equal([42, 43, 44])); } test!int(); test!(shared int)(); test!(const int)(); test!(immutable int)(); } @system unittest { void test(A)(auto ref A alloc) { long[] a = alloc.makeArray!long(0, 42); assert(a.length == 0 && a.ptr is null); a = alloc.makeArray!long(5, 42); assert(a.length == 5); assert(a == [ 42, 42, 42, 42, 42 ]); } import stdx.allocator.gc_allocator : GCAllocator; (alloc) /*pure nothrow*/ @safe { test(alloc); } (GCAllocator.instance); test(theAllocator); } // test failure with a pure, failing struct @safe unittest { import std.exception : assertThrown, enforce; struct NoCopy { @disable this(); this(int b){} // can't be copied this(this) { enforce(1 == 2); } } import stdx.allocator.mallocator : Mallocator; assertThrown(makeArray!NoCopy(Mallocator.instance, 10, NoCopy(42))); } // test failure with an impure, failing struct @system unittest { import std.exception : assertThrown, enforce; static int i = 0; struct Singleton { @disable this(); this(int b){} // can't be copied this(this) { enforce(i++ == 0); } ~this() { i--; } } import stdx.allocator.mallocator : Mallocator; assertThrown(makeArray!Singleton(Mallocator.instance, 10, Singleton(42))); } /// Ditto Unqual!(ElementEncodingType!R)[] makeArray(Allocator, R)(auto ref Allocator alloc, R range) if (isInputRange!R && !isInfinite!R) { alias T = Unqual!(ElementEncodingType!R); return makeArray!(T, Allocator, R)(alloc, range); } /// Ditto T[] makeArray(T, Allocator, R)(auto ref Allocator alloc, R range) if (isInputRange!R && !isInfinite!R) { static if (isForwardRange!R || hasLength!R) { static if (hasLength!R || isNarrowString!R) immutable length = range.length; else immutable length = range.save.walkLength; if (!length) return null; auto m = alloc.allocate(T.sizeof * length); if (!m.ptr) return null; auto result = () @trusted { return cast(T[]) m; } (); size_t i = 0; scope (failure) { foreach (j; 0 .. i) { auto p = () @trusted { return cast(Unqual!T*) &result[j]; }(); destroy(p); } static if (canSafelyDeallocPostRewind!T) () @trusted { alloc.deallocate(m); } (); else alloc.deallocate(m); } import stdx.allocator.internal : emplaceRef; static if (isNarrowString!R || isRandomAccessRange!R) { foreach (j; 0 .. range.length) { emplaceRef!T(result[i++], range[j]); } } else { for (; !range.empty; range.popFront, ++i) { emplaceRef!T(result[i], range.front); } } return result; } else { // Estimated size size_t estimated = 8; auto m = alloc.allocate(T.sizeof * estimated); if (!m.ptr) return null; auto result = () @trusted { return cast(T[]) m; } (); size_t initialized = 0; void bailout() { foreach (i; 0 .. initialized + 1) { destroy(result[i]); } static if (canSafelyDeallocPostRewind!T) () @trusted { alloc.deallocate(m); } (); else alloc.deallocate(m); } scope (failure) bailout; for (; !range.empty; range.popFront, ++initialized) { if (initialized == estimated) { // Need to reallocate static if (hasPurePostblit!T) auto success = () @trusted { return alloc.reallocate(m, T.sizeof * (estimated *= 2)); } (); else auto success = alloc.reallocate(m, T.sizeof * (estimated *= 2)); if (!success) { bailout; return null; } result = () @trusted { return cast(T[]) m; } (); } import stdx.allocator.internal : emplaceRef; emplaceRef(result[initialized], range.front); } if (initialized < estimated) { // Try to shrink memory, no harm if not possible static if (hasPurePostblit!T) auto success = () @trusted { return alloc.reallocate(m, T.sizeof * initialized); } (); else auto success = alloc.reallocate(m, T.sizeof * initialized); if (success) result = () @trusted { return cast(T[]) m; } (); } return result[0 .. initialized]; } } @system unittest { void test(A)(auto ref A alloc) { long[] a = alloc.makeArray!long((int[]).init); assert(a.length == 0 && a.ptr is null); a = alloc.makeArray!long([5, 42]); assert(a.length == 2); assert(a == [ 5, 42]); // we can also infer the type auto b = alloc.makeArray([4.0, 2.0]); static assert(is(typeof(b) == double[])); assert(b == [4.0, 2.0]); } import stdx.allocator.gc_allocator : GCAllocator; (alloc) pure nothrow @safe { test(alloc); } (GCAllocator.instance); test(theAllocator); } // infer types for strings @system unittest { void test(A)(auto ref A alloc) { auto c = alloc.makeArray("fooπ😜"); static assert(is(typeof(c) == char[])); assert(c == "fooπ😜"); auto d = alloc.makeArray("fooπ😜"d); static assert(is(typeof(d) == dchar[])); assert(d == "fooπ😜"); auto w = alloc.makeArray("fooπ😜"w); static assert(is(typeof(w) == wchar[])); assert(w == "fooπ😜"); } import stdx.allocator.gc_allocator : GCAllocator; (alloc) pure nothrow @safe { test(alloc); } (GCAllocator.instance); test(theAllocator); } /*pure*/ nothrow @safe unittest { import std.algorithm.comparison : equal; import stdx.allocator.gc_allocator : GCAllocator; import std.internal.test.dummyrange; import std.range : iota; foreach (DummyType; AllDummyRanges) { (alloc) pure nothrow @safe { DummyType d; auto arr = alloc.makeArray(d); assert(arr.length == 10); assert(arr.equal(iota(1, 11))); } (GCAllocator.instance); } } // test failure with a pure, failing struct @safe unittest { import std.exception : assertThrown, enforce; struct NoCopy { int b; @disable this(); this(int b) { this.b = b; } // can't be copied this(this) { enforce(b < 3, "there can only be three elements"); } } import stdx.allocator.mallocator : Mallocator; auto arr = [NoCopy(1), NoCopy(2), NoCopy(3)]; assertThrown(makeArray!NoCopy(Mallocator.instance, arr)); struct NoCopyRange { static j = 0; bool empty() { return j > 5; } auto front() { return NoCopy(j); } void popFront() { j++; } } assertThrown(makeArray!NoCopy(Mallocator.instance, NoCopyRange())); } // test failure with an impure, failing struct @system unittest { import std.exception : assertThrown, enforce; static i = 0; static maxElements = 2; struct NoCopy { int val; @disable this(); this(int b){ this.val = i++; } // can't be copied this(this) { enforce(i++ < maxElements, "there can only be four elements"); } } import stdx.allocator.mallocator : Mallocator; auto arr = [NoCopy(1), NoCopy(2)]; assertThrown(makeArray!NoCopy(Mallocator.instance, arr)); // allow more copies and thus force reallocation i = 0; maxElements = 30; static j = 0; struct NoCopyRange { bool empty() { return j > 100; } auto front() { return NoCopy(1); } void popFront() { j++; } } assertThrown(makeArray!NoCopy(Mallocator.instance, NoCopyRange())); maxElements = 300; auto arr2 = makeArray!NoCopy(Mallocator.instance, NoCopyRange()); import std.algorithm.comparison : equal; import std.algorithm.iteration : map; import std.range : iota; assert(arr2.map!`a.val`.equal(iota(32, 204, 2))); } version(unittest) { private struct ForcedInputRange { int[]* array; pure nothrow @safe @nogc: bool empty() { return !array || (*array).empty; } ref int front() { return (*array)[0]; } void popFront() { *array = (*array)[1 .. $]; } } } @system unittest { import std.array : array; import std.range : iota; int[] arr = iota(10).array; void test(A)(auto ref A alloc) { ForcedInputRange r; long[] a = alloc.makeArray!long(r); assert(a.length == 0 && a.ptr is null); auto arr2 = arr; r.array = () @trusted { return &arr2; } (); a = alloc.makeArray!long(r); assert(a.length == 10); assert(a == iota(10).array); } import stdx.allocator.gc_allocator : GCAllocator; (alloc) pure nothrow @safe { test(alloc); } (GCAllocator.instance); test(theAllocator); } /** Grows $(D array) by appending $(D delta) more elements. The needed memory is allocated using $(D alloc). The extra elements added are 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 array = a reference to the array being grown delta = number of elements to add (upon success the new length of $(D array) is $(D array.length + delta)) init = element used for filling the array range = range used for initializing the array elements Returns: $(D true) upon success, $(D false) if memory could not be allocated. In the latter case $(D array) is left unaffected. 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. */ bool expandArray(T, Allocator)(auto ref Allocator alloc, ref T[] array, size_t delta) { if (!delta) return true; if (array is null) return false; immutable oldLength = array.length; void[] buf = array; if (!alloc.reallocate(buf, buf.length + T.sizeof * delta)) return false; array = cast(T[]) buf; array[oldLength .. $].uninitializedFillDefault; return true; } @system unittest { void test(A)(auto ref A alloc) { auto arr = alloc.makeArray!int([1, 2, 3]); assert(alloc.expandArray(arr, 3)); assert(arr == [1, 2, 3, 0, 0, 0]); } import stdx.allocator.gc_allocator : GCAllocator; test(GCAllocator.instance); test(theAllocator); } /// Ditto bool expandArray(T, Allocator)(auto ref Allocator alloc, ref T[] array, size_t delta, auto ref T init) { if (!delta) return true; if (array is null) return false; void[] buf = array; if (!alloc.reallocate(buf, buf.length + T.sizeof * delta)) return false; immutable oldLength = array.length; array = cast(T[]) buf; scope(failure) array[oldLength .. $].uninitializedFillDefault; import std.algorithm.mutation : uninitializedFill; array[oldLength .. $].uninitializedFill(init); return true; } @system unittest { void test(A)(auto ref A alloc) { auto arr = alloc.makeArray!int([1, 2, 3]); assert(alloc.expandArray(arr, 3, 1)); assert(arr == [1, 2, 3, 1, 1, 1]); } import stdx.allocator.gc_allocator : GCAllocator; test(GCAllocator.instance); test(theAllocator); } /// Ditto bool expandArray(T, Allocator, R)(auto ref Allocator alloc, ref T[] array, R range) if (isInputRange!R) { if (array is null) return false; static if (isForwardRange!R) { immutable delta = walkLength(range.save); if (!delta) return true; immutable oldLength = array.length; // Reallocate support memory void[] buf = array; if (!alloc.reallocate(buf, buf.length + T.sizeof * delta)) { return false; } array = cast(T[]) buf; // At this point we're committed to the new length. auto toFill = array[oldLength .. $]; scope (failure) { // Fill the remainder with default-constructed data toFill.uninitializedFillDefault; } for (; !range.empty; range.popFront, toFill.popFront) { assert(!toFill.empty); import std.conv : emplace; emplace!T(&toFill.front, range.front); } assert(toFill.empty); } else { scope(failure) { // The last element didn't make it, fill with default array[$ - 1 .. $].uninitializedFillDefault; } void[] buf = array; for (; !range.empty; range.popFront) { if (!alloc.reallocate(buf, buf.length + T.sizeof)) { array = cast(T[]) buf; return false; } import std.conv : emplace; emplace!T(buf[$ - T.sizeof .. $], range.front); } array = cast(T[]) buf; } return true; } /// @system unittest { auto arr = theAllocator.makeArray!int([1, 2, 3]); assert(theAllocator.expandArray(arr, 2)); assert(arr == [1, 2, 3, 0, 0]); import std.range : only; assert(theAllocator.expandArray(arr, only(4, 5))); assert(arr == [1, 2, 3, 0, 0, 4, 5]); } @system unittest { auto arr = theAllocator.makeArray!int([1, 2, 3]); ForcedInputRange r; int[] b = [ 1, 2, 3, 4 ]; auto temp = b; r.array = &temp; assert(theAllocator.expandArray(arr, r)); assert(arr == [1, 2, 3, 1, 2, 3, 4]); } /** Shrinks an array by $(D delta) elements. If $(D array.length < delta), does nothing and returns `false`. Otherwise, destroys the last $(D array.length - delta) elements in the array and then reallocates the array's buffer. If reallocation fails, fills the array with default-initialized data. Params: T = element type of the array being created alloc = the allocator used for getting memory array = a reference to the array being shrunk delta = number of elements to remove (upon success the new length of $(D array) is $(D array.length - delta)) Returns: `true` upon success, `false` if memory could not be reallocated. In the latter case, the slice $(D array[$ - delta .. $]) is left with default-initialized elements. 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. */ bool shrinkArray(T, Allocator)(auto ref Allocator alloc, ref T[] array, size_t delta) { if (delta > array.length) return false; // Destroy elements. If a destructor throws, fill the already destroyed // stuff with the default initializer. { size_t destroyed; scope(failure) { array[$ - delta .. $][0 .. destroyed].uninitializedFillDefault; } foreach (ref e; array[$ - delta .. $]) { e.destroy; ++destroyed; } } if (delta == array.length) { alloc.deallocate(array); array = null; return true; } void[] buf = array; if (!alloc.reallocate(buf, buf.length - T.sizeof * delta)) { // urgh, at least fill back with default array[$ - delta .. $].uninitializedFillDefault; return false; } array = cast(T[]) buf; return true; } /// @system unittest { int[] a = theAllocator.makeArray!int(100, 42); assert(a.length == 100); assert(theAllocator.shrinkArray(a, 98)); assert(a.length == 2); assert(a == [42, 42]); } @system unittest { void test(A)(auto ref A alloc) { long[] a = alloc.makeArray!long((int[]).init); assert(a.length == 0 && a.ptr is null); a = alloc.makeArray!long(100, 42); assert(alloc.shrinkArray(a, 98)); assert(a.length == 2); assert(a == [ 42, 42]); } import stdx.allocator.gc_allocator : GCAllocator; test(GCAllocator.instance); test(theAllocator); } /** Destroys and then deallocates (using $(D alloc)) the object pointed to by a pointer, the class object referred to by a $(D class) or $(D interface) reference, or an entire array. It is assumed the respective entities had been allocated with the same allocator. */ void dispose(A, T)(auto ref A alloc, auto ref T* p) { static if (hasElaborateDestructor!T) { destroy(*p); } alloc.deallocate((cast(void*) p)[0 .. T.sizeof]); static if (__traits(isRef, p)) p = null; } /// Ditto void dispose(A, T)(auto ref A alloc, auto ref T p) if (is(T == class) || is(T == interface)) { if (!p) return; static if (is(T == interface)) { version(Windows) { import core.sys.windows.unknwn : IUnknown; static assert(!is(T: IUnknown), "COM interfaces can't be destroyed in " ~ __PRETTY_FUNCTION__); } auto ob = cast(Object) p; } else alias ob = p; auto support = (cast(void*) ob)[0 .. typeid(ob).initializer.length]; destroy(p); alloc.deallocate(support); static if (__traits(isRef, p)) p = null; } /// Ditto void dispose(A, T)(auto ref A alloc, auto ref T[] array) { static if (hasElaborateDestructor!(typeof(array[0]))) { foreach (ref e; array) { destroy(e); } } alloc.deallocate(array); static if (__traits(isRef, array)) array = null; } @system unittest { static int x; static interface I { void method(); } static class A : I { int y; override void method() { x = 21; } ~this() { x = 42; } } static class B : A { } auto a = theAllocator.make!A; a.method(); assert(x == 21); theAllocator.dispose(a); assert(x == 42); B b = theAllocator.make!B; b.method(); assert(x == 21); theAllocator.dispose(b); assert(x == 42); I i = theAllocator.make!B; i.method(); assert(x == 21); theAllocator.dispose(i); assert(x == 42); int[] arr = theAllocator.makeArray!int(43); theAllocator.dispose(arr); } @system unittest //bugzilla 16512 { import stdx.allocator.mallocator : Mallocator; int* i = Mallocator.instance.make!int(0); Mallocator.instance.dispose(i); assert(i is null); Object o = Mallocator.instance.make!Object(); Mallocator.instance.dispose(o); assert(o is null); uint* u = Mallocator.instance.make!uint(0); Mallocator.instance.dispose((){return u;}()); assert(u !is null); uint[] ua = Mallocator.instance.makeArray!uint([0,1,2]); Mallocator.instance.dispose(ua); assert(ua is null); } @system unittest //bugzilla 15721 { import stdx.allocator.mallocator : Mallocator; interface Foo {} class Bar: Foo {} Bar bar; Foo foo; bar = Mallocator.instance.make!Bar; foo = cast(Foo) bar; Mallocator.instance.dispose(foo); } /** Allocates a multidimensional array of elements of type T. Params: N = number of dimensions T = element type of an element of the multidimensional arrat alloc = the allocator used for getting memory lengths = static array containing the size of each dimension Returns: An N-dimensional array with individual elements of type T. */ auto makeMultidimensionalArray(T, Allocator, size_t N)(auto ref Allocator alloc, size_t[N] lengths...) { static if (N == 1) { return makeArray!T(alloc, lengths[0]); } else { alias E = typeof(makeMultidimensionalArray!(T, Allocator, N - 1)(alloc, lengths[1 .. $])); auto ret = makeArray!E(alloc, lengths[0]); foreach (ref e; ret) e = makeMultidimensionalArray!(T, Allocator, N - 1)(alloc, lengths[1 .. $]); return ret; } } /// @system unittest { import stdx.allocator.mallocator : Mallocator; auto mArray = Mallocator.instance.makeMultidimensionalArray!int(2, 3, 6); // deallocate when exiting scope scope(exit) { Mallocator.instance.disposeMultidimensionalArray(mArray); } assert(mArray.length == 2); foreach (lvl2Array; mArray) { assert(lvl2Array.length == 3); foreach (lvl3Array; lvl2Array) assert(lvl3Array.length == 6); } } /** Destroys and then deallocates a multidimensional array, assuming it was created with makeMultidimensionalArray and the same allocator was used. Params: T = element type of an element of the multidimensional array alloc = the allocator used for getting memory array = the multidimensional array that is to be deallocated */ void disposeMultidimensionalArray(T, Allocator)(auto ref Allocator alloc, auto ref T[] array) { static if (isArray!T) { foreach (ref e; array) disposeMultidimensionalArray(alloc, e); } dispose(alloc, array); static if (__traits(isRef, array)) array = null; } /// @system unittest { struct TestAllocator { import stdx.allocator.common : platformAlignment; import stdx.allocator.mallocator : Mallocator; alias allocator = Mallocator.instance; private static struct ByteRange { void* ptr; size_t length; } private ByteRange[] _allocations; enum uint alignment = platformAlignment; void[] allocate(size_t numBytes) { auto ret = allocator.allocate(numBytes); _allocations ~= ByteRange(ret.ptr, ret.length); return ret; } bool deallocate(void[] bytes) { import std.algorithm.mutation : remove; import std.algorithm.searching : canFind; bool pred(ByteRange other) { return other.ptr == bytes.ptr && other.length == bytes.length; } assert(_allocations.canFind!pred); _allocations = _allocations.remove!pred; return allocator.deallocate(bytes); } ~this() { assert(!_allocations.length); } } TestAllocator allocator; auto mArray = allocator.makeMultidimensionalArray!int(2, 3, 5, 6, 7, 2); allocator.disposeMultidimensionalArray(mArray); } /** Returns a dynamically-typed $(D CAllocator) built around a given statically- typed allocator $(D a) of type $(D A). Passing a pointer to the allocator creates a dynamic allocator around the allocator pointed to by the pointer, without attempting to copy or move it. Passing the allocator by value or reference behaves as follows. $(UL $(LI If $(D A) has no state, the resulting object is allocated in static shared storage.) $(LI If $(D A) has state and is copyable, the result will store a copy of it within. The result itself is allocated in its own statically-typed allocator.) $(LI If $(D A) has state and is not copyable, the result will move the passed-in argument into the result. The result itself is allocated in its own statically-typed allocator.) ) */ CAllocatorImpl!A allocatorObject(A)(auto ref A a) if (!isPointer!A) { import std.conv : emplace; static if (stateSize!A == 0) { enum s = stateSize!(CAllocatorImpl!A).divideRoundUp(ulong.sizeof); static __gshared ulong[s] state; static __gshared CAllocatorImpl!A result; if (!result) { // Don't care about a few races result = emplace!(CAllocatorImpl!A)(state[]); } assert(result); return result; } else static if (is(typeof({ A b = a; A c = b; }))) // copyable { auto state = a.allocate(stateSize!(CAllocatorImpl!A)); import std.traits : hasMember; static if (hasMember!(A, "deallocate")) { scope(failure) a.deallocate(state); } return cast(CAllocatorImpl!A) emplace!(CAllocatorImpl!A)(state); } else // the allocator object is not copyable { // This is sensitive... create on the stack and then move enum s = stateSize!(CAllocatorImpl!A).divideRoundUp(ulong.sizeof); ulong[s] state; import std.algorithm.mutation : move; emplace!(CAllocatorImpl!A)(state[], move(a)); auto dynState = a.allocate(stateSize!(CAllocatorImpl!A)); // Bitblast the object in its final destination dynState[] = state[]; return cast(CAllocatorImpl!A) dynState.ptr; } } /// Ditto CAllocatorImpl!(A, Yes.indirect) allocatorObject(A)(A* pa) { assert(pa); import std.conv : emplace; auto state = pa.allocate(stateSize!(CAllocatorImpl!(A, Yes.indirect))); import std.traits : hasMember; static if (hasMember!(A, "deallocate")) { scope(failure) pa.deallocate(state); } return emplace!(CAllocatorImpl!(A, Yes.indirect)) (state, pa); } /// @system unittest { import stdx.allocator.mallocator : Mallocator; IAllocator a = allocatorObject(Mallocator.instance); auto b = a.allocate(100); assert(b.length == 100); assert(a.deallocate(b)); // The in-situ region must be used by pointer import stdx.allocator.building_blocks.region : InSituRegion; auto r = InSituRegion!1024(); a = allocatorObject(&r); b = a.allocate(200); assert(b.length == 200); // In-situ regions can deallocate the last allocation assert(a.deallocate(b)); } /** Returns a dynamically-typed $(D CSharedAllocator) built around a given statically- typed allocator $(D a) of type $(D A). Passing a pointer to the allocator creates a dynamic allocator around the allocator pointed to by the pointer, without attempting to copy or move it. Passing the allocator by value or reference behaves as follows. $(UL $(LI If $(D A) has no state, the resulting object is allocated in static shared storage.) $(LI If $(D A) has state and is copyable, the result will store a copy of it within. The result itself is allocated in its own statically-typed allocator.) $(LI If $(D A) has state and is not copyable, the result will move the passed-in argument into the result. The result itself is allocated in its own statically-typed allocator.) ) */ shared(CSharedAllocatorImpl!A) sharedAllocatorObject(A)(auto ref A a) if (!isPointer!A) { import std.conv : emplace; static if (stateSize!A == 0) { enum s = stateSize!(CSharedAllocatorImpl!A).divideRoundUp(ulong.sizeof); static __gshared ulong[s] state; static shared CSharedAllocatorImpl!A result; if (!result) { // Don't care about a few races result = cast(shared CSharedAllocatorImpl!A)(emplace!(CSharedAllocatorImpl!A)(state[])); } assert(result); return result; } else static if (is(typeof({ shared A b = a; shared A c = b; }))) // copyable { auto state = a.allocate(stateSize!(CSharedAllocatorImpl!A)); import std.traits : hasMember; static if (hasMember!(A, "deallocate")) { scope(failure) a.deallocate(state); } return emplace!(shared CSharedAllocatorImpl!A)(state); } else // the allocator object is not copyable { assert(0, "Not yet implemented"); } } /// Ditto shared(CSharedAllocatorImpl!(A, Yes.indirect)) sharedAllocatorObject(A)(A* pa) { assert(pa); import std.conv : emplace; auto state = pa.allocate(stateSize!(CSharedAllocatorImpl!(A, Yes.indirect))); import std.traits : hasMember; static if (hasMember!(A, "deallocate")) { scope(failure) pa.deallocate(state); } return emplace!(shared CSharedAllocatorImpl!(A, Yes.indirect))(state, pa); } /** Implementation of `IAllocator` using `Allocator`. This adapts a statically-built allocator type to `IAllocator` that is directly usable by non-templated code. Usually `CAllocatorImpl` is used indirectly by calling $(LREF theAllocator). */ class CAllocatorImpl(Allocator, Flag!"indirect" indirect = No.indirect) : IAllocator { import std.traits : hasMember; /** The implementation is available as a public member. */ static if (indirect) { private Allocator* pimpl; ref Allocator impl() { return *pimpl; } this(Allocator* pa) { pimpl = pa; } } else { static if (stateSize!Allocator) Allocator impl; else alias impl = Allocator.instance; } /// Returns `impl.alignment`. override @property uint alignment() { return impl.alignment; } /** Returns `impl.goodAllocSize(s)`. */ override size_t goodAllocSize(size_t s) { return impl.goodAllocSize(s); } /** Returns `impl.allocate(s)`. */ override void[] allocate(size_t s, TypeInfo ti = null) { return impl.allocate(s); } /** If `impl.alignedAllocate` exists, calls it and returns the result. Otherwise, always returns `null`. */ override void[] alignedAllocate(size_t s, uint a) { static if (hasMember!(Allocator, "alignedAllocate")) return impl.alignedAllocate(s, a); else return null; } /** If `Allocator` implements `owns`, forwards to it. Otherwise, returns `Ternary.unknown`. */ override Ternary owns(void[] b) { static if (hasMember!(Allocator, "owns")) return impl.owns(b); else return Ternary.unknown; } /// Returns $(D impl.expand(b, s)) if defined, `false` otherwise. override bool expand(ref void[] b, size_t s) { static if (hasMember!(Allocator, "expand")) return impl.expand(b, s); else return s == 0; } /// Returns $(D impl.reallocate(b, s)). override bool reallocate(ref void[] b, size_t s) { return impl.reallocate(b, s); } /// Forwards to `impl.alignedReallocate` if defined, `false` otherwise. bool alignedReallocate(ref void[] b, size_t s, uint a) { static if (!hasMember!(Allocator, "alignedAllocate")) { return false; } else { return impl.alignedReallocate(b, s, a); } } // Undocumented for now Ternary resolveInternalPointer(const void* p, ref void[] result) { static if (hasMember!(Allocator, "resolveInternalPointer")) { return impl.resolveInternalPointer(p, result); } else { return Ternary.unknown; } } /** If `impl.deallocate` is not defined, returns `false`. Otherwise it forwards the call. */ override bool deallocate(void[] b) { static if (hasMember!(Allocator, "deallocate")) { return impl.deallocate(b); } else { return false; } } /** Calls `impl.deallocateAll()` and returns the result if defined, otherwise returns `false`. */ override bool deallocateAll() { static if (hasMember!(Allocator, "deallocateAll")) { return impl.deallocateAll(); } else { return false; } } /** Forwards to `impl.empty()` if defined, otherwise returns `Ternary.unknown`. */ override Ternary empty() { static if (hasMember!(Allocator, "empty")) { return Ternary(impl.empty); } else { return Ternary.unknown; } } /** Returns `impl.allocateAll()` if present, `null` otherwise. */ override void[] allocateAll() { static if (hasMember!(Allocator, "allocateAll")) { return impl.allocateAll(); } else { return null; } } } /** Implementation of `ISharedAllocator` using `Allocator`. This adapts a statically-built, shareable across threads, allocator type to `ISharedAllocator` that is directly usable by non-templated code. Usually `CSharedAllocatorImpl` is used indirectly by calling $(LREF processAllocator). */ class CSharedAllocatorImpl(Allocator, Flag!"indirect" indirect = No.indirect) : ISharedAllocator { import std.traits : hasMember; /** The implementation is available as a public member. */ static if (indirect) { private shared Allocator* pimpl; ref Allocator impl() shared { return *pimpl; } this(Allocator* pa) shared { pimpl = pa; } } else { static if (stateSize!Allocator) shared Allocator impl; else alias impl = Allocator.instance; } /// Returns `impl.alignment`. override @property uint alignment() shared { return impl.alignment; } /** Returns `impl.goodAllocSize(s)`. */ override size_t goodAllocSize(size_t s) shared { return impl.goodAllocSize(s); } /** Returns `impl.allocate(s)`. */ override void[] allocate(size_t s, TypeInfo ti = null) shared { return impl.allocate(s); } /** If `impl.alignedAllocate` exists, calls it and returns the result. Otherwise, always returns `null`. */ override void[] alignedAllocate(size_t s, uint a) shared { static if (hasMember!(Allocator, "alignedAllocate")) return impl.alignedAllocate(s, a); else return null; } /** If `Allocator` implements `owns`, forwards to it. Otherwise, returns `Ternary.unknown`. */ override Ternary owns(void[] b) shared { static if (hasMember!(Allocator, "owns")) return impl.owns(b); else return Ternary.unknown; } /// Returns $(D impl.expand(b, s)) if defined, `false` otherwise. override bool expand(ref void[] b, size_t s) shared { static if (hasMember!(Allocator, "expand")) return impl.expand(b, s); else return s == 0; } /// Returns $(D impl.reallocate(b, s)). override bool reallocate(ref void[] b, size_t s) shared { return impl.reallocate(b, s); } /// Forwards to `impl.alignedReallocate` if defined, `false` otherwise. bool alignedReallocate(ref void[] b, size_t s, uint a) shared { static if (!hasMember!(Allocator, "alignedAllocate")) { return false; } else { return impl.alignedReallocate(b, s, a); } } // Undocumented for now Ternary resolveInternalPointer(const void* p, ref void[] result) shared { static if (hasMember!(Allocator, "resolveInternalPointer")) { return impl.resolveInternalPointer(p, result); } else { return Ternary.unknown; } } /** If `impl.deallocate` is not defined, returns `false`. Otherwise it forwards the call. */ override bool deallocate(void[] b) shared { static if (hasMember!(Allocator, "deallocate")) { return impl.deallocate(b); } else { return false; } } /** Calls `impl.deallocateAll()` and returns the result if defined, otherwise returns `false`. */ override bool deallocateAll() shared { static if (hasMember!(Allocator, "deallocateAll")) { return impl.deallocateAll(); } else { return false; } } /** Forwards to `impl.empty()` if defined, otherwise returns `Ternary.unknown`. */ override Ternary empty() shared { static if (hasMember!(Allocator, "empty")) { return Ternary(impl.empty); } else { return Ternary.unknown; } } /** Returns `impl.allocateAll()` if present, `null` otherwise. */ override void[] allocateAll() shared { static if (hasMember!(Allocator, "allocateAll")) { return impl.allocateAll(); } else { return null; } } } // Example in intro above @system unittest { // 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); // Check internal pointer void[] result; assert(theAllocator.resolveInternalPointer(null, result) == Ternary.no); Ternary r = theAllocator.resolveInternalPointer(arr.ptr, result); assert(result.ptr is arr.ptr && result.length >= arr.length); // 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); } __EOF__