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
|
//
// C++ Implementation: datainputstream
//
// Description:
//
//
// Author: Rikard Bjorklind <olof@linux.nu>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "datainputstream.h"
#include <netinet/in.h>
#include "rpcexception.h"
#include <boost/scoped_array.hpp>
using std::string;
namespace rpc
{
DataInputStream::DataInputStream( CmdInputBufferPtr buf ) : data( buf )
{
}
int DataInputStream::readInt()
{
checkRead( 4 );
int i = *(reinterpret_cast<int*>(data->curPtr()));
i = ntohl(i);
data->advance( 4 );
return i;
}
char DataInputStream::readByte()
{
checkRead( 1 );
char ch = *(data->curPtr());
data->advance( 1 );
return ch;
}
short DataInputStream::readShort()
{
checkRead( 2 );
short s = *(reinterpret_cast<short*>(data->curPtr()));
s = ntohs(s);
data->advance( 2 );
return s;
}
bool DataInputStream::readBool()
{
checkRead( 1 );
char ch = *(data->curPtr());
data->advance( 1 );
return ch!=0;
}
int64 DataInputStream::readLong()
{
checkRead( 8 );
uint32_t l1 = *(reinterpret_cast<uint32_t*>(data->curPtr()));
data->advance( 4 );
uint32_t l2 = *(reinterpret_cast<uint32_t*>(data->curPtr()));
data->advance( 4 );
l1 = ntohl(l1);
l2 = ntohl(l2);
int64 l = ((int64)l1<<32)+l2;
return l;
}
string DataInputStream::readUTF()
{
// one int for length, rest is the string
int length = readInt();
checkRead( length );
// Allocate space for string
boost::scoped_array<char> str( new char[length+1] );
// Copy date from buffer
memcpy( str.get(), data->curPtr(), length );
// Null-terminate
str.get()[length] = '\0';
// Create string to return
string ret = str.get();
// Advance the buffer past the string
data->advance( length );
return ret;
}
DataInputStream::~DataInputStream()
{}
void DataInputStream::checkRead( int i )
{
if(data->remaining() < i) throw RpcException( "EndOfStream" );
}
}
|