idol
A C++ Framework for Optimization
Loading...
Searching...
No Matches
LimitedWidthStream.h
1//
2// Created by henri on 20.06.24.
3//
4
5#ifndef IDOL_LIMITEDWIDTHSTREAM_H
6#define IDOL_LIMITEDWIDTHSTREAM_H
7#include <iostream>
8#include <sstream>
9#include <streambuf>
10#include <ostream>
11
12namespace idol {
13
14 class LimitedWidthBuffer : public std::streambuf {
15 public:
16 LimitedWidthBuffer(std::streambuf* sbuf, std::size_t max_width)
17 : original_buffer(sbuf), max_width(max_width), current_width(0) {}
18
19 protected:
20 virtual int overflow(int ch) override {
21 if (ch == '\n' || ch == EOF) {
22 current_width = 0;
23 return original_buffer->sputc(ch);
24 } else {
25 if (current_width >= max_width) {
26 if (original_buffer->sputc('\n') == EOF) {
27 return EOF;
28 }
29 current_width = 0;
30 }
31 ++current_width;
32 return original_buffer->sputc(ch);
33 }
34 }
35
36 virtual std::streamsize xsputn(const char* s, std::streamsize n) override {
37 std::streamsize written = 0;
38 while (written < n) {
39 if (current_width >= max_width) {
40 if (original_buffer->sputc('\n') == EOF) {
41 return written;
42 }
43 current_width = 0;
44 }
45 std::streamsize remaining = n - written;
46 std::streamsize space_left = max_width - current_width;
47 std::streamsize to_write = std::min(remaining, space_left);
48 std::streamsize just_written = original_buffer->sputn(s + written, to_write);
49 if (just_written == 0) {
50 return written;
51 }
52 written += just_written;
53 current_width += just_written;
54 }
55 return written;
56 }
57
58 private:
59 std::streambuf* original_buffer;
60 std::size_t max_width;
61 std::size_t current_width;
62 };
63
64 class LimitedWidthStream : public std::ostream {
65 public:
66 LimitedWidthStream(std::ostream& os, std::size_t max_width)
67 : std::ostream(&buffer), buffer(os.rdbuf(), max_width) {}
68
69 private:
70 LimitedWidthBuffer buffer;
71 };
72
73}
74
75#endif //IDOL_LIMITEDWIDTHSTREAM_H