libcryfs/random/RandomGeneratorThread.cpp

34 lines
1.2 KiB
C++
Raw Normal View History

#include "RandomGeneratorThread.h"
namespace cpputils {
RandomGeneratorThread::RandomGeneratorThread(ThreadsafeRandomDataBuffer *buffer, size_t minSize, size_t maxSize)
2015-10-28 15:00:24 +01:00
: _randomGenerator(),
_buffer(buffer),
_minSize(minSize),
_maxSize(maxSize),
_thread(std::bind(&RandomGeneratorThread::_loopIteration, this)) {
ASSERT(_maxSize >= _minSize, "Invalid parameters");
}
2015-10-28 15:00:24 +01:00
void RandomGeneratorThread::start() {
return _thread.start();
}
bool RandomGeneratorThread::_loopIteration() {
_buffer->waitUntilSizeIsLessThan(_minSize);
size_t neededRandomDataSize = _maxSize - _buffer->size();
ASSERT(_maxSize > _buffer->size(), "This could theoretically fail if another thread refilled the buffer. But we should be the only refilling thread.");
Data randomData = _generateRandomData(neededRandomDataSize);
_buffer->add(std::move(randomData));
return true; // Run another iteration (don't terminate thread)
}
Data RandomGeneratorThread::_generateRandomData(size_t size) {
Data newRandom(size);
_randomGenerator.GenerateBlock(static_cast<byte*>(newRandom.data()), size);
return newRandom;
}
2015-10-16 03:17:50 +02:00
}