xref: /linux/tools/lib/api/io.h (revision 8ab2e96d8ff188006f1e3346a56443cd07fe1858)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /*
3  * Lightweight buffered reading library.
4  *
5  * Copyright 2019 Google LLC.
6  */
7 #ifndef __API_IO__
8 #define __API_IO__
9 
10 struct io {
11 	/* File descriptor being read/ */
12 	int fd;
13 	/* Size of the read buffer. */
14 	unsigned int buf_len;
15 	/* Pointer to storage for buffering read. */
16 	char *buf;
17 	/* End of the storage. */
18 	char *end;
19 	/* Currently accessed data pointer. */
20 	char *data;
21 	/* Set true on when the end of file on read error. */
22 	bool eof;
23 };
24 
25 static inline void io__init(struct io *io, int fd,
26 			    char *buf, unsigned int buf_len)
27 {
28 	io->fd = fd;
29 	io->buf_len = buf_len;
30 	io->buf = buf;
31 	io->end = buf;
32 	io->data = buf;
33 	io->eof = false;
34 }
35 
36 /* Reads one character from the "io" file with similar semantics to fgetc. */
37 static inline int io__get_char(struct io *io)
38 {
39 	char *ptr = io->data;
40 
41 	if (io->eof)
42 		return -1;
43 
44 	if (ptr == io->end) {
45 		ssize_t n = read(io->fd, io->buf, io->buf_len);
46 
47 		if (n <= 0) {
48 			io->eof = true;
49 			return -1;
50 		}
51 		ptr = &io->buf[0];
52 		io->end = &io->buf[n];
53 	}
54 	io->data = ptr + 1;
55 	return *ptr;
56 }
57 
58 /* Read a hexadecimal value with no 0x prefix into the out argument hex. If the
59  * first character isn't hexadecimal returns -2, io->eof returns -1, otherwise
60  * returns the character after the hexadecimal value which may be -1 for eof.
61  * If the read value is larger than a u64 the high-order bits will be dropped.
62  */
63 static inline int io__get_hex(struct io *io, __u64 *hex)
64 {
65 	bool first_read = true;
66 
67 	*hex = 0;
68 	while (true) {
69 		int ch = io__get_char(io);
70 
71 		if (ch < 0)
72 			return ch;
73 		if (ch >= '0' && ch <= '9')
74 			*hex = (*hex << 4) | (ch - '0');
75 		else if (ch >= 'a' && ch <= 'f')
76 			*hex = (*hex << 4) | (ch - 'a' + 10);
77 		else if (ch >= 'A' && ch <= 'F')
78 			*hex = (*hex << 4) | (ch - 'A' + 10);
79 		else if (first_read)
80 			return -2;
81 		else
82 			return ch;
83 		first_read = false;
84 	}
85 }
86 
87 /* Read a positive decimal value with out argument dec. If the first character
88  * isn't a decimal returns -2, io->eof returns -1, otherwise returns the
89  * character after the decimal value which may be -1 for eof. If the read value
90  * is larger than a u64 the high-order bits will be dropped.
91  */
92 static inline int io__get_dec(struct io *io, __u64 *dec)
93 {
94 	bool first_read = true;
95 
96 	*dec = 0;
97 	while (true) {
98 		int ch = io__get_char(io);
99 
100 		if (ch < 0)
101 			return ch;
102 		if (ch >= '0' && ch <= '9')
103 			*dec = (*dec * 10) + ch - '0';
104 		else if (first_read)
105 			return -2;
106 		else
107 			return ch;
108 		first_read = false;
109 	}
110 }
111 
112 #endif /* __API_IO__ */
113