1
0
mirror of https://github.com/danog/libtgvoip.git synced 2024-12-02 17:51:06 +01:00
libtgvoip/BufferOutputStream.cpp

87 lines
2.1 KiB
C++
Raw Normal View History

2017-02-02 17:24:40 +01:00
//
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#include "BufferOutputStream.h"
#include <string.h>
using namespace tgvoip;
BufferOutputStream::BufferOutputStream(size_t size){
2017-03-30 16:06:59 +02:00
buffer=(unsigned char*) malloc(size);
2017-02-02 17:24:40 +01:00
offset=0;
this->size=size;
}
BufferOutputStream::~BufferOutputStream(){
2017-02-02 17:24:40 +01:00
free(buffer);
}
void BufferOutputStream::WriteByte(unsigned char byte){
2017-02-02 17:24:40 +01:00
this->ExpandBufferIfNeeded(1);
buffer[offset++]=byte;
}
void BufferOutputStream::WriteInt32(int32_t i){
2017-02-02 17:24:40 +01:00
this->ExpandBufferIfNeeded(4);
2017-03-30 16:06:59 +02:00
buffer[offset+3]=(unsigned char)((i >> 24) & 0xFF);
buffer[offset+2]=(unsigned char)((i >> 16) & 0xFF);
buffer[offset+1]=(unsigned char)((i >> 8) & 0xFF);
buffer[offset]=(unsigned char)(i & 0xFF);
2017-02-02 17:24:40 +01:00
offset+=4;
}
void BufferOutputStream::WriteInt64(int64_t i){
2017-02-02 17:24:40 +01:00
this->ExpandBufferIfNeeded(8);
2017-03-30 16:06:59 +02:00
buffer[offset+7]=(unsigned char)((i >> 56) & 0xFF);
buffer[offset+6]=(unsigned char)((i >> 48) & 0xFF);
buffer[offset+5]=(unsigned char)((i >> 40) & 0xFF);
buffer[offset+4]=(unsigned char)((i >> 32) & 0xFF);
buffer[offset+3]=(unsigned char)((i >> 24) & 0xFF);
buffer[offset+2]=(unsigned char)((i >> 16) & 0xFF);
buffer[offset+1]=(unsigned char)((i >> 8) & 0xFF);
buffer[offset]=(unsigned char)(i & 0xFF);
2017-02-02 17:24:40 +01:00
offset+=8;
}
void BufferOutputStream::WriteInt16(int16_t i){
2017-02-02 17:24:40 +01:00
this->ExpandBufferIfNeeded(2);
2017-03-30 16:06:59 +02:00
buffer[offset+1]=(unsigned char)((i >> 8) & 0xFF);
buffer[offset]=(unsigned char)(i & 0xFF);
2017-02-02 17:24:40 +01:00
offset+=2;
}
void BufferOutputStream::WriteBytes(unsigned char *bytes, size_t count){
2017-02-02 17:24:40 +01:00
this->ExpandBufferIfNeeded(count);
memcpy(buffer+offset, bytes, count);
offset+=count;
}
unsigned char *BufferOutputStream::GetBuffer(){
2017-02-02 17:24:40 +01:00
return buffer;
}
size_t BufferOutputStream::GetLength(){
2017-02-02 17:24:40 +01:00
return offset;
}
void BufferOutputStream::ExpandBufferIfNeeded(size_t need){
2017-02-02 17:24:40 +01:00
if(offset+need>size){
if(need<1024){
2017-03-30 16:06:59 +02:00
buffer=(unsigned char *) realloc(buffer, size+1024);
2017-02-02 17:24:40 +01:00
size+=1024;
}else{
2017-03-30 16:06:59 +02:00
buffer=(unsigned char *) realloc(buffer, size+need);
2017-02-02 17:24:40 +01:00
size+=need;
}
}
}
void BufferOutputStream::Reset(){
2017-02-02 17:24:40 +01:00
offset=0;
}