The algorithms in std.algorithm are great. They operate the same on
arrays/slices and generic ranges. But they return their own range-types.
Often this ok but sometimes you need a T[]. You may say to just use
array() but this allocates a new array! I think you sometimes want to
get a slice to the original array. I wrote this function. It checks if
it is ok what it is doing at runtime.
////////////
import std.stdio, std.algorithm, std.range, std.conv, std.exception;
void main() {
auto x = [0, 1, 2, 3, 4, 5];
auto t = x.take(3);
foreach(i, ref elem; t) {
writefln("%s : %s (%s)", i, elem, &elem);
}
foreach(i, ref elem; array(t)) {
writefln("%s : %s (%s)", i, elem, &elem);
}
foreach(i, ref elem; slice(t)) {
writefln("%s : %s (%s)", i, elem, &elem);
}
}
/**
Retuns a slices of the data the given range represents.
throws: ConvException if the data is not continous.
*
ElementType!(R)[] slice(R)(R range) if(isInputRange!R) {
alias ElementType!(R) E;
E* addr = null;
size_t length = 0;
foreach(i, ref e; range) {
static assert(is(typeof(e) == E));
if(addr is null) {
addr = &e;
} else {
enforce(&e is (addr + i), new ConvException("Could not
create a continous slice."));
}
length++;
assert(i == length-1);
}
if (addr is null) return null;
else return addr[0.. length];
}
//////////////
Is there functinality like this in phobos? Does such a function fit into
the range world.