forked from cryfs/cryfs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathData.cpp
More file actions
72 lines (60 loc) · 1.72 KB
/
Copy pathData.cpp
File metadata and controls
72 lines (60 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Data.h"
#include <stdexcept>
#include <vendor_cryptopp/hex.h>
using std::istream;
using std::ofstream;
using std::ifstream;
using std::ios;
using boost::optional;
namespace bf = boost::filesystem;
namespace cpputils {
optional<Data> Data::LoadFromFile(const bf::path &filepath) {
ifstream file(filepath.string().c_str(), ios::binary);
if (!file.good()) {
return boost::none;
}
optional<Data> result(LoadFromStream(file));
if (!file.good()) {
throw std::runtime_error("Error reading from file");
}
return result;
}
std::streampos Data::_getStreamSize(istream &stream) {
auto current_pos = stream.tellg();
//Retrieve length
stream.seekg(0, stream.end);
auto endpos = stream.tellg();
//Restore old position
stream.seekg(current_pos, stream.beg);
return endpos - current_pos;
}
Data Data::LoadFromStream(istream &stream, size_t size) {
Data result(size);
stream.read(static_cast<char*>(result.data()), result.size());
return result;
}
Data Data::FromString(const std::string &data, unique_ref<Allocator> allocator) {
ASSERT(data.size() % 2 == 0, "hex encoded data cannot have odd number of characters");
Data result(data.size() / 2, std::move(allocator));
{
CryptoPP::StringSource _1(data, true,
new CryptoPP::HexDecoder(
new CryptoPP::ArraySink(static_cast<CryptoPP::byte*>(result._data), result.size())
)
);
}
return result;
}
std::string Data::ToString() const {
std::string result;
{
CryptoPP::ArraySource _1(static_cast<const CryptoPP::byte*>(_data), _size, true,
new CryptoPP::HexEncoder(
new CryptoPP::StringSink(result)
)
);
}
ASSERT(result.size() == 2 * _size, "Created wrongly sized string");
return result;
}
}