Skip to content

Commit

Permalink
validate the return buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
gaochundong committed Oct 22, 2016
1 parent ec7af14 commit daf869a
Showing 1 changed file with 21 additions and 12 deletions.
33 changes: 21 additions & 12 deletions Cowboy/Cowboy.Sockets/Buffer/SegmentBufferManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,12 @@ public ArraySegment<byte> BorrowBuffer()
public IEnumerable<ArraySegment<byte>> BorrowBuffers(int count)
{
var result = new ArraySegment<byte>[count];
var provided = 0;
var trial = 0;
var totalReceived = 0;

try
{
while (provided < TrialsCount)
while (trial < TrialsCount)
{
ArraySegment<byte> piece;
while (totalReceived < count)
Expand All @@ -170,7 +170,7 @@ public IEnumerable<ArraySegment<byte>> BorrowBuffers(int count)
if (totalReceived == count)
return result;
CreateNewSegment(false);
provided++;
trial++;
}
throw new UnableToAllocateBufferException();
}
Expand All @@ -184,8 +184,10 @@ public IEnumerable<ArraySegment<byte>> BorrowBuffers(int count)

public void ReturnBuffer(ArraySegment<byte> buffer)
{
CheckBuffer(buffer);
_buffers.Push(buffer);
if (ValidateBuffer(buffer))
{
_buffers.Push(buffer);
}
}

public void ReturnBuffers(IEnumerable<ArraySegment<byte>> buffers)
Expand All @@ -195,8 +197,10 @@ public void ReturnBuffers(IEnumerable<ArraySegment<byte>> buffers)

foreach (var buf in buffers)
{
CheckBuffer(buf);
_buffers.Push(buf);
if (ValidateBuffer(buf))
{
_buffers.Push(buf);
}
}
}

Expand All @@ -207,17 +211,22 @@ public void ReturnBuffers(params ArraySegment<byte>[] buffers)

foreach (var buf in buffers)
{
CheckBuffer(buf);
_buffers.Push(buf);
if (ValidateBuffer(buf))
{
_buffers.Push(buf);
}
}
}

private void CheckBuffer(ArraySegment<byte> buffer)
private bool ValidateBuffer(ArraySegment<byte> buffer)
{
if (buffer.Array == null || buffer.Count == 0 || buffer.Array.Length < buffer.Offset + buffer.Count)
throw new Exception("Attempt to check in invalid buffer");
return false;

if (buffer.Count != _chunkSize)
throw new ArgumentException("Buffer was not of the same chunk size as the buffer manager", "buffer");
return false;

return true;
}
}
}

0 comments on commit daf869a

Please sign in to comment.