Why does array loses it internal capacity on length change?

2016-03-12 Thread Uldis via Digitalmars-d-learn
While writing a structs function that I wanted to minimize 
allocations and use an internal preallocated buffer, but I 
noticed that arrays are losing their capacity when its length is 
changed.


For example:

void main() {

int[] a;
a.reserve = 1024;

void dump(in ref int[] b,size_t line = __LINE__) {
import std.stdio;
writeln(line, ": Buffer length = ", b.length, " 
capacity= ", b.capacity);

}
dump(a); // line 10
a.length = 0;
dump(a);
a ~= [1,2,3];
dump(a);
a.length = 0;
dump(a);
a ~= [4,5,6];
dump(a);
}

gives output:

10: Buffer length = 0 capacity= 2043
12: Buffer length = 0 capacity= 2043
14: Buffer length = 3 capacity= 2043
16: Buffer length = 0 capacity= 0
18: Buffer length = 3 capacity= 3

but I expected:

10: Buffer length = 0 capacity= 2043
12: Buffer length = 0 capacity= 2043
14: Buffer length = 3 capacity= 2043
16: Buffer length = 0 capacity= 2043
18: Buffer length = 3 capacity= 2043


Why is this happening, how to avoid it?




Re: Usage of custom class with JSONValue

2016-03-24 Thread Uldis via Digitalmars-d-learn

On Thursday, 24 March 2016 at 17:03:25 UTC, Andre wrote:
I hoped there is some operator overloading for implicit 
conversion of my

class to JSONValue.
I solved the issue with an toJSON method and a generic 
functionality which

checks for this method.

Kind regards
André



Vibe.d has some serialization with toJson(), fromJson() methods:
http://vibed.org/api/vibe.data.json/serializeToJson
Maybe you can work with that?