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 = u1.move; 27 assert(cast(bool)u1 == false); // u1 is now empty 28 } 29 // memory freed for the Point structure created in the block 30 31 { 32 auto s1 = RefCounted!(Point, Mallocator)(4, 5); 33 assert(*s1 == Point(4, 5)); 34 assert(s1.x == 4); 35 { 36 auto s2 = s1; // can be copied 37 } // ref count goes to 1 here 38 39 } // ref count goes to 0 here, memory released 40 41 { 42 // the constructor can also take (size, init) or (size, range) values 43 auto arr = UniqueArray!(Point, Mallocator)(3); 44 45 const Point[3] expected1 = [Point(), Point(), Point()]; // because array literals aren't @nogc 46 assert(arr[] == expected1); 47 48 const Point[1] expected2 = [Point()]; 49 arr.length = 1; 50 assert(*arr == expected2); //deferencing is the same as slicing all of it 51 52 arr ~= UniqueArray!(Point, Mallocator)(1, Point(6, 7)); 53 const Point[2] expected3 = [Point(), Point(6, 7)]; 54 assert(arr[] == expected3); 55 56 } // memory for the array released here 57 } 58 59 // just use theAllocator 60 @system unittest { 61 import std.experimental.allocator: theAllocator, allocatorObject, dispose; 62 import test_allocator: TestAllocator; // test_allocator is a dub package 63 64 auto allocator = TestAllocator(); 65 auto oldAllocator = theAllocator; 66 scope(exit) { 67 allocator.dispose(theAllocator); 68 theAllocator = oldAllocator; 69 } 70 theAllocator = allocatorObject(allocator); 71 72 auto ptr = Unique!int(42); 73 assert(*ptr == 42); 74 75 } // TestAllocator will throw here if any memory leaks