Skip to content

Commit

Permalink
Add support for Clear() method
Browse files Browse the repository at this point in the history
closes #30
  • Loading branch information
joaoportela committed Feb 3, 2022
1 parent 8773cab commit 5b1991b
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
9 changes: 5 additions & 4 deletions CircularBuffer.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,15 @@ static void Main(string[] args)
}
Console.WriteLine("\nbuffer.PushFront() {2,1,0} respectively:");
PrintBuffer(buffer);

buffer.Clear();
Console.WriteLine("\nbuffer.Clear():");
PrintBuffer(buffer);
}

private static void PrintBuffer(CircularBuffer<int> buffer)
{
for (int i = 0; i < buffer.Size; i++)
{
Console.WriteLine($"buffer[{i}] = {buffer[i]}");
}
Console.WriteLine($"{{{String.Join(",", buffer.ToArray())}}}");
}
}
}
30 changes: 30 additions & 0 deletions CircularBuffer.Tests/CircularBufferTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -291,5 +291,35 @@ public void CircularBuffer_WithDifferentSizeAndCapacity_BackReturnsLastArrayPosi

Assert.That(buffer.Back(), Is.EqualTo(4));
}

[Test]
public void CircularBuffer_Clear_ClearsContent()
{
var buffer = new CircularBuffer<int>(5, new[] { 4, 3, 2, 1, 0 });

buffer.Clear();

Assert.That(buffer.Size, Is.EqualTo(0));
Assert.That(buffer.Capacity, Is.EqualTo(5));
Assert.That(buffer.ToArray(), Is.EqualTo(new int[0]));
}

[Test]
public void CircularBuffer_Clear_WorksNormallyAfterClear()
{
var buffer = new CircularBuffer<int>(5, new[] { 4, 3, 2, 1, 0 });

buffer.Clear();
for (int i = 0; i < 5; i++)
{
buffer.PushBack(i);
}

Assert.That(buffer.Front(), Is.EqualTo(0));
for (int i = 0; i < 5; i++)
{
Assert.That(buffer[i], Is.EqualTo(i));
}
}
}
}
13 changes: 13 additions & 0 deletions CircularBuffer/CircularBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,19 @@ public void PopFront()
--_size;
}

/// <summary>
/// Clears the contents of the array. Size = 0, Capacity is unchanged.
/// </summary>
/// <exception cref="NotImplementedException"></exception>
public void Clear()
{
// to clear we just reset everything.
_start = 0;
_end = 0;
_size = 0;
Array.Clear(_buffer, 0, _buffer.Length);
}

/// <summary>
/// Copies the buffer contents to an array, according to the logical
/// contents of the buffer (i.e. independent of the internal
Expand Down

0 comments on commit 5b1991b

Please sign in to comment.