1 /*
2  * Copyright (C) 2020 Veloman Yunkan
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * is provided AS IS, WITHOUT ANY WARRANTY; without even the implied
11  * warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, and
12  * NON-INFRINGEMENT.  See the GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  */
19 
20 #ifndef ZIM_BUFFERSTREAMER_H
21 #define ZIM_BUFFERSTREAMER_H
22 
23 #include "debug.h"
24 
25 #include <string.h>
26 
27 namespace zim
28 {
29 
30 class BufferStreamer
31 {
32 public: // functions
BufferStreamer(const Buffer & buffer,zsize_t size)33   BufferStreamer(const Buffer& buffer, zsize_t size)
34     : m_buffer(buffer),
35       m_current(buffer.data()),
36       m_size(size)
37   {}
38 
BufferStreamer(const Buffer & buffer)39   explicit BufferStreamer(const Buffer& buffer)
40     : BufferStreamer(buffer, buffer.size())
41   {}
42 
43   // Reads a value of the said type from the stream
44   //
45   // For best portability this function should be used with types of known
46   // bit-width (int32_t, uint16_t, etc) rather than builtin types with
47   // unknown bit-width (int, unsigned, etc).
read()48   template<typename T> T read()
49   {
50     const size_t N(sizeof(T));
51     char buf[N];
52     memcpy(buf, m_current, N);
53     skip(zsize_t(N));
54     return fromLittleEndian<T>(buf); // XXX: This handles only integral types
55   }
56 
current()57   const char* current() const {
58     return m_current;
59   }
60 
left()61   zsize_t left() const {
62     return m_size;
63   }
64 
skip(zsize_t nbBytes)65   void skip(zsize_t nbBytes) {
66     m_current += nbBytes.v;
67     m_size -= nbBytes;
68   }
69 
70 private: // data
71   const Buffer m_buffer;
72   const char* m_current;
73   zsize_t m_size;
74 };
75 
76 } // namespace zim
77 
78 #endif // ZIM_BUFDATASTREAM_H
79