1 module automem;
2 
3 public import automem.unique;
4 public import automem.unique_array;
5 public import automem.ref_counted;
6 
7 
8 // can be @safe if the allocator has @safe functions
9 @system @nogc unittest {
10 
11     import std.experimental.allocator.mallocator: Mallocator;
12     import std.algorithm: move;
13 
14     struct Point {
15         int x;
16         int y;
17     }
18 
19     {
20         // must pass arguments to initialise the contained object
21         auto u1 = Unique!(Point, Mallocator)(2, 3);
22         assert(*u1 == Point(2, 3));
23         assert(u1.y == 3);
24 
25         // auto u2 = u1; // won't compile, can only move
26         typeof(u1) u2;
27         move(u1, u2);
28         assert(cast(bool)u1 == false); // u1 is now empty
29     }
30     // memory freed for the Point structure created in the block
31 
32     {
33         auto s1 = RefCounted!(Point, Mallocator)(4, 5);
34         assert(*s1 == Point(4, 5));
35         assert(s1.x == 4);
36         {
37             auto s2 = s1; // can be copied
38         } // ref count goes to 1 here
39 
40     } // ref count goes to 0 here, memory released
41 
42     {
43         // the constructor can also take (size, init) or (size, range) values
44         auto arr = UniqueArray!(Point, Mallocator)(3);
45 
46         const Point[3] expected1 = [Point(), Point(), Point()]; // because array literals aren't @nogc
47         assert(arr[] == expected1);
48 
49         const Point[1] expected2 = [Point()];
50         arr.length = 1;
51         assert(*arr == expected2); //deferencing is the same as slicing all of it
52 
53         arr ~= UniqueArray!(Point, Mallocator)(1, Point(6, 7));
54         const Point[2] expected3 = [Point(), Point(6, 7)];
55         assert(arr[] == expected3);
56 
57     } // memory for the array released here
58 }
59 
60 // just use theAllocator
61 @system unittest {
62     import std.experimental.allocator: theAllocator, allocatorObject, dispose;
63     import test_allocator: TestAllocator; // test_allocator is a dub package
64 
65     auto allocator = TestAllocator();
66     auto oldAllocator = theAllocator;
67     scope(exit) {
68         allocator.dispose(theAllocator);
69         theAllocator = oldAllocator;
70     }
71     theAllocator = allocatorObject(allocator);
72 
73     auto ptr = Unique!int(42);
74     assert(*ptr == 42);
75 
76 } // TestAllocator will throw here if any memory leaks