#include <algorithm>
#include <cstring>
-#include "except.h"
+#include "handle.h"
#include "memory.h"
using namespace std;
namespace Msp {
namespace IO {
-Memory::Memory(char *d, unsigned s)
+Memory::Memory(char *b, char *e, Mode m)
{
- init(d, d+s, M_RDWR);
-}
-
-Memory::Memory(char *b, char *e)
-{
- init(b, e, M_RDWR);
-}
-
-Memory::Memory(const char *cd, unsigned s)
-{
- char *d = const_cast<char *>(cd);
- init(d, d+s, M_READ);
+ begin = b;
+ end = e;
+ pos = begin;
+ mode = m;
}
-Memory::Memory(const char *b, const char *e)
+void Memory::set_block(bool)
{
- init(const_cast<char *>(b), const_cast<char *>(e), M_READ);
+ throw logic_error("Memory::set_block");
}
-void Memory::init(char *b, char *e, Mode m)
+void Memory::set_inherit(bool)
{
- begin = b;
- end = e;
- pos = begin;
- mode = m;
+ throw logic_error("Memory::set_inherit");
}
-unsigned Memory::do_write(const char *buf, unsigned size)
+size_t Memory::do_write(const char *buf, size_t size)
{
- check_mode(M_WRITE);
+ check_access(M_WRITE);
- size = min<unsigned>(size, end-pos);
+ size = min<size_t>(size, end-pos);
memcpy(pos, buf, size);
pos += size;
return size;
}
-unsigned Memory::do_read(char *buf, unsigned size)
+size_t Memory::do_read(char *buf, size_t size)
{
+ check_access(M_READ);
+
if(pos==end)
{
- eof_flag = true;
+ set_eof();
return 0;
}
- size = min<unsigned>(size, end-pos);
+ size = min<size_t>(size, end-pos);
memcpy(buf, pos, size);
pos += size;
return size;
}
-unsigned Memory::put(char c)
+size_t Memory::put(char c)
{
- check_mode(M_WRITE);
+ check_access(M_WRITE);
+
+ if(pos==end)
+ return 0;
+
*pos++ = c;
return 1;
}
bool Memory::getline(string &line)
{
+ check_access(M_READ);
+
+ if(pos==end)
+ {
+ set_eof();
+ return false;
+ }
+
char *nl = find(pos, end, '\n');
line.assign(pos, nl);
- bool result = (nl!=pos);
- pos = nl;
- return result;
+ pos = (nl==end ? end : nl+1);
+ return true;
}
int Memory::get()
{
+ check_access(M_READ);
+
if(pos==end)
{
- eof_flag = true;
+ set_eof();
return -1;
}
return static_cast<unsigned char>(*pos++);
}
-unsigned Memory::seek(int off, SeekType type)
+const Handle &Memory::get_handle(Mode)
+{
+ throw logic_error("Memory::get_handle");
+}
+
+SeekOffset Memory::seek(SeekOffset off, SeekType type)
{
char *new_pos;
if(type==S_BEG)
else if(type==S_END)
new_pos = end+off;
else
- throw InvalidParameterValue("Invalid seek type");
+ throw invalid_argument("Memory::seek");
if(new_pos<begin || new_pos>end)
- throw InvalidParameterValue("Invalid seek offset");
+ throw bad_seek(off, type);
pos = new_pos;
+ eof_flag = false;
return pos-begin;
}
-Handle Memory::get_event_handle()
-{
- throw Exception("Memory doesn't support events");
-}
-
-void Memory::check_mode(Mode m) const
-{
- if(m==M_WRITE)
- {
- if(!(mode&M_WRITE))
- throw InvalidState("Memory is not writable");
- if(pos==end)
- throw InvalidState("Attempt to write past end of Memory");
- }
-}
-
} // namespace IO
} // namespace Msp