September 16, 2014
https://issues.dlang.org/show_bug.cgi?id=13482

          Issue ID: 13482
           Summary: std.algorithm.podSort
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody@puremagic.com
          Reporter: bearophile_hugs@eml.cc

A pair of overloaded functions like this could be useful to add to Phobos to avoid most of the template bloat caused by std.algorithm.sort in the situations where the maximum sorting performance and flexibility (this just accepts an array) is not strictly necessary:


import std.array: empty;
import core.stdc.stdlib: qsort;
import std.range: hasSwappableElements, hasAssignableElements;
import std.traits: isCallable, ReturnType, arity;

void podSort(T)(T[] items)
if (__traits(isPOD, T) &&
    hasSwappableElements!(typeof(items)) &&
    hasAssignableElements!(typeof(items))) {
    if (items.empty)
        return;

    static extern(C) int cmp(const void* a, const void* b) {
        auto x = cast(T*)a;
        auto y = cast(T*)b;
        return (*x == *y) ? 0 : ((*x < *y) ? -1 : 1);
    }

    qsort(items.ptr,
          items.length,
          T.sizeof,
          &cmp);
}

void podSort(alias cmp, T)(T[] items)
if (__traits(isPOD, T) &&
    hasSwappableElements!(typeof(items)) &&
    hasAssignableElements!(typeof(items)) &&
    isCallable!cmp &&
    is(ReturnType!cmp == int) &&
    arity!cmp == 2) {
    if (items.empty)
        return;

    extern(C) int ccmp(const void* a, const void* b) {
        auto x = cast(T*)a;
        auto y = cast(T*)b;
        return cmp(*x, *y);
    }

    qsort(items.ptr,
          items.length,
          T.sizeof,
          &ccmp);
}

//--------------------------

void main() {
    import std.stdio;

    auto a = [10, 7, 2, 11, 9, 0, 3];
    auto b = a.dup;

    a.podSort;
    a.writeln;

    static int cmp1(const ref int x, const ref int y) {
        return (x == y) ? 0 : ((x > y) ? -1 : 1);
    }

    podSort!cmp1(b);
    b.writeln; // reversed
}


(This code is not perfect, not well tested, its constraints are not very good. It's just to give an idea of what I meant).

--