XorOutputStream.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  * XorOutputStream.h
8  *
9  * @author Slavey Karadzhov <slaff@attachix.com>
10  *
11  ****/
12 
13 #pragma once
14 
16 
22 {
23 public:
30  XorOutputStream(IDataSourceStream* stream, uint8_t* mask, size_t maskLength)
31  : stream(stream), mask(new uint8_t[maskLength]), maskLength(maskLength)
32  {
33  memcpy(this->mask.get(), mask, maskLength);
34  }
35 
36  StreamType getStreamType() const override
37  {
38  return eSST_Transform;
39  }
40 
41  int available() override
42  {
43  return stream->available();
44  }
45 
46  uint16_t readMemoryBlock(char* data, int bufSize) override
47  {
48  uint16_t max = stream->readMemoryBlock(data, bufSize);
49  size_t pos = maskPos;
50  for(unsigned i = 0; i < max; i++) {
51  pos = pos % maskLength;
52  data[i] = (data[i] ^ mask[pos]);
53  pos++;
54  }
55 
56  return max;
57  }
58 
59  bool seek(int len) override
60  {
61  if(!stream->seek(len)) {
62  return false;
63  }
64 
65  maskPos = (maskPos + len) % maskLength;
66  return true;
67  }
68 
69  bool isFinished() override
70  {
71  return stream->isFinished();
72  }
73 
74 private:
75  std::unique_ptr<IDataSourceStream> stream;
76  std::unique_ptr<uint8_t[]> mask;
77  size_t maskLength;
78  size_t maskPos = 0;
79 };
Base class for read-only stream.
Definition: DataSourceStream.h:46
Xors original stream content with the specified mask.
Definition: XorOutputStream.h:22
StreamType getStreamType() const override
Get the stream type.
Definition: XorOutputStream.h:36
bool isFinished() override
Check if all data has been read.
Definition: XorOutputStream.h:69
int available() override
Return the total length of the stream.
Definition: XorOutputStream.h:41
uint16_t readMemoryBlock(char *data, int bufSize) override
Read a block of memory.
Definition: XorOutputStream.h:46
XorOutputStream(IDataSourceStream *stream, uint8_t *mask, size_t maskLength)
Constructor.
Definition: XorOutputStream.h:30
bool seek(int len) override
Move read cursor.
Definition: XorOutputStream.h:59
StreamType
Data stream type.
Definition: DataSourceStream.h:25
@ eSST_Transform
A stream that is transforming the data.
Definition: DataSourceStream.h:35