summaryrefslogtreecommitdiff
path: root/encoder.h
blob: d000ffc8fd441181c8b00427b1b88330ece440e7 (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
48
49
50
51
52
53
54
55
56
57
#ifndef ENCODER_H
#define ENCODER_H

#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/operations.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>

#include <iostream>
#include <string>

class EncoderBase {
	friend class EncoderFilter;
	
	protected:
		typedef boost::function<std::size_t (char*, std::size_t)> ReadFunc;
		
		virtual size_t encode(ReadFunc read, uint8_t *output, size_t output_size) = 0;
		
	public:
		typedef boost::shared_ptr<EncoderBase> p;
		virtual ~EncoderBase() {}
};

//! Input filter to hold an encoder in a filter chain.
class EncoderFilter : public boost::iostreams::multichar_input_filter {
	private:
		EncoderBase::p encoder;
		
		//! Functor binding a source to a read function.
		template<class T>
		struct ReadFunc {
			T& s;
			
			ReadFunc(T& s_) : s(s_) {}
			
			std::size_t operator()(char* buf, std::size_t buf_size) {
				return boost::iostreams::read(s, buf, buf_size);
			}
		};
	
	public:
		typedef boost::shared_ptr<EncoderFilter> p;
		EncoderFilter(EncoderBase::p encoder_);
		
		template<typename Source>
		std::streamsize read(Source& src, char *s, std::streamsize n) {
			return encoder->encode(ReadFunc<Source>(src), (uint8_t*)s, n);
		};
};

namespace encoder {
	void init();
	EncoderFilter::p get_encoder(const std::string& name);
};

#endif