diff options
author | Dmitry Torokhov <dmitry.torokhov@gmail.com> | 2023-08-30 16:06:38 -0700 |
---|---|---|
committer | Dmitry Torokhov <dmitry.torokhov@gmail.com> | 2023-08-30 16:06:38 -0700 |
commit | 1ac731c529cd4d6adbce134754b51ff7d822b145 (patch) | |
tree | 143ab3f35ca5f3b69f583c84e6964b17139c2ec1 /tools/lib/api/io.h | |
parent | 07b4c950f27bef0362dc6ad7ee713aab61d58149 (diff) | |
parent | 54116d442e001e1b6bd482122043b1870998a1f3 (diff) |
Merge branch 'next' into for-linus
Prepare input updates for 6.6 merge window.
Diffstat (limited to 'tools/lib/api/io.h')
-rw-r--r-- | tools/lib/api/io.h | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/tools/lib/api/io.h b/tools/lib/api/io.h index 777c20f6b604..d5e8cf0dada0 100644 --- a/tools/lib/api/io.h +++ b/tools/lib/api/io.h @@ -7,7 +7,9 @@ #ifndef __API_IO__ #define __API_IO__ +#include <errno.h> #include <stdlib.h> +#include <string.h> #include <unistd.h> struct io { @@ -112,4 +114,47 @@ static inline int io__get_dec(struct io *io, __u64 *dec) } } +/* Read up to and including the first newline following the pattern of getline. */ +static inline ssize_t io__getline(struct io *io, char **line_out, size_t *line_len_out) +{ + char buf[128]; + int buf_pos = 0; + char *line = NULL, *temp; + size_t line_len = 0; + int ch = 0; + + /* TODO: reuse previously allocated memory. */ + free(*line_out); + while (ch != '\n') { + ch = io__get_char(io); + + if (ch < 0) + break; + + if (buf_pos == sizeof(buf)) { + temp = realloc(line, line_len + sizeof(buf)); + if (!temp) + goto err_out; + line = temp; + memcpy(&line[line_len], buf, sizeof(buf)); + line_len += sizeof(buf); + buf_pos = 0; + } + buf[buf_pos++] = (char)ch; + } + temp = realloc(line, line_len + buf_pos + 1); + if (!temp) + goto err_out; + line = temp; + memcpy(&line[line_len], buf, buf_pos); + line[line_len + buf_pos] = '\0'; + line_len += buf_pos; + *line_out = line; + *line_len_out = line_len; + return line_len; +err_out: + free(line); + return -ENOMEM; +} + #endif /* __API_IO__ */ |