Luanti 5.18.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 <cstring>
8#include <iostream>
9#include <string_view>
10#include <functional>
11
12// this is declared in util/string.h, which we don't want to pull in entirely.
13extern size_t utf8_truncate_count(std::string_view input);
14
15template<unsigned int BufferLength, typename Emitter = std::function<void(std::string_view)> >
16class StringStreamBuffer : public std::streambuf {
17public:
18 StringStreamBuffer(Emitter emitter) : m_emitter(emitter) {
19 buffer_index = 0;
20 }
21
22 int overflow(int c) override {
23 if (c != traits_type::eof())
24 push_back(c);
25 return 0;
26 }
27
28 void push_back(char c) {
29 // emit only complete lines, or if the buffer is full
30 if (c == '\n') {
31 sync();
32 } else {
33 buffer[buffer_index++] = c;
34 if (buffer_index >= BufferLength) {
35 sync();
36 }
37 }
38 }
39
40 std::streamsize xsputn(const char *s, std::streamsize n) override {
41 for (std::streamsize i = 0; i < n; ++i)
42 push_back(s[i]);
43 return n;
44 }
45
46 int sync() override {
47 unsigned int tail = 0;
48 if (buffer_index) {
49 tail = utf8_truncate_count(std::string_view(buffer, buffer_index));
50 if (tail != buffer_index)
51 m_emitter(std::string_view(buffer, buffer_index - tail));
52 }
53 if (tail != buffer_index)
54 memmove(buffer, buffer + buffer_index - tail, tail);
55 // Note: because utf8_truncate_count will never return a tail larger
56 // than 4, we will always be able to flush enough bytes so that push_back
57 // doesn't need to worry about overflow (unless our buffer is tiny).
58 static_assert(BufferLength >= 10);
59 buffer_index = tail;
60 return 0;
61 }
62
63private:
64 Emitter m_emitter;
65 unsigned int buffer_index;
66 char buffer[BufferLength];
67};
68
69class DummyStreamBuffer : public std::streambuf {
70 int overflow(int c) override {
71 return 0;
72 }
73 std::streamsize xsputn(const char *s, std::streamsize n) override {
74 return n;
75 }
76};
Definition stream.h:69
int overflow(int c) override
Definition stream.h:70
std::streamsize xsputn(const char *s, std::streamsize n) override
Definition stream.h:73
unsigned int buffer_index
Definition stream.h:65
StringStreamBuffer(Emitter emitter)
Definition stream.h:18
int overflow(int c) override
Definition stream.h:22
std::streamsize xsputn(const char *s, std::streamsize n) override
Definition stream.h:40
Emitter m_emitter
Definition stream.h:64
char buffer[BufferLength]
Definition stream.h:66
void push_back(char c)
Definition stream.h:28
int sync() override
Definition stream.h:46
size_t utf8_truncate_count(std::string_view input)
Definition string.cpp:187