1 /* SPDX-License-Identifier: GPL-2.0 */
3 * Lightweight buffered reading library.
5 * Copyright 2019 Google LLC.
12 #include <linux/types.h>
15 /* File descriptor being read/ */
17 /* Size of the read buffer. */
19 /* Pointer to storage for buffering read. */
21 /* End of the storage. */
23 /* Currently accessed data pointer. */
25 /* Set true on when the end of file on read error. */
29 static inline void io__init(struct io *io, int fd,
30 char *buf, unsigned int buf_len)
33 io->buf_len = buf_len;
40 /* Reads one character from the "io" file with similar semantics to fgetc. */
41 static inline int io__get_char(struct io *io)
49 ssize_t n = read(io->fd, io->buf, io->buf_len);
56 io->end = &io->buf[n];
62 /* Read a hexadecimal value with no 0x prefix into the out argument hex. If the
63 * first character isn't hexadecimal returns -2, io->eof returns -1, otherwise
64 * returns the character after the hexadecimal value which may be -1 for eof.
65 * If the read value is larger than a u64 the high-order bits will be dropped.
67 static inline int io__get_hex(struct io *io, __u64 *hex)
69 bool first_read = true;
73 int ch = io__get_char(io);
77 if (ch >= '0' && ch <= '9')
78 *hex = (*hex << 4) | (ch - '0');
79 else if (ch >= 'a' && ch <= 'f')
80 *hex = (*hex << 4) | (ch - 'a' + 10);
81 else if (ch >= 'A' && ch <= 'F')
82 *hex = (*hex << 4) | (ch - 'A' + 10);
91 /* Read a positive decimal value with out argument dec. If the first character
92 * isn't a decimal returns -2, io->eof returns -1, otherwise returns the
93 * character after the decimal value which may be -1 for eof. If the read value
94 * is larger than a u64 the high-order bits will be dropped.
96 static inline int io__get_dec(struct io *io, __u64 *dec)
98 bool first_read = true;
102 int ch = io__get_char(io);
106 if (ch >= '0' && ch <= '9')
107 *dec = (*dec * 10) + ch - '0';
116 #endif /* __API_IO__ */