1 module ddsp.util.memory;
2 
3 import dplug.core.nogc;
4 
5 import core.stdc.stdlib;
6 
7 
8 /// Template for allocating single instances of class or arrays of classes
9 /// for multiple channels.
10 template calloc(alias EffectName)
11 {
12     private import core.stdc.stdlib : malloc;
13 
14     /// Returns an initialized array of the given template parameter.
15     EffectName[] numChannels(Args...)(int n, Args args) nothrow @nogc
16     {
17         EffectName* e = cast(EffectName*)malloc(EffectName.sizeof * n);
18         foreach(chan; 0..n)
19             e[chan] = mallocNew!EffectName(args);
20         return e[0..n];
21     }
22 
23     /// Returns a new instance of EffectName
24     EffectName init(Args...)(Args args)
25     {
26         return mallocNew!EffectName(args);
27     }
28 }
29 
30 unittest
31 {
32     import ddsp.effect.compressor;
33 
34     Compressor!float[] compChannel = calloc!(Compressor!float).numChannels(2);
35     Compressor!float comp = calloc!(Compressor!float).init();
36 }
37 
38 /// Allocates a slice of memory of type T and with the specified length.
39 /// Since dynamic arrays cannot be 
40 T[] callocSlice(T)(size_t length) nothrow @nogc
41 {
42     T* mem = cast(T*)malloc(T.sizeof * length);
43     return mem[0..length];
44 }
45 
46 /// Free memory from slice created with callocSlice
47 void freeSlice(T)(T[] slice)
48 {
49     free(cast(T*)slice);
50 }
51 
52 unittest
53 {
54     import std.stdio;
55     char[] s = callocSlice!char(200);
56     s.freeSlice();
57 }