BaseContainer.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright (c) Kuba Szczodrzyński 2022-1-7.
  2. #include "BaseContainer.h"
  3. void BaseContainer::feed(const std::shared_ptr<bell::ByteStream> &stream, uint32_t position) {
  4. this->reader = std::make_unique<bell::BinaryReader>(stream);
  5. this->source = stream;
  6. this->pos = position;
  7. }
  8. // TODO move source stream reading here, and set closed = true when stream ends
  9. uint8_t BaseContainer::readUint8() {
  10. pos += 1;
  11. return reader->readByte();
  12. }
  13. uint16_t BaseContainer::readUint16() {
  14. pos += 2;
  15. return reader->readShort();
  16. }
  17. uint32_t BaseContainer::readUint24() {
  18. uint8_t b[3];
  19. readBytes(b, 3);
  20. return static_cast<int32_t>((b[2]) | (b[1] << 8) | (b[0] << 16));
  21. }
  22. uint32_t BaseContainer::readUint32() {
  23. pos += 4;
  24. return reader->readUInt();
  25. }
  26. uint64_t BaseContainer::readUint64() {
  27. pos += 8;
  28. return reader->readLong();
  29. }
  30. uint32_t BaseContainer::readVarint32() {
  31. uint8_t b = readUint8();
  32. uint32_t result = b & 0x7f;
  33. while (b & 0b10000000) {
  34. b = readUint8();
  35. result <<= 7;
  36. result |= b & 0x7f;
  37. }
  38. return result;
  39. }
  40. uint32_t BaseContainer::readBytes(uint8_t *dst, uint32_t num) {
  41. if (!num)
  42. return 0;
  43. uint32_t len, total = 0;
  44. do {
  45. if (dst) {
  46. len = source->read(dst, num);
  47. dst += len; // increment destination pointer
  48. } else {
  49. len = source->skip(num);
  50. }
  51. total += len; // increment total read count
  52. pos += len; // increment absolute source position
  53. num -= len; // decrement bytes left to read
  54. } while (len && num);
  55. if (!len) // source->read() returned 0, it's closed
  56. closed = true;
  57. return len;
  58. }
  59. uint32_t BaseContainer::skipBytes(uint32_t num) {
  60. return readBytes(nullptr, num);
  61. }
  62. uint32_t BaseContainer::skipTo(uint32_t offset) {
  63. if (offset <= pos)
  64. return 0;
  65. return readBytes(nullptr, offset - pos);
  66. }