summaryrefslogtreecommitdiff
path: root/decoder.h
blob: d58dcf1cc4bc55b5f95dc2247171c7f5c5b36d2f (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
#ifndef DECODER_H
#define DECODER_H

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

#include <string>

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

//! Input filter to hold a decoder in a filter chain.
class DecoderFilter : public boost::iostreams::multichar_input_filter {
	private:
		DecoderBase::p decoder;
		
		//! 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<DecoderFilter> p;
		DecoderFilter(DecoderBase::p decoder_);
		
		template<typename Source>
		std::streamsize read(Source& src, char *s, std::streamsize n) {
			return decoder->decode(ReadFunc<Source>(src), (uint8_t*)s, n);
		}
};

namespace decoder {
	void init();
	DecoderFilter::p get_decoder(const std::string& name);
};

#endif