Skip to content

Binary IO Classes #273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: dev
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions kernel/lib/io.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
#pragma once

#include <stddef.h>
#include <stdbool.h>
#include <sys/types.h>

namespace io {

enum whence {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be cased as Whence?

SEEK_SET,
SEEK_CUR,
SEEK_END,
};

class Read {
public:
virtual ~Read() { }
virtual bool isSeekable(void) const = 0;
virtual size_t tell(void) const = 0;
virtual bool seek(off_t offset, whence whence) = 0;
virtual size_t read(void* ptr, size_t size, size_t nmem) = 0;
virtual int error(void) const = 0;
virtual bool eof(void) const = 0;
};

class BufReader :
public Read
{
public:
BufReader(const void* buf, off_t size)
: _buffer((const char* )buf)
, _size(size > 0 ? size : 0)
, _pos(0) {
}
virtual ~BufReader() { }
virtual bool isSeekable(void) const { return true; }
virtual size_t tell(void) const { return _pos; }
virtual bool seek(off_t offset, whence whence) {
off_t target;
switch (whence) {
case SEEK_SET:
target = offset;
break;
case SEEK_CUR:
target = _pos + offset;
break;
case SEEK_END:
target = _size + offset;
break;
default:
return false;
}
if (target < 0 || target > _size)
return false;
_pos = target;
return true;
}
virtual size_t read(void* ptr, size_t size, size_t nmem) {
off_t count = (off_t)(size * nmem);
off_t final = _pos + count;
if (count <= 0 || final < _pos)
return 0;
if (final > _size)
count = _size - _pos;
memcpy(ptr, _buffer + _pos, count);
_pos += count;
return count;
}
virtual int error(void) const { return 0; }
virtual bool eof(void) const { return _pos == _size; }

private:
const char* _buffer;
const off_t _size;
off_t _pos;
};

class BinaryReader {
public:
BinaryReader(Read* reader)
: _reader(reader) {
}

template<typename T>
bool read(T* out) {
return _reader->read(out, sizeof(*out), 1) == sizeof(*out);
}

private:
Read* _reader;
};

}