2 * Copyright: 2014 by Digital Mars
3 * License: $(LINK2 http://boost.org/LICENSE_1_0.txt, Boost License 1.0).
4 * Authors: Walter Bright
5 * Source: $(PHOBOSSRC std/internal/_scopebuffer.d)
8 module std.internal.scopebuffer;
13 import core.stdc.stdlib : realloc;
16 /**************************************
17 * ScopeBuffer encapsulates using a local array as a temporary buffer.
18 * It is initialized with a local array that should be large enough for
19 * most uses. If the need exceeds that size, ScopeBuffer will reallocate
20 * the data using its `realloc` function.
22 * ScopeBuffer cannot contain more than `(uint.max-16)/2` elements.
24 * ScopeBuffer is an Output Range.
26 * Since ScopeBuffer may store elements of type `T` in `malloc`'d memory,
27 * those elements are not scanned when the GC collects. This can cause
28 * memory corruption. Do not use ScopeBuffer when elements of type `T` point
29 * to the GC heap, except when a `realloc` function is provided which supports this.
33 import core.stdc.stdio;
34 import std.internal.scopebuffer;
38 auto textbuf = ScopeBuffer!char(buf);
39 scope(exit) textbuf.free(); // necessary for cleanup
41 // Put characters and strings into textbuf, verify they got there
45 assert(textbuf.length == 5);
46 assert(textbuf[1 .. 3] == "xa");
47 assert(textbuf[3] == 'b');
51 assert(textbuf[0 .. textbuf.length] == "axa");
52 assert(textbuf[textbuf.length - 1] == 'a');
53 assert(textbuf[1 .. 3] == "xa");
56 assert(textbuf[] == "axaz");
58 // Can shrink it to 0 size, and reuse same memory
62 * It is invalid to access ScopeBuffer's contents when ScopeBuffer goes out of scope.
63 * Hence, copying the contents are necessary to keep them around:
65 import std.internal.scopebuffer;
66 string cat(string s1, string s2)
68 char[10] tmpbuf = void;
69 auto textbuf = ScopeBuffer!char(tmpbuf);
70 scope(exit) textbuf.free();
73 textbuf.put("even more");
74 return textbuf[].idup;
77 * ScopeBuffer is intended for high performance usages in $(D @system) and $(D @trusted) code.
78 * It is designed to fit into two 64 bit registers, again for high performance use.
79 * If used incorrectly, memory leaks and corruption can result. Be sure to use
80 * $(D scope(exit) textbuf.free();) for proper cleanup, and do not refer to a ScopeBuffer
81 * instance's contents after $(D ScopeBuffer.free()) has been called.
83 * The `realloc` parameter defaults to C's `realloc()`. Another can be supplied to override it.
85 * ScopeBuffer instances may be copied, as in:
87 textbuf = doSomething(textbuf, args);
89 * which can be very efficent, but these must be regarded as a move rather than a copy.
90 * Additionally, the code between passing and returning the instance must not throw
91 * exceptions, otherwise when `ScopeBuffer.free()` is called, memory may get corrupted.
95 struct ScopeBuffer(T, alias realloc = /*core.stdc.stdlib*/.realloc)
97 !hasElaborateDestructor!T &&
98 !hasElaborateCopyConstructor!T &&
99 !hasElaborateAssign!T)
101 import core.exception : onOutOfMemoryError;
102 import core.stdc.string : memcpy;
105 /**************************
106 * Initialize with buf to use as scratch buffer space.
108 * buf = Scratch buffer space, must have length that is even
111 * ubyte[10] tmpbuf = void;
112 * auto sbuf = ScopeBuffer!ubyte(tmpbuf);
115 * If buf was created by the same `realloc` passed as a parameter
116 * to `ScopeBuffer`, then the contents of `ScopeBuffer` can be extracted without needing
117 * to copy them, and `ScopeBuffer.free()` will not need to be called.
122 assert(!(buf.length & wasResized)); // assure even length of scratch buffer space
123 assert(buf.length <= uint.max); // because we cast to uint later
128 this.bufLen = cast(uint) buf.length;
133 ubyte[10] tmpbuf = void;
134 auto sbuf = ScopeBuffer!ubyte(tmpbuf);
137 /**************************
138 * Releases any memory used.
139 * This will invalidate any references returned by the `[]` operator.
140 * A destructor is not used, because that would make it not POD
141 * (Plain Old Data) and it could not be placed in registers.
145 debug(ScopeBuffer) buf[0 .. bufLen] = 0;
146 if (bufLen & wasResized)
153 /************************
154 * Append element c to the buffer.
155 * This member function makes `ScopeBuffer` an Output Range.
159 /* j will get enregistered, while used will not because resize() may change used
164 assert(j <= (uint.max - 16) / 2);
171 /************************
172 * Append array s to the buffer.
174 * If $(D const(T)) can be converted to $(D T), then put will accept
175 * $(D const(T)[]) as input. It will accept a $(D T[]) otherwise.
177 package alias CT = Select!(is(const(T) : T), const(T), T);
181 const newlen = used + s.length;
182 assert((cast(ulong) used + s.length) <= uint.max);
186 assert(len <= uint.max / 2);
187 resize(newlen <= len * 2 ? len * 2 : newlen);
189 buf[used .. newlen] = s[];
190 used = cast(uint) newlen;
195 * A slice into the temporary buffer.
197 * The result is only valid until the next `put()` or `ScopeBuffer` goes out of scope.
199 @system inout(T)[] opSlice(size_t lower, size_t upper) inout
202 assert(lower <= bufLen);
203 assert(upper <= bufLen);
204 assert(lower <= upper);
208 return buf[lower .. upper];
212 @system inout(T)[] opSlice() inout
214 assert(used <= bufLen);
215 return buf[0 .. used];
220 * The element at index i.
222 ref inout(T) opIndex(size_t i) inout
230 * The number of elements in the `ScopeBuffer`.
232 @property size_t length() const
238 * Used to shrink the length of the buffer,
239 * typically to `0` so the buffer can be reused.
240 * Cannot be used to extend the length of the buffer.
242 @property void length(size_t i)
245 assert(i <= this.used);
249 this.used = cast(uint) i;
252 alias opDollar = length;
256 // Using uint instead of size_t so the struct fits in 2 registers in 64 bit code
258 enum wasResized = 1; // this bit is set in bufLen if we control the memory
261 void resize(size_t newsize)
264 assert(newsize <= uint.max);
268 //writefln("%s: oldsize %s newsize %s", id, buf.length, newsize);
269 newsize |= wasResized;
270 void *newBuf = realloc((bufLen & wasResized) ? buf : null, newsize * T.sizeof);
272 onOutOfMemoryError();
273 if (!(bufLen & wasResized))
275 memcpy(newBuf, buf, used * T.sizeof);
276 debug(ScopeBuffer) buf[0 .. bufLen] = 0;
278 buf = cast(T*) newBuf;
279 bufLen = cast(uint) newsize;
281 /* This function is called only rarely,
282 * inlining results in poorer register allocation.
284 version (DigitalMars)
285 /* With dmd, a fake loop will prevent inlining.
286 * Using a hack until a language enhancement is implemented.
294 import core.stdc.stdio;
297 char[2] tmpbuf = void;
299 // Exercise all the lines of code except for assert(0)'s
300 auto textbuf = ScopeBuffer!char(tmpbuf);
301 scope(exit) textbuf.free();
303 static assert(isOutputRange!(ScopeBuffer!char, char));
307 textbuf.put("abc"); // tickle put([])'s resize
308 assert(textbuf.length == 5);
309 assert(textbuf[1 .. 3] == "xa");
310 assert(textbuf[3] == 'b');
312 textbuf.length = textbuf.length - 1;
313 assert(textbuf[0 .. textbuf.length] == "axab");
316 assert(textbuf[0 .. textbuf.length] == "axa");
317 assert(textbuf[textbuf.length - 1] == 'a');
318 assert(textbuf[1 .. 3] == "xa");
320 textbuf.put(cast(dchar)'z');
321 assert(textbuf[] == "axaz");
323 textbuf.length = 0; // reset for reuse
324 assert(textbuf.length == 0);
326 foreach (char c; "asdf;lasdlfaklsdjfalksdjfa;lksdjflkajsfdasdfkja;sdlfj")
328 textbuf.put(c); // tickle put(c)'s resize
330 assert(textbuf[] == "asdf;lasdlfaklsdjfalksdjfa;lksdjflkajsfdasdfkja;sdlfj");
331 } // run destructor on textbuf here
337 string cat(string s1, string s2)
339 char[10] tmpbuf = void;
340 auto textbuf = ScopeBuffer!char(tmpbuf);
341 scope(exit) textbuf.free();
344 textbuf.put("even more");
345 return textbuf[].idup;
348 auto s = cat("hello", "betty");
349 assert(s == "hellobettyeven more");
355 char[10] tmpbuf = void;
356 auto textbuf = ScopeBuffer!char(tmpbuf);
357 scope(exit) textbuf.free();
358 foreach (i; 0 .. 10) textbuf.put('w');
361 const slice0 = csb[0 .. 5];
362 const slice1 = csb[];
365 /*********************************
366 * Creates a `ScopeBuffer` instance using type deduction - see
367 * $(LREF .ScopeBuffer.this) for details.
369 * tmpbuf = the initial buffer to use
371 * An instance of `ScopeBuffer`.
374 auto scopeBuffer(T)(T[] tmpbuf)
376 return ScopeBuffer!T(tmpbuf);
382 ubyte[10] tmpbuf = void;
383 auto sb = scopeBuffer(tmpbuf);
384 scope(exit) sb.free();
389 ScopeBuffer!(int*) b;