Get the length of data within a buffer (by getting the position of the last byte with data) Background. I start out with a completely empty byte[4096]. As data streams into my application, the byte[4096] gets filled with data starting from first position.

This results in a byte array that is partially filled, but mostly empty, like so...

                0  1  2  3  4  5  6  7  8                       4096
byte[4096] --&gt; [+][+][+][+][+][+][+][+][+][ ][ ][ ][ ][ ][ ] ... [ ]

[+] = Data
[ ] = Empty


I am trying to quickly obtain the position of the last byte with data.



My Question for Code Review

I'm looking for feedback for performance and possibly any correctness in unanticipated cases of this code block:

/// &lt;summary&gt;
/// Get the position of the last byte with data
/// &lt;/summary&gt;
public static int GetPositionOfLastByteWithData(this byte[] array)
{
    int i = array.Length - 1;
    // find the end of the buffer by iterating backwards
    while (array[i] == 0) --i;

    return i;
}


Note: This method will throw an exception in the event that the byte[] passed in is totally blank/empty. In the actual use, I do validate that there is data in the byte array before it gets to this method. This method is aimed squarely for high performance.
If your array is completely "empty" your current method will throw an exeption because it will try to get array[-1].

Just use a for loop starting at 0 and if you find the first 0 return index-1. For the case that the whole buffer is filled return array.Length - 1.  

Update:  

As it seems it is possible that there are 0 values in between valid data like [+][+][+][+][ ][ ][ ][+][+][+][ ]...[ ]. Hence going from start to end of the array doesn't seem a reliable action.  

Using a for loop instead of using the while loop enables your code to do the empty check as well like so  

public const int NotFound = -1;
public static int GetPositionOfLastByteWithData(this byte[] array)
{
    for (int i = array.Length - 1; i &gt; -1; i--)
    {
        if (array[i] &gt; 0) { return i; }
    }
    return NotFound;
}  




As you are talking about streams in your question, wouldn't it be better to store the index of the last written byte ? This would be the easiest and the most safe variant because, assuming you are reading exactly 10 bytes from the stream and later on you need exactly these 10 bytes to restore the read data. If the last byte of that stream would be a 0 like
[+][+][+][+][+][+][+][+][+][ ][ ][ ][ ][ ]...[ ]  

both methods, yours and mine, would return 8 but the really read byte count would be 9.