Merge pull request #610 from jskeet/fix-enumerator

Remove the struct-based iterator for RepeatedField.
This commit is contained in:
Jon Skeet 2015-07-16 09:34:04 +01:00
commit 7ea5239792
2 changed files with 6 additions and 63 deletions

View File

@ -241,18 +241,12 @@ namespace Google.Protobuf.Collections
var list = new RepeatedField<string> { "first", "second" }; var list = new RepeatedField<string> { "first", "second" };
using (var enumerator = list.GetEnumerator()) using (var enumerator = list.GetEnumerator())
{ {
Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
Assert.IsTrue(enumerator.MoveNext()); Assert.IsTrue(enumerator.MoveNext());
Assert.AreEqual("first", enumerator.Current); Assert.AreEqual("first", enumerator.Current);
Assert.IsTrue(enumerator.MoveNext()); Assert.IsTrue(enumerator.MoveNext());
Assert.AreEqual("second", enumerator.Current); Assert.AreEqual("second", enumerator.Current);
Assert.IsFalse(enumerator.MoveNext()); Assert.IsFalse(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
Assert.IsFalse(enumerator.MoveNext()); Assert.IsFalse(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current.GetHashCode());
Assert.IsTrue(enumerator.MoveNext());
Assert.AreEqual("first", enumerator.Current);
} }
} }

View File

@ -288,14 +288,12 @@ namespace Google.Protobuf.Collections
} }
} }
public RepeatedField<T>.Enumerator GetEnumerator() public IEnumerator<T> GetEnumerator()
{ {
return new Enumerator(this); for (int i = 0; i < count; i++)
} {
yield return array[i];
IEnumerator<T> IEnumerable<T>.GetEnumerator() }
{
return GetEnumerator();
} }
public override bool Equals(object obj) public override bool Equals(object obj)
@ -468,54 +466,5 @@ namespace Google.Protobuf.Collections
Remove((T)value); Remove((T)value);
} }
#endregion #endregion
public struct Enumerator : IEnumerator<T>
{
private int index;
private readonly RepeatedField<T> field;
public Enumerator(RepeatedField<T> field)
{
this.field = field;
this.index = -1;
}
public bool MoveNext()
{
if (index + 1 >= field.Count)
{
index = field.Count;
return false;
}
index++;
return true;
}
public void Reset()
{
index = -1;
}
public T Current
{
get
{
if (index == -1 || index >= field.count)
{
throw new InvalidOperationException();
}
return field.array[index];
}
}
object IEnumerator.Current
{
get { return Current; }
}
public void Dispose()
{
}
}
} }
} }