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 "BufferPool.h"
|
|
|
|
#include "logging.h"
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <assert.h>
|
|
|
|
|
2017-04-28 13:17:56 +02:00
|
|
|
using namespace tgvoip;
|
|
|
|
|
|
|
|
BufferPool::BufferPool(unsigned int size, unsigned int count){
|
2017-02-02 17:24:40 +01:00
|
|
|
assert(count<=64);
|
|
|
|
init_mutex(mutex);
|
|
|
|
buffers[0]=(unsigned char*) malloc(size*count);
|
|
|
|
bufferCount=count;
|
|
|
|
int i;
|
|
|
|
for(i=1;i<count;i++){
|
|
|
|
buffers[i]=buffers[0]+i*size;
|
|
|
|
}
|
|
|
|
usedBuffers=0;
|
|
|
|
}
|
|
|
|
|
2017-04-28 13:17:56 +02:00
|
|
|
BufferPool::~BufferPool(){
|
2017-02-02 17:24:40 +01:00
|
|
|
free_mutex(mutex);
|
|
|
|
free(buffers[0]);
|
|
|
|
}
|
|
|
|
|
2017-04-28 13:17:56 +02:00
|
|
|
unsigned char* BufferPool::Get(){
|
2017-02-02 17:24:40 +01:00
|
|
|
lock_mutex(mutex);
|
|
|
|
int i;
|
|
|
|
for(i=0;i<bufferCount;i++){
|
|
|
|
if(!((usedBuffers >> i) & 1)){
|
|
|
|
usedBuffers|=(1LL << i);
|
|
|
|
unlock_mutex(mutex);
|
|
|
|
return buffers[i];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
unlock_mutex(mutex);
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
2017-04-28 13:17:56 +02:00
|
|
|
void BufferPool::Reuse(unsigned char* buffer){
|
2017-02-02 17:24:40 +01:00
|
|
|
lock_mutex(mutex);
|
|
|
|
int i;
|
|
|
|
for(i=0;i<bufferCount;i++){
|
|
|
|
if(buffers[i]==buffer){
|
|
|
|
usedBuffers&= ~(1LL << i);
|
|
|
|
unlock_mutex(mutex);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
LOGE("pointer passed isn't a valid buffer from this pool");
|
|
|
|
abort();
|
|
|
|
}
|
|
|
|
|