Reader.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include "Reader.h"
  2. #include "Text.h"
  3. using namespace Framework;
  4. //! \param buffer The buffer to be read
  5. //! \param length The length of the buffer
  6. //! \param deleteBuffer true if the buffer should be automatically deleted
  7. //! with delete[]
  8. ByteArrayReader::ByteArrayReader(
  9. const char* buffer, int length, bool deleteBuffer)
  10. : ReferenceCounter(),
  11. length(length),
  12. buffer(buffer),
  13. deleteBuffer(deleteBuffer),
  14. position(0)
  15. {}
  16. ByteArrayReader::~ByteArrayReader()
  17. {
  18. if (deleteBuffer) delete[] buffer;
  19. }
  20. //! Reads from the resource
  21. //! \param bytes An array to be filled with bytes from the resource
  22. //! \param len How many bytes should be read from the resource
  23. void ByteArrayReader::read(char* bytes, int len)
  24. {
  25. if (position < length)
  26. memcpy(bytes, buffer + position, min(len, length - position));
  27. position = min(position + len, length);
  28. }
  29. //! Reads the next line of the resource
  30. //! \return The read line as Text with line break
  31. Text* ByteArrayReader::readLine()
  32. {
  33. if (position >= length) return 0;
  34. int start = position;
  35. for (; buffer[position] != '\n' && position < length; position++)
  36. ;
  37. Text* ret = new Text("");
  38. ret->fillText('\0', position - start + 1);
  39. read((char*)ret->getText(), position - start + 1);
  40. return ret;
  41. }
  42. //! Checks whether the resource has been fully read
  43. //! return 1 if the resource has been fully read. 0 otherwise
  44. bool ByteArrayReader::isEnd() const
  45. {
  46. return position >= length;
  47. }
  48. //! Sets the position of the byte to be read next
  49. //! \param pos The index of the byte
  50. //! \param ende 1 if the index counts from the end of the resource. 0 if the index
  51. //! counts from the beginning of the resource
  52. void ByteArrayReader::setLPosition(__int64 pos, bool ende)
  53. {
  54. position = ende ? max(length - (int)pos, 0) : min((int)pos, length);
  55. }
  56. //! Returns the index of the byte from the resource that would be read next
  57. //! return -1 if an error occurred. Otherwise the position of the read pointer
  58. __int64 ByteArrayReader::getLPosition() const
  59. {
  60. return position;
  61. }
  62. //! Returns the number of bytes to be read
  63. __int64 ByteArrayReader::getSize() const
  64. {
  65. return length;
  66. }