CInputStream.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * CInputStream.h, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #pragma once
  11. #include "CStream.h"
  12. #include <boost/crc.hpp>
  13. VCMI_LIB_NAMESPACE_BEGIN
  14. /**
  15. * Abstract class which provides method definitions for reading from a stream.
  16. */
  17. class DLL_LINKAGE CInputStream : public virtual CStream
  18. {
  19. public:
  20. /**
  21. * Reads n bytes from the stream into the data buffer.
  22. *
  23. * @param data A pointer to the destination data array.
  24. * @param size The number of bytes to read.
  25. * @return the number of bytes read actually.
  26. */
  27. virtual si64 read(ui8 * data, si64 size) = 0;
  28. /**
  29. * @brief for convenience, reads whole stream at once
  30. *
  31. * @return pair, first = raw data, second = size of data
  32. */
  33. std::pair<std::unique_ptr<ui8[]>, si64> readAll()
  34. {
  35. std::unique_ptr<ui8[]> data(new ui8[getSize()]);
  36. seek(0);
  37. [[maybe_unused]] auto readSize = read(data.get(), getSize());
  38. assert(readSize == getSize());
  39. return std::make_pair(std::move(data), getSize());
  40. }
  41. /**
  42. * @brief calculateCRC32 calculates CRC32 checksum for the whole file
  43. * @return calculated checksum
  44. */
  45. virtual ui32 calculateCRC32()
  46. {
  47. si64 originalPos = tell();
  48. boost::crc_32_type checksum;
  49. auto data = readAll();
  50. checksum.process_bytes(reinterpret_cast<const void *>(data.first.get()), data.second);
  51. seek(originalPos);
  52. return checksum.checksum();
  53. }
  54. };
  55. VCMI_LIB_NAMESPACE_END