aboutsummaryrefslogtreecommitdiffstats
path: root/util/stream/input.cpp
blob: a0e4ce36b84a5ed0dfcd28c2347626207362553a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#include "input.h"
#include "output.h" 
#include "str.h" 

#include <util/charset/wide.h>
#include <util/memory/tempbuf.h>
#include <util/generic/string.h>
#include <util/generic/yexception.h>
#include <util/generic/singleton.h>
#include <util/string/cast.h>
#include <util/system/compat.h>
#include <util/system/spinlock.h>

#include <cstdlib>

IInputStream::IInputStream() noexcept = default;

IInputStream::~IInputStream() = default;

size_t IInputStream::DoReadTo(TString& st, char to) {
    char ch;

    if (!Read(&ch, 1)) {
        return 0; 
    }

    st.clear();

    size_t result = 0; 
    do {
        ++result;
 
        if (ch == to) {
            break;
        }

        st += ch;
    } while (Read(&ch, 1));

    return result; 
}

ui64 IInputStream::DoReadAll(IOutputStream& out) {
    TTempBuf buffer; 
    void* ptr = buffer.Data(); 
    size_t size = buffer.Size(); 
 
    ui64 result = 0; 
    while (size_t read = Read(ptr, size)) { 
        out.Write(ptr, read); 
        result += read; 
    } 
 
    return result; 
} 
 
size_t IInputStream::Load(void* buf_in, size_t len) {
    char* buf = (char*)buf_in;

    while (len) {
        const size_t ret = Read(buf, len);

        buf += ret;
        len -= ret;

        if (ret == 0) {
            break;
        }
    }

    return buf - (char*)buf_in;
}

void IInputStream::LoadOrFail(void* buf, size_t len) {
    const size_t realLen = Load(buf, len);
    if (Y_UNLIKELY(realLen != len)) {
        ythrow yexception() << "Failed to read required number of bytes from stream! Expected: " << len << ", gained: " << realLen << "!";
    }
}

size_t IInputStream::ReadLine(TString& st) {
    const size_t ret = ReadTo(st, '\n'); 

    if (ret && !st.empty() && st.back() == '\r') {
        st.pop_back();
    }

    return ret; 
}

size_t IInputStream::ReadLine(TUtf16String& w) {
    TString s;
    size_t result = ReadLine(s); 

    if (result) { 
        UTF8ToWide(s, w); 
    } 
 
    return result; 
}

TString IInputStream::ReadLine() {
    TString ret;

    if (!ReadLine(ret)) {
        ythrow yexception() << "can not read line from stream";
    }

    return ret;
}

TString IInputStream::ReadTo(char ch) {
    TString ret;

    if (!ReadTo(ret, ch)) {
        ythrow yexception() << "can not read from stream";
    }

    return ret;
}

size_t IInputStream::Skip(size_t sz) {
    return DoSkip(sz);
}

size_t IInputStream::DoSkip(size_t sz) {
    if (sz < 128) {
        return Load(alloca(sz), sz);
    }

    TTempBuf buf;
    size_t total = 0;

    while (sz) {
        const size_t lresult = Read(buf.Data(), Min<size_t>(sz, buf.Size()));

        if (lresult == 0) {
            return total;
        }

        total += lresult;
        sz -= lresult;
    }

    return total;
}

TString IInputStream::ReadAll() {
    TString result;
    TStringOutput stream(result); 

    DoReadAll(stream); 
 
    return result; 
} 

ui64 IInputStream::ReadAll(IOutputStream& out) {
    return DoReadAll(out); 
}

ui64 TransferData(IInputStream* in, IOutputStream* out) {
    return in->ReadAll(*out); 
} 
 
namespace {
    struct TStdIn: public IInputStream {
        ~TStdIn() override = default;

        size_t DoRead(void* buf, size_t len) override {
            const size_t ret = fread(buf, 1, len, F_);

            if (ret < len && ferror(F_)) {
                ythrow TSystemError() << "can not read from stdin";
            }

            return ret;
        }

        FILE* F_ = stdin;
    };

#if defined(_win_)
    using TGetLine = TStdIn;
#else
    #if defined(_bionic_)
    using TGetLineBase = TStdIn;
    #else
    struct TGetLineBase: public TStdIn {
        ~TGetLineBase() override {
            free(B_);
        }

        size_t DoReadTo(TString& st, char ch) override {
            auto&& guard = Guard(M_);

            (void)guard;

            const auto r = getdelim(&B_, &L_, ch, F_);

            if (r < 0) {
                if (ferror(F_)) {
                    ythrow TSystemError() << "can not read from stdin";
                }

                st.clear();

                return 0;
            }

            st.AssignNoAlias(B_, r);

            if (st && st.back() == ch) {
                st.pop_back();
            }

            return r;
        }

        TAdaptiveLock M_;
        char* B_ = nullptr;
        size_t L_ = 0;
    };
    #endif

    #if defined(_glibc_) || defined(_cygwin_)
    // glibc does not have fgetln
    using TGetLine = TGetLineBase;
    #else
    struct TGetLine: public TGetLineBase {
        size_t DoReadTo(TString& st, char ch) override {
            if (ch == '\n') {
                size_t len = 0;
                auto r = fgetln(F_, &len);

                if (r) {
                    st.AssignNoAlias(r, len);

                    if (st && st.back() == '\n') {
                        st.pop_back();
                    }

                    return len;
                }
            }

            return TGetLineBase::DoReadTo(st, ch);
        }
    };
    #endif
#endif
}

IInputStream& NPrivate::StdInStream() noexcept {
    return *SingletonWithPriority<TGetLine, 4>();
}

// implementation of >> operator

// helper functions

static inline bool IsStdDelimiter(char c) {
    return (c == '\0') || (c == ' ') || (c == '\r') || (c == '\n') || (c == '\t');
}

static void ReadUpToDelimiter(IInputStream& i, TString& s) {
    char c;
    while (i.ReadChar(c)) { // skip delimiters
        if (!IsStdDelimiter(c)) {
            s += c;
            break;
        }
    }
    while (i.ReadChar(c) && !IsStdDelimiter(c)) { // read data (with trailing delimiter)
        s += c;
    }
}

// specialization for string-related stuff

template <>
void In<TString>(IInputStream& i, TString& s) {
    s.resize(0);
    ReadUpToDelimiter(i, s);
}

template <>
void In<TUtf16String>(IInputStream& i, TUtf16String& w) {
    TString s;
    ReadUpToDelimiter(i, s);

    if (s.empty()) {
        w.erase();
    } else {
        w = UTF8ToWide(s);
    }
}

// specialization for char types

#define SPEC_FOR_CHAR(T)                  \
    template <>                           \
    void In<T>(IInputStream & i, T & t) { \
        i.ReadChar((char&)t);             \
    }

SPEC_FOR_CHAR(char)
SPEC_FOR_CHAR(unsigned char)
SPEC_FOR_CHAR(signed char)

#undef SPEC_FOR_CHAR

// specialization for number types

#define SPEC_FOR_NUMBER(T)                                                       \
    template <>                                                                  \
    void In<T>(IInputStream & i, T & t) {                                        \
        char buf[128];                                                           \
        size_t pos = 0;                                                          \
        while (i.ReadChar(buf[0])) {                                             \
            if (!IsStdDelimiter(buf[0])) {                                       \
                ++pos;                                                           \
                break;                                                           \
            }                                                                    \
        }                                                                        \
        while (i.ReadChar(buf[pos]) && !IsStdDelimiter(buf[pos]) && pos < 127) { \
            ++pos;                                                               \
        }                                                                        \
        t = FromString<T, char>(buf, pos);                                       \
    }

SPEC_FOR_NUMBER(signed short)
SPEC_FOR_NUMBER(signed int)
SPEC_FOR_NUMBER(signed long int)
SPEC_FOR_NUMBER(signed long long int)
SPEC_FOR_NUMBER(unsigned short)
SPEC_FOR_NUMBER(unsigned int)
SPEC_FOR_NUMBER(unsigned long int)
SPEC_FOR_NUMBER(unsigned long long int)

SPEC_FOR_NUMBER(float)
SPEC_FOR_NUMBER(double)
SPEC_FOR_NUMBER(long double)

#undef SPEC_FOR_NUMBER