stream.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. Minetest
  3. Copyright (C) 2022 Minetest Authors
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include <iostream>
  18. #include <string>
  19. #include <functional>
  20. template<int BufferLength, typename Emitter = std::function<void(const std::string &)> >
  21. class StringStreamBuffer : public std::streambuf {
  22. public:
  23. StringStreamBuffer(Emitter emitter) : m_emitter(emitter) {
  24. buffer_index = 0;
  25. }
  26. int overflow(int c) {
  27. push_back(c);
  28. return c;
  29. }
  30. void push_back(char c) {
  31. if (c == '\n' || c == '\r') {
  32. if (buffer_index)
  33. m_emitter(std::string(buffer, buffer_index));
  34. buffer_index = 0;
  35. } else {
  36. buffer[buffer_index++] = c;
  37. if (buffer_index >= BufferLength) {
  38. m_emitter(std::string(buffer, buffer_index));
  39. buffer_index = 0;
  40. }
  41. }
  42. }
  43. std::streamsize xsputn(const char *s, std::streamsize n) {
  44. for (int i = 0; i < n; ++i)
  45. push_back(s[i]);
  46. return n;
  47. }
  48. private:
  49. Emitter m_emitter;
  50. char buffer[BufferLength];
  51. int buffer_index;
  52. };
  53. class DummyStreamBuffer : public std::streambuf {
  54. int overflow(int c) {
  55. return c;
  56. }
  57. std::streamsize xsputn(const char *s, std::streamsize n) {
  58. return n;
  59. }
  60. };