www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Why is sort allocating in this case?

reply Jack Stouffer <jack jackstouffer.com> writes:
The docs explicitly say that SwapStrategy.unstable is 
non-allocating, but this code (which is for finding the 
statistical mode of a range) will fail to compile.

auto mode(alias pred = "a == b", R)(R r)  nogc
     if (is(ElementType!R : real) &&
         isInputRange!R &&
         !isInfinite!R)
{
     import core.stdc.stdlib : malloc;

     import std.algorithm.iteration : group;
     import std.algorithm.sorting : sort, SwapStrategy;
     import std.algorithm.mutation : copy;
     import std.typecons : Tuple;

     alias LT = Tuple!(Unqual!(ElementType!R), size_t);

     if (r.empty)
     {
         return real.nan;
     }

     auto grouping = r.group!pred;

     // Because the struct Group does not have swappable elements, 
it cannot be
     // sorted, so copy it to another array
     auto buffer = (cast(LT*) malloc(r.length * LT.sizeof))[0 .. 
r.length];
     copy(grouping, buffer);

     sort!("a[1] > b[1]", SwapStrategy.unstable)(buffer);

     return buffer[0][0];
}


$ dmd/src/dmd -unittest test.d
test.d(439): Error:  nogc function 'test.mode!("a == b", 
int[]).mode' cannot call non- nogc function 
'std.algorithm.sorting.sort!("a[1] > b[1]", cast(SwapStrategy)0, 
Tuple!(int, ulong)[]).sort'
Sep 17 2015
next sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
Works for me. What version are you using? Might be the old one 
wasn't actually marked nogc yet.
Sep 17 2015
parent reply Jack Stouffer <jack jackstouffer.com> writes:
On Friday, 18 September 2015 at 02:24:44 UTC, Adam D. Ruppe wrote:
 Works for me. What version are you using? Might be the old one 
 wasn't actually marked nogc yet.
I'm using the git head, must be a regression.
Sep 17 2015
parent Jack Stouffer <jack jackstouffer.com> writes:
On Friday, 18 September 2015 at 02:29:55 UTC, Jack Stouffer wrote:
 On Friday, 18 September 2015 at 02:24:44 UTC, Adam D. Ruppe 
 wrote:
 Works for me. What version are you using? Might be the old one 
 wasn't actually marked nogc yet.
I'm using the git head, must be a regression.
Well apparently it's not, as I just used digger to check, and the digger version of dmd compiles it just fine. I'm not quite sure how a mis-build or something like that would manifest itself as a nogc error though.
Sep 17 2015
prev sibling parent Vladimir Panteleev <thecybershadow.lists gmail.com> writes:
On Friday, 18 September 2015 at 02:21:13 UTC, Jack Stouffer wrote:
 The docs explicitly say that SwapStrategy.unstable is 
 non-allocating, but this code (which is for finding the 
 statistical mode of a range) will fail to compile.
Perhaps related to this issue you filed? https://issues.dlang.org/show_bug.cgi?id=15003 sort calls assumeSorted, so it's affected by the same problem.
Sep 18 2015