1 /** 2 Memory provider allocators to be used in templated composition 3 within other, designated allocators. 4 5 Copyright: © 2012-2013 RejectedSoftware e.K. 6 © 2014-2015 Etienne Cimon 7 License: Subject to the terms of the MIT license. 8 Authors: Sönke Ludwig, Etienne Cimon 9 */ 10 module memutils.memory; 11 12 import memutils.allocators; 13 import memutils.helpers; 14 import memutils.constants; 15 16 struct MallocAllocator { 17 nothrow: 18 @trusted: 19 void[] alloc(size_t sz, bool must_zeroise = true) 20 { 21 logInfo("Mallocating sz ", sz); 22 auto ptr = wasm_malloc(sz + Allocator.alignment); 23 if (ptr is null) return null; 24 25 auto mem = adjustPointerAlignment(ptr)[0 .. sz]; 26 memset(mem.ptr, 0, mem.length); 27 return mem; 28 } 29 30 void[] realloc(void[] mem, size_t new_size, bool must_zeroise = true) 31 { 32 size_t csz = min(mem.length, new_size); 33 auto p = extractUnalignedPointer(mem.ptr); 34 size_t oldmisalign = mem.ptr - p; 35 ubyte misalign; 36 auto pn = cast(ubyte*)wasm_realloc(p, mem.length, new_size+Allocator.alignment); 37 if (must_zeroise) memset(pn + mem.length, 0, new_size - mem.length); 38 if (p == pn) return pn[oldmisalign .. new_size+oldmisalign]; 39 40 auto pna = cast(ubyte*)adjustPointerAlignment(pn, &misalign); 41 scope(exit) 42 *(cast(ubyte*)pna-1) = misalign; 43 auto newmisalign = pna - pn; 44 45 // account for changed alignment after realloc (move memory back to aligned position) 46 if (oldmisalign != newmisalign) { 47 if (newmisalign > oldmisalign) { 48 foreach_reverse (i; 0 .. csz) 49 pn[i + newmisalign] = pn[i + oldmisalign]; 50 } else { 51 foreach (i; 0 .. csz) 52 pn[i + newmisalign] = pn[i + oldmisalign]; 53 } 54 } 55 56 auto mem2 = pna[0 .. new_size]; 57 return mem2; 58 } 59 60 void free(void[] mem, bool must_zeroise = true) 61 { 62 if (must_zeroise) memset(mem.ptr, 0, mem.length); 63 wasm_free(extractUnalignedPointer(mem.ptr), mem.length); 64 } 65 }