0001
0002
0003
0004
0005
0006
0007 #ifndef __API_IO__
0008 #define __API_IO__
0009
0010 #include <stdlib.h>
0011 #include <unistd.h>
0012
0013 struct io {
0014
0015 int fd;
0016
0017 unsigned int buf_len;
0018
0019 char *buf;
0020
0021 char *end;
0022
0023 char *data;
0024
0025 bool eof;
0026 };
0027
0028 static inline void io__init(struct io *io, int fd,
0029 char *buf, unsigned int buf_len)
0030 {
0031 io->fd = fd;
0032 io->buf_len = buf_len;
0033 io->buf = buf;
0034 io->end = buf;
0035 io->data = buf;
0036 io->eof = false;
0037 }
0038
0039
0040 static inline int io__get_char(struct io *io)
0041 {
0042 char *ptr = io->data;
0043
0044 if (io->eof)
0045 return -1;
0046
0047 if (ptr == io->end) {
0048 ssize_t n = read(io->fd, io->buf, io->buf_len);
0049
0050 if (n <= 0) {
0051 io->eof = true;
0052 return -1;
0053 }
0054 ptr = &io->buf[0];
0055 io->end = &io->buf[n];
0056 }
0057 io->data = ptr + 1;
0058 return *ptr;
0059 }
0060
0061
0062
0063
0064
0065
0066 static inline int io__get_hex(struct io *io, __u64 *hex)
0067 {
0068 bool first_read = true;
0069
0070 *hex = 0;
0071 while (true) {
0072 int ch = io__get_char(io);
0073
0074 if (ch < 0)
0075 return ch;
0076 if (ch >= '0' && ch <= '9')
0077 *hex = (*hex << 4) | (ch - '0');
0078 else if (ch >= 'a' && ch <= 'f')
0079 *hex = (*hex << 4) | (ch - 'a' + 10);
0080 else if (ch >= 'A' && ch <= 'F')
0081 *hex = (*hex << 4) | (ch - 'A' + 10);
0082 else if (first_read)
0083 return -2;
0084 else
0085 return ch;
0086 first_read = false;
0087 }
0088 }
0089
0090
0091
0092
0093
0094
0095 static inline int io__get_dec(struct io *io, __u64 *dec)
0096 {
0097 bool first_read = true;
0098
0099 *dec = 0;
0100 while (true) {
0101 int ch = io__get_char(io);
0102
0103 if (ch < 0)
0104 return ch;
0105 if (ch >= '0' && ch <= '9')
0106 *dec = (*dec * 10) + ch - '0';
0107 else if (first_read)
0108 return -2;
0109 else
0110 return ch;
0111 first_read = false;
0112 }
0113 }
0114
0115 #endif