StreamBuffer.h
Go to the documentation of this file.
1 /****
2  * Sming Framework Project - Open Source framework for high efficiency native ESP8266 development.
3  * Created 2015 by Skurydin Alexey
4  * http://github.com/SmingHub/Sming
5  * All files of the Sming Core are provided under the LGPL v3 license.
6  *
7  * StreamBuffer.h - Buffering for more efficient reading of byte streams
8  *
9  * @author Sept 2019 mikee47 <mike@sillyhouse.net>
10  *
11  ****/
12 
13 #pragma once
14 
16 #include <memory>
17 
18 template <unsigned bufSize> class StreamBuffer
19 {
20 public:
21  void setStream(IDataSourceStream* stream)
22  {
23  this->stream.reset(stream);
24  if(stream == nullptr) {
25  streamPos = 0;
26  pos = len = 0;
27  } else {
28  streamPos = stream->seekFrom(0, SeekOrigin::Current);
29  fill();
30  }
31  }
32 
33  bool setPos(unsigned pos)
34  {
35  if(!stream) {
36  return false;
37  }
38 
39  if(stream->seekFrom(pos, SeekOrigin::Start) < 0) {
40  return false;
41  }
42 
43  streamPos = pos;
44  fill();
45  return !eof();
46  }
47 
48  char peekChar()
49  {
50  return (pos < len) ? data[pos] : '\0';
51  };
52 
53  char readChar()
54  {
55  char c = data[pos++];
56  if(pos >= len) {
57  fill();
58  }
59  return c;
60  };
61 
62  unsigned getPos()
63  {
64  return streamPos - len + pos;
65  }
66 
67  bool eof()
68  {
69  return len == 0;
70  }
71 
72 private:
73  void fill()
74  {
75  len = stream->readMemoryBlock(data, sizeof(data));
76  stream->seek(len);
77  streamPos += len;
78  pos = 0;
79  };
80 
81 private:
82  std::unique_ptr<IDataSourceStream> stream;
83  unsigned streamPos = 0;
84  char data[bufSize];
85  uint8_t pos = 0;
86  uint8_t len = 0;
87 };
Base class for read-only stream.
Definition: DataSourceStream.h:45
Definition: StreamBuffer.h:18
char peekChar()
Definition: StreamBuffer.h:58
bool eof()
Definition: StreamBuffer.h:77
@ Current
SEEK_CUR: Current position in file.
virtual uint16_t readMemoryBlock(char *data, int bufSize)=0
Read a block of memory.
unsigned getPos()
Definition: StreamBuffer.h:72
char readChar()
Definition: StreamBuffer.h:63
virtual int seekFrom(int offset, SeekOrigin origin)
Change position in stream.
Definition: DataSourceStream.h:97
virtual bool seek(int len)
Move read cursor.
Definition: DataSourceStream.h:106
void setStream(IDataSourceStream *stream)
Definition: StreamBuffer.h:31
@ Start
SEEK_SET: Start of file.
bool setPos(unsigned pos)
Definition: StreamBuffer.h:43