aboutsummaryrefslogtreecommitdiffstats
path: root/util/stream/output.cpp
blob: 9cd1f4b0926cc86e6fc4eeeeffe6440c23244c24 (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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
#include "output.h"

#include <util/string/cast.h>
#include "format.h"
#include <util/memory/tempbuf.h>
#include <util/generic/singleton.h>
#include <util/generic/yexception.h>
#include <util/charset/utf8.h>
#include <util/charset/wide.h>

#if defined(_android_)
    #include <util/system/dynlib.h>
    #include <util/system/guard.h>
    #include <util/system/mutex.h>
    #include <android/log.h>
#endif

#include <cerrno>
#include <string>
#include <string_view>
#include <cstdio>

#if defined(_win_)
    #include <io.h>
#endif

constexpr size_t MAX_UTF8_BYTES = 4; // UTF-8-encoded code point takes between 1 and 4 bytes

IOutputStream::IOutputStream() noexcept = default;

IOutputStream::~IOutputStream() = default;

void IOutputStream::DoFlush() {
    /*
     * do nothing
     */
}

void IOutputStream::DoFinish() {
    Flush();
}

void IOutputStream::DoWriteV(const TPart* parts, size_t count) {
    for (size_t i = 0; i < count; ++i) {
        const TPart& part = parts[i];

        DoWrite(part.buf, part.len);
    }
}

void IOutputStream::DoWriteC(char ch) {
    DoWrite(&ch, 1);
}

template <>
void Out<wchar16>(IOutputStream& o, wchar16 ch) {
    const wchar32 w32ch = ReadSymbol(&ch, &ch + 1);
    size_t length;
    unsigned char buffer[MAX_UTF8_BYTES];
    WriteUTF8Char(w32ch, length, buffer);
    o.Write(buffer, length);
}

template <>
void Out<wchar32>(IOutputStream& o, wchar32 ch) {
    size_t length;
    unsigned char buffer[MAX_UTF8_BYTES];
    WriteUTF8Char(ch, length, buffer);
    o.Write(buffer, length);
}

static void WriteString(IOutputStream& o, const wchar16* w, size_t n) {
    const size_t buflen = (n * MAX_UTF8_BYTES); // * 4 because the conversion functions can convert unicode character into maximum 4 bytes of UTF8
    TTempBuf buffer(buflen + 1);
    char* const data = buffer.Data();
    size_t written = 0;
    WideToUTF8(w, n, data, written);
    data[written] = 0;
    o.Write(data, written);
}

static void WriteString(IOutputStream& o, const wchar32* w, size_t n) {
    const size_t buflen = (n * MAX_UTF8_BYTES); // * 4 because the conversion functions can convert unicode character into maximum 4 bytes of UTF8
    TTempBuf buffer(buflen + 1);
    char* const data = buffer.Data();
    size_t written = 0;
    WideToUTF8(w, n, data, written);
    data[written] = 0;
    o.Write(data, written);
}

template <>
void Out<TString>(IOutputStream& o, const TString& p) {
    o.Write(p.data(), p.size());
}

template <>
void Out<std::string>(IOutputStream& o, const std::string& p) {
    o.Write(p.data(), p.length());
}

template <>
void Out<std::string_view>(IOutputStream& o, const std::string_view& p) {
    o.Write(p.data(), p.length());
}

template <>
void Out<std::u16string_view>(IOutputStream& o, const std::u16string_view& p) {
    WriteString(o, p.data(), p.length());
}

template <>
void Out<std::u32string_view>(IOutputStream& o, const std::u32string_view& p) {
    WriteString(o, p.data(), p.length());
}

template <>
void Out<TStringBuf>(IOutputStream& o, const TStringBuf& p) {
    o.Write(p.data(), p.length());
} 
 
template <> 
void Out<TWtringBuf>(IOutputStream& o, const TWtringBuf& p) {
    WriteString(o, p.data(), p.length());
} 
 
template <> 
void Out<TUtf32StringBuf>(IOutputStream& o, const TUtf32StringBuf& p) {
    WriteString(o, p.data(), p.length());
} 
 
template <> 
void Out<const wchar16*>(IOutputStream& o, const wchar16* w) {
    if (w) {
        WriteString(o, w, std::char_traits<wchar16>::length(w));
    } else {
        o.Write("(null)");
    }
}

template <>
void Out<const wchar32*>(IOutputStream& o, const wchar32* w) {
    if (w) {
        WriteString(o, w, std::char_traits<wchar32>::length(w));
    } else {
        o.Write("(null)");
    }
}

template <>
void Out<TUtf16String>(IOutputStream& o, const TUtf16String& w) {
    WriteString(o, w.c_str(), w.size());
}

template <>
void Out<TUtf32String>(IOutputStream& o, const TUtf32String& w) {
    WriteString(o, w.c_str(), w.size());
}

#define DEF_CONV_DEFAULT(type)                  \
    template <>                                 \
    void Out<type>(IOutputStream & o, type p) { \
        o << ToString(p);                       \
    }

#define DEF_CONV_CHR(type)                      \
    template <>                                 \
    void Out<type>(IOutputStream & o, type p) { \
        o.Write((char)p);                       \
    }

#define DEF_CONV_NUM(type, len)                                   \
    template <>                                                   \
    void Out<type>(IOutputStream & o, type p) {                   \
        char buf[len];                                            \
        o.Write(buf, ToString(p, buf, sizeof(buf)));              \
    }                                                             \
                                                                  \
    template <>                                                   \
    void Out<volatile type>(IOutputStream & o, volatile type p) { \
        Out<type>(o, p);                                          \
    }

DEF_CONV_NUM(bool, 64)

DEF_CONV_CHR(char)
DEF_CONV_CHR(signed char)
DEF_CONV_CHR(unsigned char)

DEF_CONV_NUM(signed short, 64)
DEF_CONV_NUM(signed int, 64)
DEF_CONV_NUM(signed long int, 64)
DEF_CONV_NUM(signed long long int, 64)

DEF_CONV_NUM(unsigned short, 64)
DEF_CONV_NUM(unsigned int, 64)
DEF_CONV_NUM(unsigned long int, 64)
DEF_CONV_NUM(unsigned long long int, 64)

DEF_CONV_NUM(float, 512)
DEF_CONV_NUM(double, 512)
DEF_CONV_NUM(long double, 512)

#if !defined(_YNDX_LIBCXX_ENABLE_VECTOR_BOOL_COMPRESSION) || (_YNDX_LIBCXX_ENABLE_VECTOR_BOOL_COMPRESSION == 1) 
// TODO: acknowledge std::bitset::reference for both libc++ and libstdc++ 
template <>
void Out<typename std::vector<bool>::reference>(IOutputStream& o, const std::vector<bool>::reference& bit) { 
    return Out<bool>(o, static_cast<bool>(bit)); 
} 
#endif 
 
#ifndef TSTRING_IS_STD_STRING
template <>
void Out<TBasicCharRef<TString>>(IOutputStream& o, const TBasicCharRef<TString>& c) {
    o << static_cast<char>(c);
}

template <>
void Out<TBasicCharRef<TUtf16String>>(IOutputStream& o, const TBasicCharRef<TUtf16String>& c) {
    o << static_cast<wchar16>(c);
}

template <>
void Out<TBasicCharRef<TUtf32String>>(IOutputStream& o, const TBasicCharRef<TUtf32String>& c) {
    o << static_cast<wchar32>(c);
}
#endif

template <>
void Out<const void*>(IOutputStream& o, const void* t) {
    o << Hex(size_t(t));
}

template <>
void Out<void*>(IOutputStream& o, void* t) {
    Out<const void*>(o, t);
}

using TNullPtr = decltype(nullptr);

template <>
void Out<TNullPtr>(IOutputStream& o, TTypeTraits<TNullPtr>::TFuncParam) {
    o << TStringBuf("nullptr");
}

#if defined(_android_)
namespace {
    class TAndroidStdIOStreams {
    public:
        TAndroidStdIOStreams()
            : LogLibrary("liblog.so")
            , LogFuncPtr((TLogFuncPtr)LogLibrary.Sym("__android_log_write"))
            , Out(LogFuncPtr)
            , Err(LogFuncPtr)
        {
        }

    public:
        using TLogFuncPtr = void (*)(int, const char*, const char*);

        class TAndroidStdOutput: public IOutputStream {
        public:
            inline TAndroidStdOutput(TLogFuncPtr logFuncPtr) noexcept
                : Buffer()
                , LogFuncPtr(logFuncPtr)
            {
            }

            virtual ~TAndroidStdOutput() {
            }

        private:
            virtual void DoWrite(const void* buf, size_t len) override {
                with_lock (BufferMutex) {
                    Buffer.Write(buf, len);
                }
            }

            virtual void DoFlush() override {
                with_lock (BufferMutex) {
                    LogFuncPtr(ANDROID_LOG_DEBUG, GetTag(), Buffer.Data());
                    Buffer.Clear();
                }
            }

            virtual const char* GetTag() const = 0;

        private:
            TMutex BufferMutex;
            TStringStream Buffer;
            TLogFuncPtr LogFuncPtr;
        };

        class TStdErr: public TAndroidStdOutput {
        public:
            TStdErr(TLogFuncPtr logFuncPtr)
                : TAndroidStdOutput(logFuncPtr)
            {
            }

            virtual ~TStdErr() {
            }

        private:
            virtual const char* GetTag() const override {
                return "stderr";
            }
        };

        class TStdOut: public TAndroidStdOutput {
        public:
            TStdOut(TLogFuncPtr logFuncPtr)
                : TAndroidStdOutput(logFuncPtr)
            {
            }

            virtual ~TStdOut() {
            }

        private:
            virtual const char* GetTag() const override {
                return "stdout";
            }
        };

        static bool Enabled;
        TDynamicLibrary LogLibrary; // field order is important, see constructor
        TLogFuncPtr LogFuncPtr;
        TStdOut Out;
        TStdErr Err;

        static inline TAndroidStdIOStreams& Instance() {
            return *SingletonWithPriority<TAndroidStdIOStreams, 4>();
        }
    };

    bool TAndroidStdIOStreams::Enabled = false;
}
#endif // _android_

namespace {
    class TStdOutput: public IOutputStream {
    public:
        inline TStdOutput(FILE* f) noexcept
            : F_(f)
        {
        }

        ~TStdOutput() override = default;

    private:
        void DoWrite(const void* buf, size_t len) override {
            if (len != fwrite(buf, 1, len, F_)) {
#if defined(_win_)
                // On Windows, if 'F_' is console -- 'fwrite' returns count of written characters.
                // If, for example, console output codepage is UTF-8, then returned value is
                // not equal to 'len'. So, we ignore some 'errno' values...
                if ((errno == 0 || errno == EINVAL || errno == EILSEQ) && _isatty(fileno(F_))) {
                    return;
                }
#endif
                ythrow TSystemError() << "write failed";
            }
        }

        void DoFlush() override {
            if (fflush(F_) != 0) {
                ythrow TSystemError() << "fflush failed";
            }
        }

    private:
        FILE* F_;
    };

    struct TStdIOStreams {
        struct TStdErr: public TStdOutput {
            inline TStdErr()
                : TStdOutput(stderr)
            {
            }

            ~TStdErr() override = default;
        };

        struct TStdOut: public TStdOutput {
            inline TStdOut()
                : TStdOutput(stdout)
            {
            }

            ~TStdOut() override = default;
        };

        TStdOut Out;
        TStdErr Err;

        static inline TStdIOStreams& Instance() {
            return *SingletonWithPriority<TStdIOStreams, 4>();
        }
    };
}

IOutputStream& NPrivate::StdErrStream() noexcept {
#if defined(_android_)
    if (TAndroidStdIOStreams::Enabled) {
        return TAndroidStdIOStreams::Instance().Err;
    }
#endif
    return TStdIOStreams::Instance().Err;
}

IOutputStream& NPrivate::StdOutStream() noexcept {
#if defined(_android_)
    if (TAndroidStdIOStreams::Enabled) {
        return TAndroidStdIOStreams::Instance().Out;
    }
#endif
    return TStdIOStreams::Instance().Out;
}

void RedirectStdioToAndroidLog(bool redirect) {
#if defined(_android_)
    TAndroidStdIOStreams::Enabled = redirect;
#else
    Y_UNUSED(redirect);
#endif
}