crn_data_stream.cpp 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. // File: crn_data_stream.cpp
  2. // See Copyright Notice and license at the end of inc/crnlib.h
  3. #include "crn_core.h"
  4. #include "crn_data_stream.h"
  5. namespace crnlib
  6. {
  7. data_stream::data_stream() :
  8. m_attribs(0),
  9. m_opened(false), m_error(false), m_got_cr(false)
  10. {
  11. }
  12. data_stream::data_stream(const char* pName, uint attribs) :
  13. m_name(pName),
  14. m_attribs(static_cast<uint16>(attribs)),
  15. m_opened(false), m_error(false), m_got_cr(false)
  16. {
  17. }
  18. uint64 data_stream::skip(uint64 len)
  19. {
  20. uint64 total_bytes_read = 0;
  21. const uint cBufSize = 1024;
  22. uint8 buf[cBufSize];
  23. while (len)
  24. {
  25. const uint64 bytes_to_read = math::minimum<uint64>(sizeof(buf), len);
  26. const uint64 bytes_read = read(buf, static_cast<uint>(bytes_to_read));
  27. total_bytes_read += bytes_read;
  28. if (bytes_read != bytes_to_read)
  29. break;
  30. len -= bytes_read;
  31. }
  32. return total_bytes_read;
  33. }
  34. bool data_stream::read_line(dynamic_string& str)
  35. {
  36. str.empty();
  37. for ( ; ; )
  38. {
  39. const int c = read_byte();
  40. const bool prev_got_cr = m_got_cr;
  41. m_got_cr = false;
  42. if (c < 0)
  43. {
  44. if (!str.is_empty())
  45. break;
  46. return false;
  47. }
  48. else if ((26 == c) || (!c))
  49. continue;
  50. else if (13 == c)
  51. {
  52. m_got_cr = true;
  53. break;
  54. }
  55. else if (10 == c)
  56. {
  57. if (prev_got_cr)
  58. continue;
  59. break;
  60. }
  61. str.append_char(static_cast<char>(c));
  62. }
  63. return true;
  64. }
  65. bool data_stream::printf(const char* p, ...)
  66. {
  67. va_list args;
  68. va_start(args, p);
  69. dynamic_string buf;
  70. buf.format_args(p, args);
  71. va_end(args);
  72. return write(buf.get_ptr(), buf.get_len() * sizeof(char)) == buf.get_len() * sizeof(char);
  73. }
  74. bool data_stream::write_line(const dynamic_string& str)
  75. {
  76. if (!str.is_empty())
  77. return write(str.get_ptr(), str.get_len()) == str.get_len();
  78. return true;
  79. }
  80. bool data_stream::read_array(vector<uint8>& buf)
  81. {
  82. if (buf.size() < get_remaining())
  83. {
  84. if (get_remaining() > 1024U*1024U*1024U)
  85. return false;
  86. buf.resize((uint)get_remaining());
  87. }
  88. if (!get_remaining())
  89. {
  90. buf.resize(0);
  91. return true;
  92. }
  93. return read(&buf[0], buf.size()) == buf.size();
  94. }
  95. bool data_stream::write_array(const vector<uint8>& buf)
  96. {
  97. if (!buf.empty())
  98. return write(&buf[0], buf.size()) == buf.size();
  99. return true;
  100. }
  101. } // namespace crnlib