zhangmeng
2021-07-02 056f71f24cefaf88f2a93714c6678c03ed5f1e0e
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
//
//  Copyright (c) 2012 Artyom Beilis (Tonkikh)
//  Copyright (c) 2019-2020 Alexander Grund
//
//  Distributed under the Boost Software License, Version 1.0. (See
//  accompanying file LICENSE or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_NOWIDE_FILEBUF_HPP_INCLUDED
#define BOOST_NOWIDE_FILEBUF_HPP_INCLUDED
 
#include <boost/nowide/config.hpp>
#if BOOST_NOWIDE_USE_FILEBUF_REPLACEMENT
#include <boost/nowide/cstdio.hpp>
#include <boost/nowide/stackstring.hpp>
#include <cassert>
#include <cstdio>
#include <ios>
#include <limits>
#include <locale>
#include <stdexcept>
#include <streambuf>
#else
#include <fstream>
#endif
 
namespace boost {
namespace nowide {
    namespace detail {
        /// Same as std::ftell but potentially with Large File Support
        BOOST_NOWIDE_DECL std::streampos ftell(FILE* file);
        /// Same as std::fseek but potentially with Large File Support
        BOOST_NOWIDE_DECL int fseek(FILE* file, std::streamoff offset, int origin);
    } // namespace detail
 
#if !BOOST_NOWIDE_USE_FILEBUF_REPLACEMENT && !defined(BOOST_NOWIDE_DOXYGEN)
    using std::basic_filebuf;
    using std::filebuf;
#else // Windows
    ///
    /// \brief This forward declaration defines the basic_filebuf type.
    ///
    /// it is implemented and specialized for CharType = char, it
    /// implements std::filebuf over standard C I/O
    ///
    template<typename CharType, typename Traits = std::char_traits<CharType>>
    class basic_filebuf;
 
    ///
    /// \brief This is the implementation of std::filebuf
    ///
    /// it is implemented and specialized for CharType = char, it
    /// implements std::filebuf over standard C I/O
    ///
    template<>
    class basic_filebuf<char> : public std::basic_streambuf<char>
    {
        using Traits = std::char_traits<char>;
 
    public:
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable : 4351) // new behavior : elements of array will be default initialized
#endif
        ///
        /// Creates new filebuf
        ///
        basic_filebuf() :
            buffer_size_(BUFSIZ), buffer_(0), file_(0), owns_buffer_(false), last_char_(),
            mode_(std::ios_base::openmode(0))
        {
            setg(0, 0, 0);
            setp(0, 0);
        }
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
        basic_filebuf(const basic_filebuf&) = delete;
        basic_filebuf& operator=(const basic_filebuf&) = delete;
        basic_filebuf(basic_filebuf&& other) noexcept : basic_filebuf()
        {
            swap(other);
        }
        basic_filebuf& operator=(basic_filebuf&& other) noexcept
        {
            swap(other);
            return *this;
        }
        void swap(basic_filebuf& rhs)
        {
            std::basic_streambuf<char>::swap(rhs);
            using std::swap;
            swap(buffer_size_, rhs.buffer_size_);
            swap(buffer_, rhs.buffer_);
            swap(file_, rhs.file_);
            swap(owns_buffer_, rhs.owns_buffer_);
            swap(last_char_[0], rhs.last_char_[0]);
            swap(mode_, rhs.mode_);
            // Fixup last_char references
            if(epptr() == rhs.last_char_)
                setp(last_char_, last_char_);
            if(egptr() == rhs.last_char_)
                rhs.setg(last_char_, gptr() == rhs.last_char_ ? last_char_ : last_char_ + 1, last_char_ + 1);
            if(rhs.epptr() == last_char_)
                setp(rhs.last_char_, rhs.last_char_);
            if(rhs.egptr() == rhs.last_char_)
            {
                rhs.setg(rhs.last_char_,
                         rhs.gptr() == last_char_ ? rhs.last_char_ : rhs.last_char_ + 1,
                         rhs.last_char_ + 1);
            }
        }
 
        virtual ~basic_filebuf()
        {
            close();
        }
 
        ///
        /// Same as std::filebuf::open but s is UTF-8 string
        ///
        basic_filebuf* open(const std::string& s, std::ios_base::openmode mode)
        {
            return open(s.c_str(), mode);
        }
        ///
        /// Same as std::filebuf::open but s is UTF-8 string
        ///
        basic_filebuf* open(const char* s, std::ios_base::openmode mode)
        {
            const wstackstring name(s);
            return open(name.get(), mode);
        }
        /// Opens the file with the given name, see std::filebuf::open
        basic_filebuf* open(const wchar_t* s, std::ios_base::openmode mode)
        {
            if(is_open())
                return NULL;
            validate_cvt(this->getloc());
            const bool ate = (mode & std::ios_base::ate) != 0;
            if(ate)
                mode &= ~std::ios_base::ate;
            const wchar_t* smode = get_mode(mode);
            if(!smode)
                return 0;
            file_ = detail::wfopen(s, smode);
            if(!file_)
                return 0;
            if(ate && detail::fseek(file_, 0, SEEK_END) != 0)
            {
                close();
                return 0;
            }
            mode_ = mode;
            return this;
        }
        ///
        /// Same as std::filebuf::close()
        ///
        basic_filebuf* close()
        {
            if(!is_open())
                return NULL;
            bool res = sync() == 0;
            if(std::fclose(file_) != 0)
                res = false;
            file_ = NULL;
            mode_ = std::ios_base::openmode(0);
            if(owns_buffer_)
            {
                delete[] buffer_;
                buffer_ = NULL;
                owns_buffer_ = false;
            }
            return res ? this : NULL;
        }
        ///
        /// Same as std::filebuf::is_open()
        ///
        bool is_open() const
        {
            return file_ != NULL;
        }
 
    private:
        void make_buffer()
        {
            if(buffer_)
                return;
            if(buffer_size_ > 0)
            {
                buffer_ = new char[buffer_size_];
                owns_buffer_ = true;
            }
        }
        void validate_cvt(const std::locale& loc)
        {
            if(!std::use_facet<std::codecvt<char, char, std::mbstate_t>>(loc).always_noconv())
                throw std::runtime_error("Converting codecvts are not supported");
        }
 
    protected:
        std::streambuf* setbuf(char* s, std::streamsize n) override
        {
            assert(n >= 0);
            // Maximum compatibility: Discard all local buffers and use user-provided values
            // Users should call sync() before or better use it before any IO is done or any file is opened
            setg(NULL, NULL, NULL);
            setp(NULL, NULL);
            if(owns_buffer_)
                delete[] buffer_;
            buffer_ = s;
            buffer_size_ = (n >= 0) ? static_cast<size_t>(n) : 0;
            return this;
        }
 
        int overflow(int c = EOF) override
        {
            if(!(mode_ & std::ios_base::out))
                return EOF;
 
            if(!stop_reading())
                return EOF;
 
            size_t n = pptr() - pbase();
            if(n > 0)
            {
                if(std::fwrite(pbase(), 1, n, file_) != n)
                    return -1;
                setp(buffer_, buffer_ + buffer_size_);
                if(c != EOF)
                {
                    *buffer_ = Traits::to_char_type(c);
                    pbump(1);
                }
            } else if(c != EOF)
            {
                if(buffer_size_ > 0)
                {
                    make_buffer();
                    setp(buffer_, buffer_ + buffer_size_);
                    *buffer_ = Traits::to_char_type(c);
                    pbump(1);
                } else if(std::fputc(c, file_) == EOF)
                {
                    return EOF;
                } else if(!pptr())
                {
                    // Set to dummy value so we know we have written something
                    setp(last_char_, last_char_);
                }
            }
            return Traits::not_eof(c);
        }
 
        int sync() override
        {
            if(!file_)
                return 0;
            bool result;
            if(pptr())
            {
                result = overflow() != EOF;
                // Only flush if anything was written, otherwise behavior of fflush is undefined
                if(std::fflush(file_) != 0)
                    return result = false;
            } else
                result = stop_reading();
            return result ? 0 : -1;
        }
 
        int underflow() override
        {
            if(!(mode_ & std::ios_base::in))
                return EOF;
            if(!stop_writing())
                return EOF;
            if(buffer_size_ == 0)
            {
                const int c = std::fgetc(file_);
                if(c == EOF)
                    return EOF;
                last_char_[0] = Traits::to_char_type(c);
                setg(last_char_, last_char_, last_char_ + 1);
            } else
            {
                make_buffer();
                const size_t n = std::fread(buffer_, 1, buffer_size_, file_);
                setg(buffer_, buffer_, buffer_ + n);
                if(n == 0)
                    return EOF;
            }
            return Traits::to_int_type(*gptr());
        }
 
        int pbackfail(int c = EOF) override
        {
            if(!(mode_ & std::ios_base::in))
                return EOF;
            if(!stop_writing())
                return EOF;
            if(gptr() > eback())
                gbump(-1);
            else if(seekoff(-1, std::ios_base::cur) != std::streampos(std::streamoff(-1)))
            {
                if(underflow() == EOF)
                    return EOF;
            } else
                return EOF;
 
            // Case 1: Caller just wanted space for 1 char
            if(c == EOF)
                return Traits::not_eof(c);
            // Case 2: Caller wants to put back different char
            // gptr now points to the (potentially newly read) previous char
            if(*gptr() != c)
                *gptr() = Traits::to_char_type(c);
            return Traits::not_eof(c);
        }
 
        std::streampos seekoff(std::streamoff off,
                               std::ios_base::seekdir seekdir,
                               std::ios_base::openmode = std::ios_base::in | std::ios_base::out) override
        {
            if(!file_)
                return EOF;
            // Switching between input<->output requires a seek
            // So do NOT optimize for seekoff(0, cur) as No-OP
 
            // On some implementations a seek also flushes, so do a full sync
            if(sync() != 0)
                return EOF;
            int whence;
            switch(seekdir)
            {
            case std::ios_base::beg: whence = SEEK_SET; break;
            case std::ios_base::cur: whence = SEEK_CUR; break;
            case std::ios_base::end: whence = SEEK_END; break;
            default: assert(false); return EOF;
            }
            if(detail::fseek(file_, off, whence) != 0)
                return EOF;
            return detail::ftell(file_);
        }
        std::streampos seekpos(std::streampos pos,
                               std::ios_base::openmode m = std::ios_base::in | std::ios_base::out) override
        {
            // Standard mandates "as-if fsetpos", but assume the effect is the same as fseek
            return seekoff(pos, std::ios_base::beg, m);
        }
        void imbue(const std::locale& loc) override
        {
            validate_cvt(loc);
        }
 
    private:
        /// Stop reading adjusting the file pointer if necessary
        /// Postcondition: gptr() == NULL
        bool stop_reading()
        {
            if(!gptr())
                return true;
            const auto off = gptr() - egptr();
            setg(0, 0, 0);
            if(!off)
                return true;
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
#endif
            // coverity[result_independent_of_operands]
            if(off > std::numeric_limits<std::streamoff>::max())
                return false;
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
            return detail::fseek(file_, static_cast<std::streamoff>(off), SEEK_CUR) == 0;
        }
 
        /// Stop writing. If any bytes are to be written, writes them to file
        /// Postcondition: pptr() == NULL
        bool stop_writing()
        {
            if(pptr())
            {
                const char* const base = pbase();
                const size_t n = pptr() - base;
                setp(0, 0);
                if(n && std::fwrite(base, 1, n, file_) != n)
                    return false;
            }
            return true;
        }
 
        void reset(FILE* f = 0)
        {
            sync();
            if(file_)
            {
                fclose(file_);
                file_ = 0;
            }
            file_ = f;
        }
 
        static const wchar_t* get_mode(std::ios_base::openmode mode)
        {
            //
            // done according to n2914 table 106 27.9.1.4
            //
 
            // note can't use switch case as overload operator can't be used
            // in constant expression
            if(mode == (std::ios_base::out))
                return L"w";
            if(mode == (std::ios_base::out | std::ios_base::app))
                return L"a";
            if(mode == (std::ios_base::app))
                return L"a";
            if(mode == (std::ios_base::out | std::ios_base::trunc))
                return L"w";
            if(mode == (std::ios_base::in))
                return L"r";
            if(mode == (std::ios_base::in | std::ios_base::out))
                return L"r+";
            if(mode == (std::ios_base::in | std::ios_base::out | std::ios_base::trunc))
                return L"w+";
            if(mode == (std::ios_base::in | std::ios_base::out | std::ios_base::app))
                return L"a+";
            if(mode == (std::ios_base::in | std::ios_base::app))
                return L"a+";
            if(mode == (std::ios_base::binary | std::ios_base::out))
                return L"wb";
            if(mode == (std::ios_base::binary | std::ios_base::out | std::ios_base::app))
                return L"ab";
            if(mode == (std::ios_base::binary | std::ios_base::app))
                return L"ab";
            if(mode == (std::ios_base::binary | std::ios_base::out | std::ios_base::trunc))
                return L"wb";
            if(mode == (std::ios_base::binary | std::ios_base::in))
                return L"rb";
            if(mode == (std::ios_base::binary | std::ios_base::in | std::ios_base::out))
                return L"r+b";
            if(mode == (std::ios_base::binary | std::ios_base::in | std::ios_base::out | std::ios_base::trunc))
                return L"w+b";
            if(mode == (std::ios_base::binary | std::ios_base::in | std::ios_base::out | std::ios_base::app))
                return L"a+b";
            if(mode == (std::ios_base::binary | std::ios_base::in | std::ios_base::app))
                return L"a+b";
            return 0;
        }
 
        size_t buffer_size_;
        char* buffer_;
        FILE* file_;
        bool owns_buffer_;
        char last_char_[1];
        std::ios::openmode mode_;
    };
 
    ///
    /// \brief Convenience typedef
    ///
    using filebuf = basic_filebuf<char>;
 
#endif // windows
 
} // namespace nowide
} // namespace boost
 
#endif