1 /* SPDX-License-Identifier: GPL-2.0 */
3 * Lightweight buffered reading library.
5 * Copyright 2019 Google LLC.
17 /* File descriptor being read/ */
19 /* Size of the read buffer. */
21 /* Pointer to storage for buffering read. */
23 /* End of the storage. */
25 /* Currently accessed data pointer. */
27 /* Read timeout, 0 implies no timeout. */
29 /* Set true on when the end of file on read error. */
33 static inline void io__init(struct io *io, int fd,
34 char *buf, unsigned int buf_len)
37 io->buf_len = buf_len;
45 /* Reads one character from the "io" file with similar semantics to fgetc. */
46 static inline int io__get_char(struct io *io)
56 if (io->timeout_ms != 0) {
57 struct pollfd pfds[] = {
64 n = poll(pfds, 1, io->timeout_ms);
67 if (n > 0 && !(pfds[0].revents & POLLIN)) {
76 n = read(io->fd, io->buf, io->buf_len);
83 io->end = &io->buf[n];
89 /* Read a hexadecimal value with no 0x prefix into the out argument hex. If the
90 * first character isn't hexadecimal returns -2, io->eof returns -1, otherwise
91 * returns the character after the hexadecimal value which may be -1 for eof.
92 * If the read value is larger than a u64 the high-order bits will be dropped.
94 static inline int io__get_hex(struct io *io, __u64 *hex)
96 bool first_read = true;
100 int ch = io__get_char(io);
104 if (ch >= '0' && ch <= '9')
105 *hex = (*hex << 4) | (ch - '0');
106 else if (ch >= 'a' && ch <= 'f')
107 *hex = (*hex << 4) | (ch - 'a' + 10);
108 else if (ch >= 'A' && ch <= 'F')
109 *hex = (*hex << 4) | (ch - 'A' + 10);
118 /* Read a positive decimal value with out argument dec. If the first character
119 * isn't a decimal returns -2, io->eof returns -1, otherwise returns the
120 * character after the decimal value which may be -1 for eof. If the read value
121 * is larger than a u64 the high-order bits will be dropped.
123 static inline int io__get_dec(struct io *io, __u64 *dec)
125 bool first_read = true;
129 int ch = io__get_char(io);
133 if (ch >= '0' && ch <= '9')
134 *dec = (*dec * 10) + ch - '0';
143 /* Read up to and including the first newline following the pattern of getline. */
144 static inline ssize_t io__getline(struct io *io, char **line_out, size_t *line_len_out)
148 char *line = NULL, *temp;
152 /* TODO: reuse previously allocated memory. */
155 ch = io__get_char(io);
160 if (buf_pos == sizeof(buf)) {
161 temp = realloc(line, line_len + sizeof(buf));
165 memcpy(&line[line_len], buf, sizeof(buf));
166 line_len += sizeof(buf);
169 buf[buf_pos++] = (char)ch;
171 temp = realloc(line, line_len + buf_pos + 1);
175 memcpy(&line[line_len], buf, buf_pos);
176 line[line_len + buf_pos] = '\0';
179 *line_len_out = line_len;
187 #endif /* __API_IO__ */