1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
|
/*
* libopenraw - memstream.cpp
*
* Copyright (C) 2007-2008 Hubert Figuière
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <libopenraw/libopenraw.h>
#include "memstream.h"
#include "debug.h"
using namespace Debug;
namespace OpenRaw {
namespace IO {
MemStream::MemStream(void *ptr, size_t s)
: Stream(""),
m_ptr(ptr),
m_size(s),
m_current(NULL)
{
}
or_error MemStream::open()
{
m_current = (unsigned char *)m_ptr;
return OR_ERROR_NONE;
}
int MemStream::close()
{
m_current = NULL;
return 0;
}
int MemStream::seek(off_t offset, int whence)
{
int newpos = 0;
// Trace(DEBUG1) << "MemStream::seek " << offset
// << " bytes - whence = "
// << whence << "\n";
// TODO check bounds
if (m_current == NULL) {
// TODO set error code
return -1;
}
switch(whence)
{
case SEEK_SET:
m_current = (unsigned char*)m_ptr + offset;
newpos = offset;
break;
case SEEK_END:
m_current = (unsigned char*)m_ptr + m_size + offset;
newpos = m_size + offset;
break;
case SEEK_CUR:
m_current += offset;
newpos = (m_current - (unsigned char*)m_ptr);
break;
default:
return -1;
break;
}
return newpos;
}
int MemStream::read(void *buf, size_t count)
{
if((m_current == NULL) || (m_ptr == NULL)) {
Trace(DEBUG1) << "MemStream::failed\n";
return -1;
}
unsigned char * end = (unsigned char*)m_ptr + m_size;
if((off_t)count > (end - m_current)) {
count = end - m_current;
// TODO set EOF
}
memcpy(buf, m_current, count);
m_current += count;
return count;
}
off_t MemStream::filesize()
{
return m_size;
}
}
}
|