summaryrefslogtreecommitdiff
path: root/cache.cpp
blob: 92e0cfaa57ec2ccd2d270e8e36c149f66de274fc (plain)
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
#include "cache.h"
#include "config.h"

#include <boost/format.hpp>
#include <boost/filesystem/fstream.hpp>
#include <openssl/sha.h>

#include <iostream>
#include <stdexcept>

EncodedCache::EncodedCache(fs::path path, Decoder::p decoder, Encoder::p encoder) {
	this->decoder = decoder;
	this->encoder = encoder;

	// TODO: Differentiate between encoders?
	SHA_CTX context;
	unsigned char md[SHA_DIGEST_LENGTH];
	SHA_Init(&context);
	SHA_Update(&context, (unsigned char*)path.string().c_str(), path.string().length());
	SHA_Final(md, &context);
	for(int i = 0; i < SHA_DIGEST_LENGTH; i++) {
		hash = hash + (boost::format("%02x") % (int)md[i]).str();
	}
}

fs::path EncodedCache::get_path() {
	return fs::path(config::vm["audist.cache_dir"].as<std::string>()) / hash;
}

void EncodedCache::create_cache() {
	fs::path path = get_path();

	// TODO: Locking?
	fs::ofstream os(path, std::ios::out | std::ios::binary);
	// TODO: Make an encoder-to-istream adapter to get rid of this:

	if(!os.is_open())
		throw std::runtime_error("failed to create cache object");
	char data[0x10000];
	std::streamsize size = 1;
	while(size) {
		size = encoder->read(data, 0x10000);
		if(size > 0)
			os.write(data, size);
	}
	os.close();
}