libcryfs/test/testutils/DataBlockFixture.cpp

88 lines
2.4 KiB
C++
Raw Normal View History

#include "DataBlockFixture.h"
#include <algorithm>
#include <cstring>
using std::min;
DataBlockFixture::DataBlockFixture(size_t size, long long int IV): _fileData(new char[size]), _size(size) {
2014-11-27 16:40:22 +01:00
fillFileWithRandomData(IV);
}
DataBlockFixture::~DataBlockFixture() {
delete[] _fileData;
}
void DataBlockFixture::fillFileWithRandomData(long long int IV) {
2014-11-27 16:40:22 +01:00
long long int val = IV;
for(size_t i=0; i<_size/sizeof(long long int); ++i) {
//MMIX linear congruential generator
val *= 6364136223846793005L;
val += 1442695040888963407;
reinterpret_cast<long long int*>(_fileData)[i] = val;
}
uint64_t alreadyWritten = (_size/sizeof(long long int))*sizeof(long long int);
val *= 6364136223846793005L;
val += 1442695040888963407;
char *remainingBytes = reinterpret_cast<char*>(&val);
//Fill remaining bytes
for(size_t i=0; i<_size-alreadyWritten; ++i) {
reinterpret_cast<char*>(_fileData)[alreadyWritten + i] = remainingBytes[i];
}
}
const char *DataBlockFixture::data() const {
2014-11-27 16:40:22 +01:00
return _fileData;
}
int DataBlockFixture::read(void *buf, size_t count, off_t offset) {
size_t realCount = min(count, _size - offset);
memcpy(buf, _fileData+offset, realCount);
return realCount;
}
size_t DataBlockFixture::size() const {
2014-11-27 16:40:22 +01:00
return _size;
}
bool DataBlockFixture::fileContentEqual(const char *content, size_t count, off_t offset) {
return 0 == memcmp(content, _fileData + offset, count);
}
DataBlockFixtureWriteable::DataBlockFixtureWriteable(size_t size, long long int IV)
:DataBlockFixture(size, IV), _originalSize(size) {
2014-11-27 16:40:22 +01:00
_originalFileData = new char[size];
memcpy(_originalFileData, _fileData, size);
}
DataBlockFixtureWriteable::~DataBlockFixtureWriteable() {
2014-11-27 16:40:22 +01:00
delete[] _originalFileData;
}
void DataBlockFixtureWriteable::write(const void *buf, size_t count, off_t offset) {
2014-11-27 16:40:22 +01:00
extendFileSizeIfNecessary(count + offset);
memcpy(_fileData+offset, buf, count);
}
void DataBlockFixtureWriteable::extendFileSizeIfNecessary(size_t size) {
2014-11-27 16:40:22 +01:00
if (size > _size) {
extendFileSize(size);
}
}
void DataBlockFixtureWriteable::extendFileSize(size_t size) {
2014-11-27 16:40:22 +01:00
char *newfile = new char[size];
memcpy(newfile, _fileData, _size);
delete[] _fileData;
_fileData = newfile;
_size = size;
}
bool DataBlockFixtureWriteable::sizeUnchanged() {
2014-11-27 16:40:22 +01:00
return _size == _originalSize;
}
bool DataBlockFixtureWriteable::regionUnchanged(off_t offset, size_t count) {
2014-11-27 16:40:22 +01:00
return 0 == memcmp(_fileData+offset, _originalFileData+offset, count);
}