dhess / c-ringbuf

A ring buffer implemented in C
Other
418 stars 143 forks source link

the function ringbuf_findchr no match/ index 0 confusion #10

Open ghost opened 5 years ago

ghost commented 5 years ago

hello everyone, don't you think the fuction ringbuf_findchr should return -1 if there is no match ? Ror now it return 0 if there is no match and if the match is at index 0.

dhess commented 5 years ago

ringbuf_findchr returns ringbuf_bytes_used when there is no match, so it only returns 0 when the ring buffer is empty. (If the ring buffer is not empty and there is no match, then the value returned will be > 0.)

It is expected that you will compare the value returned by ringbuf_findchr to the value returned by ringbuf_bytes_used to determine whether a match has been found, e.g.:

https://github.com/dhess/echoev/blob/c74ff579483e3aab5e10b088ef0ba63445dac0bf/echoevc.c#L337

If you compare the two values with <, then there is no ambiguity.

The reason that ringbuf_findchr returns ringbuf_bytes_used when there is no match, rather than returning -1 or some other sentinel value, is so that the type of the returned value can be size_t rather than ssize_t; and the reason for that is for type safety, since ringbuf_findchr itself takes size_t offset values. (Negative offsets make no sense.)

So while this convention is slightly clumsier and a bit more expensive than checking for -1 (because this convention requires an additional call to ringbuf_bytes_used), I think it's worth the type safety.

However, in retrospect, this is all a bit confusing, and I should probably make a note of this convention in the documentation.