libcryfs/src/blockstore/implementations/ondisk/OnDiskBlock.cpp

88 lines
2.2 KiB
C++
Raw Normal View History

2014-12-09 17:19:59 +01:00
#include <blockstore/implementations/ondisk/FileAlreadyExistsException.h>
#include <blockstore/implementations/ondisk/OnDiskBlock.h>
#include <blockstore/implementations/ondisk/OnDiskBlockStore.h>
#include <blockstore/utils/FileDoesntExistException.h>
#include <cstring>
#include <fstream>
#include <boost/filesystem.hpp>
using std::unique_ptr;
using std::make_unique;
using std::istream;
using std::ostream;
using std::ifstream;
using std::ofstream;
using std::ios;
namespace bf = boost::filesystem;
namespace blockstore {
namespace ondisk {
2015-01-24 22:08:41 +01:00
OnDiskBlock::OnDiskBlock(const Key &key, const bf::path &filepath, size_t size)
: Block(key), _filepath(filepath), _data(size) {
2014-12-09 17:19:59 +01:00
}
2015-01-24 22:08:41 +01:00
OnDiskBlock::OnDiskBlock(const Key &key, const bf::path &filepath, Data &&data)
: Block(key), _filepath(filepath), _data(std::move(data)) {
2014-12-09 17:19:59 +01:00
}
OnDiskBlock::~OnDiskBlock() {
_storeToDisk();
}
void *OnDiskBlock::data() {
return _data.data();
}
const void *OnDiskBlock::data() const {
return _data.data();
}
size_t OnDiskBlock::size() const {
return _data.size();
}
2015-01-24 22:08:41 +01:00
unique_ptr<OnDiskBlock> OnDiskBlock::LoadFromDisk(const bf::path &rootdir, const Key &key) {
auto filepath = rootdir / key.ToString();
2014-12-09 17:19:59 +01:00
try {
//If it isn't a file, Data::LoadFromFile() would usually also crash. We still need this extra check
//upfront, because Data::LoadFromFile() doesn't crash if we give it the path of a directory
//instead the path of a file.
if(!bf::is_regular_file(filepath)) {
return nullptr;
}
Data data = Data::LoadFromFile(filepath);
2015-01-24 22:08:41 +01:00
return unique_ptr<OnDiskBlock>(new OnDiskBlock(key, filepath, std::move(data)));
2014-12-09 17:19:59 +01:00
} catch (const FileDoesntExistException &e) {
return nullptr;
}
}
2015-01-24 22:08:41 +01:00
unique_ptr<OnDiskBlock> OnDiskBlock::CreateOnDisk(const bf::path &rootdir, const Key &key, size_t size) {
auto filepath = rootdir / key.ToString();
2014-12-09 17:19:59 +01:00
if (bf::exists(filepath)) {
return nullptr;
}
2015-01-24 22:08:41 +01:00
auto block = unique_ptr<OnDiskBlock>(new OnDiskBlock(key, filepath, size));
2014-12-09 17:19:59 +01:00
block->_fillDataWithZeroes();
block->_storeToDisk();
return block;
}
void OnDiskBlock::_fillDataWithZeroes() {
_data.FillWithZeroes();
}
void OnDiskBlock::_storeToDisk() const {
_data.StoreToFile(_filepath);
}
void OnDiskBlock::flush() {
_storeToDisk();
}
}
}