-
Notifications
You must be signed in to change notification settings - Fork 0
/
RangeEnumerator.cs
90 lines (73 loc) · 1.86 KB
/
RangeEnumerator.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
/// <summary>
/// Provides iterating in foreach and manipulating via LINQ over elements of range
/// </summary>
public struct RangeEnumerator : IEnumerator<int>
{
private Range _range;
private int _current;
private int _mode; // 0 - not started, 1 - started, 2- finished
private bool HasMoreElement { get { return (_current != _range.Stop) && ((_current < _range.Stop) ^ (_range.Step < 0)); } }
internal RangeEnumerator(ref Range range)
{
_range = range;
_mode = 0;
_current = 0;
}
public void Dispose() { }
public bool MoveNext()
{
switch (_mode)
{
case 0:
_mode = 1;
_current = _range.Start;
return true;
case 1:
_current += _range.Step;
if (!HasMoreElement)
{
_mode = 2;
return false;
}
return true;
default: // 2
return false;
}
}
public void Reset()
{
_mode = 0;
}
bool IEnumerator.MoveNext()
{
return MoveNext();
}
void IEnumerator.Reset()
{
Reset();
}
void IDisposable.Dispose()
{
Dispose();
}
object IEnumerator.Current { get { return Current as object; } }
public int Current
{
get
{
switch (_mode)
{
case 1:
return _current;
case 0:
throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
default: //2
throw new InvalidOperationException("Enumeration already finished.");
}
}
}
}