1 /* SPDX-License-Identifier: GPL-2.0 */
3 * Lightweight buffered reading library.
5 * Copyright 2019 Google LLC.
15 #include <linux/types.h>
18 /* File descriptor being read/ */
20 /* Size of the read buffer. */
22 /* Pointer to storage for buffering read. */
24 /* End of the storage. */
26 /* Currently accessed data pointer. */
28 /* Read timeout, 0 implies no timeout. */
30 /* Set true on when the end of file on read error. */
34 static inline void io__init(struct io *io, int fd,
35 char *buf, unsigned int buf_len)
38 io->buf_len = buf_len;
46 /* Reads one character from the "io" file with similar semantics to fgetc. */
47 static inline int io__get_char(struct io *io)
57 if (io->timeout_ms != 0) {
58 struct pollfd pfds[] = {
65 n = poll(pfds, 1, io->timeout_ms);
68 if (n > 0 && !(pfds[0].revents & POLLIN)) {
77 n = read(io->fd, io->buf, io->buf_len);
84 io->end = &io->buf[n];
90 /* Read a hexadecimal value with no 0x prefix into the out argument hex. If the
91 * first character isn't hexadecimal returns -2, io->eof returns -1, otherwise
92 * returns the character after the hexadecimal value which may be -1 for eof.
93 * If the read value is larger than a u64 the high-order bits will be dropped.
95 static inline int io__get_hex(struct io *io, __u64 *hex)
97 bool first_read = true;
101 int ch = io__get_char(io);
105 if (ch >= '0' && ch <= '9')
106 *hex = (*hex << 4) | (ch - '0');
107 else if (ch >= 'a' && ch <= 'f')
108 *hex = (*hex << 4) | (ch - 'a' + 10);
109 else if (ch >= 'A' && ch <= 'F')
110 *hex = (*hex << 4) | (ch - 'A' + 10);
119 /* Read a positive decimal value with out argument dec. If the first character
120 * isn't a decimal returns -2, io->eof returns -1, otherwise returns the
121 * character after the decimal value which may be -1 for eof. If the read value
122 * is larger than a u64 the high-order bits will be dropped.
124 static inline int io__get_dec(struct io *io, __u64 *dec)
126 bool first_read = true;
130 int ch = io__get_char(io);
134 if (ch >= '0' && ch <= '9')
135 *dec = (*dec * 10) + ch - '0';
144 /* Read up to and including the first delim. */
145 static inline ssize_t io__getdelim(struct io *io, char **line_out, size_t *line_len_out, int delim)
149 char *line = NULL, *temp;
153 /* TODO: reuse previously allocated memory. */
155 while (ch != delim) {
156 ch = io__get_char(io);
161 if (buf_pos == sizeof(buf)) {
162 temp = realloc(line, line_len + sizeof(buf));
166 memcpy(&line[line_len], buf, sizeof(buf));
167 line_len += sizeof(buf);
170 buf[buf_pos++] = (char)ch;
172 temp = realloc(line, line_len + buf_pos + 1);
176 memcpy(&line[line_len], buf, buf_pos);
177 line[line_len + buf_pos] = '\0';
180 *line_len_out = line_len;
188 static inline ssize_t io__getline(struct io *io, char **line_out, size_t *line_len_out)
190 return io__getdelim(io, line_out, line_len_out, /*delim=*/'\n');
193 #endif /* __API_IO__ */