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