Skip to content

Instantly share code, notes, and snippets.

@JakobOvrum
Created April 17, 2014 10:33
Show Gist options
  • Save JakobOvrum/10972257 to your computer and use it in GitHub Desktop.
Save JakobOvrum/10972257 to your computer and use it in GitHub Desktop.
removeSpan overload set
import std.traits;
import std.range;
E[] removeSpan(E)(E[] arr, size_t from, size_t to) @trusted
if (isMutable!E && !hasElaborateAssign!E)
{
import core.exception : RangeError;
import core.stdc.string : memmove;
import std.exception : enforceEx;
immutable len = arr.length;
enforceEx!RangeError(to <= len && from < to);
immutable tailLen = len - to;
memmove(arr.ptr + from, arr.ptr + to, tailLen * E.sizeof);
return arr[0 .. from + tailLen];
}
unittest
{
auto arr = [1, 2, 3];
arr = arr.removeSpan(1, 2);
assert(arr == [1, 3]);
arr = [1, 2, 3, 4, 5, 6];
arr = arr.removeSpan(1, 4);
assert(arr == [1, 5, 6]);
}
E[] removeSpan(E)(E[] arr, size_t from, size_t to)
if (isMutable!E && hasElaborateAssign!E)
{
auto tailLen = arr.length - to;
foreach(i, ref e; arr[from .. tailLen + 1])
e = arr[to + i];
return arr[0 .. from + tailLen];
}
unittest
{
static struct S
{
int n = 0;
void opAssign(ref S other)
{
this.n = other.n * 10;
}
}
auto arr = [S(0), S(1), S(2), S(3), S(4)];
arr = arr.removeSpan(1, 3);
import std.stdio;
writeln(arr);
assert(arr == [S(0), S(30), S(40)]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment