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