2024-10-28 15:57:39 +01:00
|
|
|
// Luanti
|
|
|
|
// SPDX-License-Identifier: LGPL-2.1-or-later
|
|
|
|
// Copyright (C) 2022 Minetest Authors
|
2022-05-04 11:55:01 -07:00
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <iostream>
|
2024-08-31 21:23:16 +02:00
|
|
|
#include <string_view>
|
2022-05-04 11:55:01 -07:00
|
|
|
#include <functional>
|
|
|
|
|
2024-10-08 12:14:40 +02:00
|
|
|
template<unsigned int BufferLength, typename Emitter = std::function<void(std::string_view)> >
|
2022-05-04 11:55:01 -07:00
|
|
|
class StringStreamBuffer : public std::streambuf {
|
|
|
|
public:
|
|
|
|
StringStreamBuffer(Emitter emitter) : m_emitter(emitter) {
|
|
|
|
buffer_index = 0;
|
|
|
|
}
|
|
|
|
|
2024-10-08 12:14:40 +02:00
|
|
|
int overflow(int c) override {
|
|
|
|
if (c != traits_type::eof())
|
|
|
|
push_back(c);
|
|
|
|
return 0;
|
2022-05-04 11:55:01 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
void push_back(char c) {
|
2024-10-08 12:14:40 +02:00
|
|
|
// emit only complete lines, or if the buffer is full
|
|
|
|
if (c == '\n') {
|
|
|
|
sync();
|
2022-05-04 11:55:01 -07:00
|
|
|
} else {
|
|
|
|
buffer[buffer_index++] = c;
|
|
|
|
if (buffer_index >= BufferLength) {
|
2024-10-08 12:14:40 +02:00
|
|
|
sync();
|
2022-05-04 11:55:01 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-08 12:14:40 +02:00
|
|
|
std::streamsize xsputn(const char *s, std::streamsize n) override {
|
2024-08-31 21:23:16 +02:00
|
|
|
for (std::streamsize i = 0; i < n; ++i)
|
2022-05-04 11:55:01 -07:00
|
|
|
push_back(s[i]);
|
|
|
|
return n;
|
|
|
|
}
|
2024-10-08 12:14:40 +02:00
|
|
|
|
|
|
|
int sync() override {
|
|
|
|
if (buffer_index)
|
|
|
|
m_emitter(std::string_view(buffer, buffer_index));
|
|
|
|
buffer_index = 0;
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2022-05-04 11:55:01 -07:00
|
|
|
private:
|
|
|
|
Emitter m_emitter;
|
2024-10-08 12:14:40 +02:00
|
|
|
unsigned int buffer_index;
|
2022-05-04 11:55:01 -07:00
|
|
|
char buffer[BufferLength];
|
|
|
|
};
|
|
|
|
|
|
|
|
class DummyStreamBuffer : public std::streambuf {
|
2024-10-08 12:14:40 +02:00
|
|
|
int overflow(int c) override {
|
|
|
|
return 0;
|
2022-05-04 11:55:01 -07:00
|
|
|
}
|
2024-10-08 12:14:40 +02:00
|
|
|
std::streamsize xsputn(const char *s, std::streamsize n) override {
|
2022-05-04 11:55:01 -07:00
|
|
|
return n;
|
|
|
|
}
|
|
|
|
};
|