1 module tagion.betterC.mobile.Recycle;
2 
3 import tagion.betterC.utils.Memory;
4 import tagion.betterC.utils.StringHelper;
5 
6 struct Recycle(T) {
7     private {
8         T[] _active;
9         uint[] _reuse;
10     }
11 
12     /// Create an object of T and return it's index in '_active'
13     const(uint) create(T x) {
14         import core.stdc.stdio;
15 
16         if (_reuse.length > 0) {
17             const reuse_id = _reuse.pop_back();
18             _active[reuse_id] = x;
19             return reuse_id;
20         }
21         _active.append(x);
22         return cast(uint) _active.length - 1;
23     }
24 
25     bool put(T x, const uint id) {
26         bool result = false;
27 
28         if (exists(id)) {
29             _active[id] = x;
30             result = true;
31         }
32         return result;
33     }
34 
35     /// Erase by index
36     void erase(const uint id)
37     in {
38         assert(id >= 0);
39         assert(id < _active.length);
40     }
41     do {
42         import std.algorithm.searching : count;
43 
44         _active[id] = T.init;
45         // Check for avoiding the multiple append the same id
46         if (_reuse.count(id) is 0) {
47             _reuse.append(id);
48         }
49     }
50 
51     /// overloading function call operator
52     T opCall(const uint id)
53     in {
54         assert(id < _active.length);
55         assert(_active[id]!is T.init);
56     }
57     do {
58         return _active[id];
59     }
60 
61     /// Checking for existence by id
62     bool exists(const uint id) const nothrow {
63         if (id < _active.length) {
64             return _active[id]!is T.init;
65         }
66         return false;
67     }
68 }
69 
70 // unittest {
71 //     import tagion.betterC.hibon.HiBON;
72 //     import tagion.betterC.hibon.Document;
73 
74 //     import core.stdc.stdio;
75 
76 //     auto hibon = HiBON();
77 //     Document doc = Document(hibon.serialize);
78 //     Recycle!Document recycler;
79 //     auto doc_id = recycler.create(doc);
80 //     // printf("%u\n", res);
81 
82 //     assert(recycler.exists(doc_id));
83 //     assert(doc == recycler(doc_id));
84 
85 //     Document doc1 = Document(hibon.serialize);
86 //     auto doc1_id = recycler.create(doc1);
87 
88 //     assert(doc1_id != doc_id);
89 //     assert(recycler.exists(doc1_id));
90 //     assert(doc == recycler(doc1_id));
91 
92 //     recycler.erase(doc1_id);
93 //     assert(!recycler.exists(doc1_id));
94 // }