Luanti 5.11.0-dev
 
Loading...
Searching...
No Matches
stream.h
Go to the documentation of this file.
1// Luanti
2// SPDX-License-Identifier: LGPL-2.1-or-later
3// Copyright (C) 2022 Minetest Authors
4
5#pragma once
6
7#include <iostream>
8#include <string_view>
9#include <functional>
10
11template<unsigned int BufferLength, typename Emitter = std::function<void(std::string_view)> >
12class StringStreamBuffer : public std::streambuf {
13public:
14 StringStreamBuffer(Emitter emitter) : m_emitter(emitter) {
15 buffer_index = 0;
16 }
17
18 int overflow(int c) override {
19 if (c != traits_type::eof())
20 push_back(c);
21 return 0;
22 }
23
24 void push_back(char c) {
25 // emit only complete lines, or if the buffer is full
26 if (c == '\n') {
27 sync();
28 } else {
29 buffer[buffer_index++] = c;
30 if (buffer_index >= BufferLength) {
31 sync();
32 }
33 }
34 }
35
36 std::streamsize xsputn(const char *s, std::streamsize n) override {
37 for (std::streamsize i = 0; i < n; ++i)
38 push_back(s[i]);
39 return n;
40 }
41
42 int sync() override {
43 if (buffer_index)
44 m_emitter(std::string_view(buffer, buffer_index));
45 buffer_index = 0;
46 return 0;
47 }
48
49private:
50 Emitter m_emitter;
51 unsigned int buffer_index;
52 char buffer[BufferLength];
53};
54
55class DummyStreamBuffer : public std::streambuf {
56 int overflow(int c) override {
57 return 0;
58 }
59 std::streamsize xsputn(const char *s, std::streamsize n) override {
60 return n;
61 }
62};
Definition stream.h:55
int overflow(int c) override
Definition stream.h:56
std::streamsize xsputn(const char *s, std::streamsize n) override
Definition stream.h:59
Definition stream.h:12
unsigned int buffer_index
Definition stream.h:51
StringStreamBuffer(Emitter emitter)
Definition stream.h:14
int overflow(int c) override
Definition stream.h:18
std::streamsize xsputn(const char *s, std::streamsize n) override
Definition stream.h:36
Emitter m_emitter
Definition stream.h:50
char buffer[BufferLength]
Definition stream.h:52
void push_back(char c)
Definition stream.h:24
int sync() override
Definition stream.h:42