git: 5745a5841413 - main - daemon: replace memchr with memrchr
- Go to: [ bottom of page ] [ top of archives ] [ this month ]
Date: Wed, 27 Dec 2023 06:08:11 UTC
The branch main has been updated by kevans: URL: https://cgit.FreeBSD.org/src/commit/?id=5745a5841413da5c2e002ba65c60d7b9d594bc52 commit 5745a5841413da5c2e002ba65c60d7b9d594bc52 Author: Ihor Antonov <ihor@antonovs.family> AuthorDate: 2023-12-27 06:07:26 +0000 Commit: Kyle Evans <kevans@FreeBSD.org> CommitDate: 2023-12-27 06:07:26 +0000 daemon: replace memchr with memrchr Looping over lines in the buffer is not needed. Same effect can be achieved by looking for the last new line. If found the buffer is guaranteed to have one or more complete lines. All complete lines are flushed at once with no looping. Reviewed by: cperciva, kevans --- usr.sbin/daemon/daemon.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/usr.sbin/daemon/daemon.c b/usr.sbin/daemon/daemon.c index e9c4bf05504c..066240fc8302 100644 --- a/usr.sbin/daemon/daemon.c +++ b/usr.sbin/daemon/daemon.c @@ -587,23 +587,27 @@ static bool listen_child(struct daemon_state *state) { ssize_t rv; + unsigned char *cp; assert(state != NULL); assert(state->pos < LBUF_SIZE - 1); rv = read(state->pipe_fd[0], state->buf + state->pos, LBUF_SIZE - state->pos - 1); if (rv > 0) { - unsigned char *cp; - state->pos += rv; assert(state->pos <= LBUF_SIZE - 1); /* Always NUL-terminate just in case. */ state->buf[LBUF_SIZE - 1] = '\0'; + /* - * Chomp line by line until we run out of buffer. + * Find position of the last newline in the buffer. + * The buffer is guaranteed to have one or more complete lines + * if at least one newline was found when searching in reverse. + * All complete lines are flushed. * This does not take NUL characters into account. */ - while ((cp = memchr(state->buf, '\n', state->pos)) != NULL) { + cp = memrchr(state->buf, '\n', state->pos); + if (cp != NULL) { size_t bytes_line = cp - state->buf + 1; assert(bytes_line <= state->pos); do_output(state->buf, bytes_line, state);