[Article Contest, first draft] D Slices
Steven Schveighoffer
schveiguy at yahoo.com
Thu May 19 05:30:25 PDT 2011
On Thu, 19 May 2011 07:42:57 -0400, Lars T. Kyllingstad
<public at kyllingen.nospamnet> wrote:
> On Wed, 18 May 2011 14:03:05 -0400, Steven Schveighoffer wrote:
>
>> Having seen quite a few incorrect descriptions of how D slices work
>> (particularly regarding appending), I wrote an article that tries to
>> describe how D slices work, and why they behave the way they do.
>>
>> Being one of the only places where I have web space, it's on my
>> dcollections site, I probably will move it to the D wiki eventually, but
>> I'm much more familiar with the Trac wiki syntax.
>>
>> Please, if you have any comments or recommendations, let me know. I
>> certainly am no author, so I probably screwed a few things up :)
>>
>> http://www.dsource.org/projects/dcollections/wiki/ArrayArticle
>
> This is an excellent article! It answers many questions about the new
> appending system which I've been meaning to ask you for a long time.
Thanks!
>
> One question, still: It seems inconsistent that the value of capacity()
> normally includes the existing slice elements, yet suddenly returns 0
> when the array cannot be appended to. Why doesn't it return
> slice.length?
Well, I think someone has brought that up before, and I thought it was a
good idea, but I found a reason recently for leaving it the way it is.
If an array has completely filled a memory block, and you have a slice
that ends at the end of that memory block, the capacity will be equal to
the slice length. This might be a condition you want to know, vs a slice
that does not end at the end of the array (which currently returns
capacity of 0).
The example I found was a recent request for a way to safely remove an
element from a slice. I recommended to use assumeSafeAppend after
removing the element. The question was then asked, what if the slice is
part of a larger array? Calling assumeSafeAppend effectively invalidates
all elements after the slice. So you want to know positively that a slice
ends at the end of the array, and only call assumeSafeAppend if it's safe
to do so.
Maybe there is a better way to do this, but it turns out to be a useful
inconsistency. Keep in mind that calling capacity is not a simple quick
lookup, so you don't want to have to call it multiple times.
Slices of non-heap arrays also return a capacity of 0.
-Steve
More information about the Digitalmars-d
mailing list