xref: /netbsd-src/external/gpl3/gcc.old/dist/libphobos/libdruntime/rt/util/container/common.d (revision 627f7eb200a4419d89b531d55fccd2ee3ffdcde0)
1 /**
2  * Common code for writing containers.
3  *
4  * Copyright: Copyright Martin Nowak 2013.
5  * License:   $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0).
6  * Authors:   Martin Nowak
7  */
8 module rt.util.container.common;
9 
10 import core.stdc.stdlib : malloc, realloc;
11 public import core.stdc.stdlib : free;
12 import core.internal.traits : dtorIsNothrow;
13 nothrow:
14 
xrealloc(void * ptr,size_t sz)15 void* xrealloc(void* ptr, size_t sz) nothrow @nogc
16 {
17     import core.exception;
18 
19     if (!sz) { .free(ptr); return null; }
20     if (auto nptr = .realloc(ptr, sz)) return nptr;
21     .free(ptr); onOutOfMemoryErrorNoGC();
22     assert(0);
23 }
24 
xmalloc(size_t sz)25 void* xmalloc(size_t sz) nothrow @nogc
26 {
27     import core.exception;
28     if (auto nptr = .malloc(sz))
29         return nptr;
30     onOutOfMemoryErrorNoGC();
31     assert(0);
32 }
33 
34 void destroy(T)(ref T t) if (is(T == struct) && dtorIsNothrow!T)
35 {
36     scope (failure) assert(0); // nothrow hack
37     object.destroy(t);
38 }
39 
40 void destroy(T)(ref T t) if (!is(T == struct))
41 {
42     t = T.init;
43 }
44 
45 void initialize(T)(ref T t) if (is(T == struct))
46 {
47     import core.stdc.string;
48     if (auto p = typeid(T).initializer().ptr)
49         memcpy(&t, p, T.sizeof);
50     else
51         memset(&t, 0, T.sizeof);
52 }
53 
54 void initialize(T)(ref T t) if (!is(T == struct))
55 {
56     t = T.init;
57 }
58 
version(unittest)59 version (unittest) struct RC()
60 {
61 nothrow:
62     this(size_t* cnt) { ++*(_cnt = cnt); }
63     ~this() { if (_cnt) --*_cnt; }
64     this(this) { if (_cnt) ++*_cnt; }
65     size_t* _cnt;
66 }
67