Skip to content

Commit ba0e1b9

Browse files
committed
Add basic Read interface with a simple BufReader
1 parent f6bc5fe commit ba0e1b9

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

kernel/lib/io.hpp

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
#pragma once
2+
3+
#include <stddef.h>
4+
#include <stdbool.h>
5+
#include <sys/types.h>
6+
7+
namespace io {
8+
9+
enum whence {
10+
SEEK_SET,
11+
SEEK_CUR,
12+
SEEK_END,
13+
};
14+
15+
class Read {
16+
public:
17+
virtual ~Read() { }
18+
virtual bool isSeekable(void) = 0;
19+
virtual size_t tell(void) = 0;
20+
virtual bool seek(off_t offset, whence whence) = 0;
21+
virtual size_t read(void *ptr, size_t size, size_t nmem) = 0;
22+
virtual int error(void) = 0;
23+
virtual bool eof(void) = 0;
24+
};
25+
26+
class BufReader :
27+
public Read
28+
{
29+
public:
30+
BufReader(const void *buf, off_t size)
31+
: _buffer((const char *)buf)
32+
, _size(size > 0 ? size : 0)
33+
, _pos(0) {
34+
}
35+
virtual ~BufReader() { }
36+
virtual bool isSeekable(void) { return true; }
37+
virtual size_t tell(void) { return _pos; }
38+
virtual bool seek(off_t offset, whence whence) {
39+
off_t target;
40+
switch (whence) {
41+
case SEEK_SET:
42+
target = offset;
43+
break;
44+
case SEEK_CUR:
45+
target = _pos + offset;
46+
break;
47+
case SEEK_END:
48+
target = _size + offset;
49+
break;
50+
default:
51+
return false;
52+
}
53+
if (target < 0 || target > _size)
54+
return false;
55+
_pos = target;
56+
return true;
57+
}
58+
virtual size_t read(void *ptr, size_t size, size_t nmem) {
59+
off_t count = (off_t)(size * nmem);
60+
off_t final = _pos + count;
61+
if (count <= 0 || final < _pos)
62+
return 0;
63+
if (final > _size)
64+
count = _size - _pos;
65+
memcpy(ptr, _buffer + _pos, count);
66+
_pos += count;
67+
return count;
68+
}
69+
virtual int error(void) { return 0; }
70+
virtual bool eof(void) { return _pos == _size; }
71+
72+
private:
73+
const char *_buffer;
74+
const off_t _size;
75+
off_t _pos;
76+
};
77+
78+
}

0 commit comments

Comments
 (0)