Botan  1.11.15
src/lib/compression/compress_utils.h
Go to the documentation of this file.
00001 /*
00002 * Compression utility header
00003 * (C) 2014 Jack Lloyd
00004 *
00005 * Botan is released under the Simplified BSD License (see license.txt)
00006 */
00007 
00008 #ifndef BOTAN_COMPRESSION_UTILS_H__
00009 #define BOTAN_COMPRESSION_UTILS_H__
00010 
00011 #include <botan/compression.h>
00012 #include <botan/internal/algo_registry.h>
00013 #include <memory>
00014 #include <unordered_map>
00015 
00016 namespace Botan {
00017 
00018 /*
00019 * Allocation Size Tracking Helper for Zlib/Bzlib/LZMA
00020 */
00021 class Compression_Alloc_Info
00022    {
00023    public:
00024       template<typename T>
00025       static void* malloc(void* self, T n, T size)
00026          {
00027          return static_cast<Compression_Alloc_Info*>(self)->do_malloc(n, size);
00028          }
00029 
00030       static void free(void* self, void* ptr)
00031          {
00032          static_cast<Compression_Alloc_Info*>(self)->do_free(ptr);
00033          }
00034 
00035    private:
00036       void* do_malloc(size_t n, size_t size);
00037       void do_free(void* ptr);
00038 
00039       std::unordered_map<void*, size_t> m_current_allocs;
00040    };
00041 
00042 /**
00043 * Wrapper for Zlib/Bzlib/LZMA stream types
00044 */
00045 template<typename Stream, typename ByteType>
00046 class Zlib_Style_Stream : public Compression_Stream
00047    {
00048    public:
00049       void next_in(byte* b, size_t len) override
00050          {
00051          m_stream.next_in = reinterpret_cast<ByteType*>(b);
00052          m_stream.avail_in = len;
00053          }
00054 
00055       void next_out(byte* b, size_t len) override
00056          {
00057          m_stream.next_out = reinterpret_cast<ByteType*>(b);
00058          m_stream.avail_out = len;
00059          }
00060 
00061       size_t avail_in() const override { return m_stream.avail_in; }
00062 
00063       size_t avail_out() const override { return m_stream.avail_out; }
00064 
00065       Zlib_Style_Stream()
00066          {
00067          clear_mem(&m_stream, 1);
00068          m_allocs.reset(new Compression_Alloc_Info);
00069          }
00070 
00071       ~Zlib_Style_Stream()
00072          {
00073          clear_mem(&m_stream, 1);
00074          m_allocs.reset();
00075          }
00076 
00077    protected:
00078       typedef Stream stream_t;
00079 
00080       stream_t* streamp() { return &m_stream; }
00081 
00082       Compression_Alloc_Info* alloc() { return m_allocs.get(); }
00083    private:
00084       stream_t m_stream;
00085       std::unique_ptr<Compression_Alloc_Info> m_allocs;
00086    };
00087 
00088 #define BOTAN_REGISTER_COMPRESSION(C, D) \
00089    BOTAN_REGISTER_T_1LEN(Transform, C, 9) \
00090    BOTAN_REGISTER_T_NOARGS(Transform, D)
00091 
00092 }
00093 
00094 #endif