Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

the function ringbuf_findchr no match/ index 0 confusion #10

Open
ghost opened this issue Jul 10, 2018 · 1 comment
Open

the function ringbuf_findchr no match/ index 0 confusion #10

ghost opened this issue Jul 10, 2018 · 1 comment
Assignees
Labels

Comments

@ghost
Copy link

ghost commented Jul 10, 2018

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 dhess self-assigned this Jul 10, 2018
@dhess dhess added the docfix label Jul 10, 2018
@dhess
Copy link
Owner

dhess commented Jul 10, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant