Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

better support of foreach for array #683

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions std/container.d
Original file line number Diff line number Diff line change
Expand Up @@ -2354,6 +2354,28 @@ Defines the container's primary range, which is a random-access range.
mixin("_outer._payload.ptr[_a + i] "~op~"= value;");
}

int opApply(int delegate(ref T) dg)
{
enforce(_b <= _outer.length);
foreach(i; _a .. _b)
{
int result = dg(_outer._data._payload[i]);
if(result) return result;
}
return 0;
}

int opApplyReverse(int delegate(ref T) dg)
{
enforce(_b <= _outer.length);
foreach_reverse(i; _a .. _b)
{
int result = dg(_outer._data._payload[i]);
if(result) return result;
}
return 0;
}

@property size_t length() const {
return _b - _a;
}
Expand Down Expand Up @@ -2461,6 +2483,44 @@ Complexity: $(BIGOH 1)
return Range(copy, a, b);
}

/**
Iterates over over the elements of the container, applying delegate dg
to each element in forward order.

Complexity: $(BIGOH n)
*/
int opApply(int delegate(ref T) dg)
{
if(_data.RefCounted.isInitialized())
{
foreach(ref v; _data._payload)
{
int result = dg(v);
if(result) return result;
}
}
return 0;
}

/**
Iterates over over the elements of the container, applying delegate dg
to each element in reverse order.

Complexity: $(BIGOH n)
*/
int opApplyReverse(int delegate(ref T) dg)
{
if(_data.RefCounted.isInitialized())
{
foreach_reverse(ref v; _data._payload)
{
int result = dg(v);
if(result) return result;
}
}
return 0;
}

/**
@@@BUG@@@ This doesn't work yet
*/
Expand Down Expand Up @@ -3047,6 +3107,22 @@ unittest
assertThrown(a.replace(r, [42]));
assertThrown(a.linearRemove(r));
}
// Tests that foreach(_reverse) with(out) ref works as intended
unittest
{
auto a = Array!int(1, 2, 3, 4);
foreach(v; a) ++v; //Foreach without ref
assert(equal(a[], [1, 2, 3, 4]));
foreach(ref v; a) ++v; //Foreach ref on container
assert(equal(a[], [2, 3, 4, 5]));
foreach(ref v; a[]) v = 0; //Foreach ref on range
assert(equal(a[], [0, 0, 0, 0]));
int i = 0;
foreach_reverse(ref v; a[]) {v += ++i;} //Foreach_ ref with reverse
assert(equal(a[], [4, 3, 2, 1]));
foreach_reverse(ref v; a[]) {if(v == 3) break; v = 0;} //foreach with break
assert(equal(a[], [4, 3, 0, 0]));
}

// BinaryHeap
/**
Expand Down