libcryfs/test/testutils/DataBlockFixture.cpp

86 lines
2.3 KiB
C++
Raw Normal View History

2015-02-17 00:48:49 +01:00
#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;
}
//Fill remaining bytes
for(size_t i=(_size/sizeof(long long int))*sizeof(long long int); i<_size; ++i) {
val *= 6364136223846793005L;
val += 1442695040888963407;
reinterpret_cast<char*>(_fileData)[i] = val;
}
}
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);
}