www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Retrieve base type of an array (D2)

Here I created a template for getting an arrays base type. I also made the
std.string.replaceSlice function accessible with wstrings.

May someone could use it or integrate it into phobos...

(module std.traits)
template ArrayBaseType(A : E[],E)
{
	alias E ArrayBaseType;
}


(module std.string)
S replaceSlice(S)(S s, in S slice, in S replacement)
in
{
    alias Unqual!(ArrayBaseType!(S)) E;
/*
static if(is(S==wstring)) 
     static assert(is(E==wchar));
*/
    // Verify that slice[] really is a slice of s[]
    auto so = cast(E*)slice - cast(E*)s;
    assert(so >= 0);
    //printf("s.length = %d, so = %d, slice.length = %d\n", s.length,
    //so, slice.length);
    assert(s.length >= so + slice.length);
}
body
{
    alias Unqual!(ArrayBaseType!(S)) E;

    E[] result;
    int so = cast(E*)slice - cast(E*)s;

    result.length = s.length - slice.length + replacement.length;

    result[0 .. so] = s[0 .. so];
    result[so .. so + replacement.length] = replacement;
    result[so + replacement.length .. result.length] = s[so + slice.length ..
s.length];

    return cast(S)result;
}
Jul 08 2009