Bug 6193 – Appender.clear() functionality or documentation
Status
RESOLVED
Resolution
FIXED
Severity
minor
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-06-21T16:12:00Z
Last change time
2011-06-22T06:15:52Z
Assigned to
schveiguy
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2011-06-21T16:12:43Z
This is an enhancement request, or (because I am often mistaken) it's just an enhancement request for the documentation.
This program works with DMD 2.053:
import std.stdio;
void main() {
string foo = "abc";
foo ~= 'a';
foo.length = 0;
}
This other program too runs:
import std.array: Appender;
void main() {
Appender!(char[]) foo;
foo.put('a');
foo.clear();
}
But this gives an error:
temp.d(5): Error: no property 'clear' for type 'Appender!(string)'
import std.array: Appender;
void main() {
Appender!string foo;
foo.put('a');
foo.clear();
}
Strings are made of immutable chars, but you are allowed to clear (set the length to zero) a string. So I expect Appender to allow the same.
If this not a good thing, then I suggest to add to the online docs of the std.array.Appender.clear() method a note that explains it is present (compiled-in) only in certain cases. Because currently I haven't seen a mention of this, and the error message given by the compiler doesn't explain enough.
Comment #1 by schveiguy — 2011-06-22T06:02:18Z
It is intentionally missing from Appender when the data type is immutable or const. See the code here:
https://github.com/D-Programming-Language/phobos/blob/master/std/array.d#L1870
The issue is because Appender owns the data it's appending to, clearing the data will *reuse* the buffer to do appending again. But this would violate the requirements for immutable. This is different from setting a slice length to 0, because a slice *does not own* the data. Appending to a slice whose length was set to 0 would allocate a *new* block to append into.
The equivalent slice code for Appender.clear is:
slice.length = 0;
slice.assumeSafeAppend();
There is a reason const is also included. Appender can take an *existing* buffer and use it as the base for appending. Since Appender!(const(T)[]) can accept an immutable(T)[], you would have the same issue if you then called clear on the data.
I'll note that clear is not enabled when the Appender is for const or immutable arrays in the documentation.