summaryrefslogtreecommitdiffstats
path: root/src/third-party/scnlib/include/scn/detail/file.h
blob: 03ccff75231939bdc060aafad1eea9f21ea774bd (plain)
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Copyright 2017 Elias Kosunen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// This file is a part of scnlib:
//     https://github.com/eliaskosunen/scnlib

#ifndef SCN_DETAIL_FILE_H
#define SCN_DETAIL_FILE_H

#include <cstdio>
#include <string>

#include "../util/algorithm.h"
#include "range.h"

namespace scn {
    SCN_BEGIN_NAMESPACE

    namespace detail {
        struct native_file_handle {
#if SCN_WINDOWS
            using handle_type = void*;
#else
            using handle_type = int;
#endif

            static native_file_handle invalid();

            handle_type handle;
        };

        class byte_mapped_file {
        public:
            using iterator = const char*;
            using sentinel = const char*;

            byte_mapped_file() = default;
            explicit byte_mapped_file(const char* filename);

            byte_mapped_file(const byte_mapped_file&) = delete;
            byte_mapped_file& operator=(const byte_mapped_file&) = delete;

            byte_mapped_file(byte_mapped_file&& o) noexcept
                : m_map(exchange(o.m_map, span<char>{})),
                  m_file(exchange(o.m_file, native_file_handle::invalid()))
            {
#if SCN_WINDOWS
                m_map_handle =
                    exchange(o.m_map_handle, native_file_handle::invalid());
#endif
                SCN_ENSURE(!o.valid());
                SCN_ENSURE(valid());
            }
            byte_mapped_file& operator=(byte_mapped_file&& o) noexcept
            {
                if (valid()) {
                    _destruct();
                }

                m_map = exchange(o.m_map, span<char>{});
                m_file = exchange(o.m_file, native_file_handle::invalid());
#if SCN_WINDOWS
                m_map_handle =
                    exchange(o.m_map_handle, native_file_handle::invalid());
#endif

                SCN_ENSURE(!o.valid());
                SCN_ENSURE(valid());
                return *this;
            }

            ~byte_mapped_file()
            {
                if (valid()) {
                    _destruct();
                }
            }

            SCN_NODISCARD bool valid() const
            {
                return m_file.handle != native_file_handle::invalid().handle;
            }

            SCN_NODISCARD iterator begin() const
            {
                return m_map.begin();
            }
            SCN_NODISCARD sentinel end() const
            {
                return m_map.end();
            }

        protected:
            void _destruct();

            span<char> m_map{};
            native_file_handle m_file{native_file_handle::invalid().handle};
#if SCN_WINDOWS
            native_file_handle m_map_handle{
                native_file_handle::invalid().handle};
#endif
        };
    }  // namespace detail

    /**
     * Memory-mapped file range.
     * Manages the lifetime of the mapping itself.
     */
    template <typename CharT>
    class basic_mapped_file : public detail::byte_mapped_file {
    public:
        using iterator = const CharT*;
        using sentinel = const CharT*;

        /// Constructs an empty mapping
        basic_mapped_file() = default;

        /// Constructs a mapping to a filename
        explicit basic_mapped_file(const char* f) : detail::byte_mapped_file{f}
        {
        }

        SCN_NODISCARD iterator begin() const noexcept
        {
            // embrace the UB
            return reinterpret_cast<iterator>(byte_mapped_file::begin());
        }
        SCN_NODISCARD sentinel end() const noexcept
        {
            return reinterpret_cast<sentinel>(byte_mapped_file::end());
        }

        SCN_NODISCARD iterator data() const noexcept
        {
            return begin();
        }
        SCN_NODISCARD size_t size() const noexcept
        {
            return m_map.size() / sizeof(CharT);
        }

        /// Mapping data
        span<const CharT> buffer() const
        {
            return {data(), size()};
        }

        detail::range_wrapper<basic_string_view<CharT>> wrap() const noexcept
        {
            return basic_string_view<CharT>{data(), size()};
        }
    };

    using mapped_file = basic_mapped_file<char>;
    using mapped_wfile = basic_mapped_file<wchar_t>;

    namespace detail {
        template <typename CharT>
        struct basic_file_access;
        template <typename CharT>
        struct basic_file_iterator_access;
    }  // namespace detail

    /**
     * Range mapping to a C FILE*.
     * Not copyable or reconstructible.
     */
    template <typename CharT>
    class basic_file {
        friend struct detail::basic_file_access<CharT>;
        friend struct detail::basic_file_iterator_access<CharT>;

    public:
        class iterator {
            friend struct detail::basic_file_iterator_access<CharT>;

        public:
            using char_type = CharT;
            using value_type = expected<CharT>;
            using reference = value_type;
            using pointer = value_type*;
            using difference_type = std::ptrdiff_t;
            using iterator_category = std::bidirectional_iterator_tag;
            using file_type = basic_file<CharT>;

            iterator() = default;

            expected<CharT> operator*() const;

            iterator& operator++()
            {
                SCN_EXPECT(m_file);
                ++m_current;
                return *this;
            }
            iterator operator++(int)
            {
                iterator tmp(*this);
                operator++();
                return tmp;
            }

            iterator& operator--()
            {
                SCN_EXPECT(m_file);
                SCN_EXPECT(m_current > 0);

                m_last_error = error{};
                --m_current;

                return *this;
            }
            iterator operator--(int)
            {
                iterator tmp(*this);
                operator--();
                return tmp;
            }

            bool operator==(const iterator& o) const;

            bool operator!=(const iterator& o) const
            {
                return !operator==(o);
            }

            bool operator<(const iterator& o) const
            {
                // any valid iterator is before eof and null
                if (!m_file) {
                    return !o.m_file;
                }
                if (!o.m_file) {
                    return !m_file;
                }
                SCN_EXPECT(m_file == o.m_file);
                return m_current < o.m_current;
            }
            bool operator>(const iterator& o) const
            {
                return o.operator<(*this);
            }
            bool operator<=(const iterator& o) const
            {
                return !operator>(o);
            }
            bool operator>=(const iterator& o) const
            {
                return !operator<(o);
            }

            void reset_begin_iterator() const noexcept
            {
                m_current = 0;
            }

        private:
            friend class basic_file;

            iterator(const file_type& f, size_t i)
                : m_file{std::addressof(f)}, m_current{i}
            {
            }

            mutable error m_last_error{};
            const file_type* m_file{nullptr};
            mutable size_t m_current{0};
        };

        using sentinel = iterator;
        using char_type = CharT;

        /**
         * Construct an empty file.
         * Reading not possible: valid() is `false`
         */
        basic_file() = default;
        /**
         * Construct from a FILE*.
         * Must be a valid handle that can be read from.
         */
        basic_file(FILE* f) : m_file{f} {}

        basic_file(const basic_file&) = delete;
        basic_file& operator=(const basic_file&) = delete;

        basic_file(basic_file&& o) noexcept
            : m_buffer(detail::exchange(o.m_buffer, {})),
              m_file(detail::exchange(o.m_file, nullptr))
        {
        }
        basic_file& operator=(basic_file&& o) noexcept
        {
            if (valid()) {
                sync();
            }
            m_buffer = detail::exchange(o.m_buffer, {});
            m_file = detail::exchange(o.m_file, nullptr);
            return *this;
        }

        ~basic_file()
        {
            if (valid()) {
                _sync_all();
            }
        }

        /**
         * Get the FILE* for this range.
         * Only use this handle for reading sync() has been called and no
         * reading operations have taken place after that.
         *
         * \see sync
         */
        FILE* handle() const
        {
            return m_file;
        }

        /**
         * Reset the file handle.
         * Calls sync(), if necessary, before resetting.
         * @return The old handle
         */
        FILE* set_handle(FILE* f, bool allow_sync = true) noexcept
        {
            auto old = m_file;
            if (old && allow_sync) {
                sync();
            }
            m_file = f;
            return old;
        }

        /// Whether the file has been opened
        constexpr bool valid() const noexcept
        {
            return m_file != nullptr;
        }

        /**
         * Synchronizes this file with the underlying FILE*.
         * Invalidates all non-end iterators.
         * File must be open.
         *
         * Necessary for mixing-and-matching scnlib and <cstdio>:
         * \code{.cpp}
         * scn::scan(file, ...);
         * file.sync();
         * std::fscanf(file.handle(), ...);
         * \endcode
         *
         * Necessary for synchronizing result objects:
         * \code{.cpp}
         * auto result = scn::scan(file, ...);
         * // only result.range() can now be used for scanning
         * result = scn::scan(result.range(), ...);
         * // .sync() allows the original file to also be used
         * file.sync();
         * result = scn::scan(file, ...);
         * \endcode
         */
        void sync() noexcept
        {
            _sync_all();
            m_buffer.clear();
        }

        iterator begin() const noexcept
        {
            return {*this, 0};
        }
        sentinel end() const noexcept
        {
            return {};
        }

        span<const CharT> get_buffer(iterator it,
                                     size_t max_size) const noexcept
        {
            if (!it.m_file) {
                return {};
            }
            const auto begin =
                m_buffer.begin() + static_cast<std::ptrdiff_t>(it.m_current);
            const auto end_diff = detail::min(
                max_size,
                static_cast<size_t>(ranges::distance(begin, m_buffer.end())));
            return {begin, begin + static_cast<std::ptrdiff_t>(end_diff)};
        }

    private:
        friend class iterator;

        expected<CharT> _read_single() const;

        void _sync_all() noexcept
        {
            _sync_until(m_buffer.size());
        }
        void _sync_until(size_t pos) noexcept;

        CharT _get_char_at(size_t i) const
        {
            SCN_EXPECT(valid());
            SCN_EXPECT(i < m_buffer.size());
            return m_buffer[i];
        }

        bool _is_at_end(size_t i) const
        {
            SCN_EXPECT(valid());
            return i >= m_buffer.size();
        }

        mutable std::basic_string<CharT> m_buffer{};
        FILE* m_file{nullptr};
    };

    using file = basic_file<char>;
    using wfile = basic_file<wchar_t>;

    template <>
    expected<char> file::iterator::operator*() const;
    template <>
    expected<wchar_t> wfile::iterator::operator*() const;
    template <>
    bool file::iterator::operator==(const file::iterator&) const;
    template <>
    bool wfile::iterator::operator==(const wfile::iterator&) const;

    template <>
    expected<char> file::_read_single() const;
    template <>
    expected<wchar_t> wfile::_read_single() const;
    template <>
    void file::_sync_until(size_t) noexcept;
    template <>
    void wfile::_sync_until(size_t) noexcept;

    /**
     * A child class for basic_file, handling fopen, fclose, and lifetimes with
     * RAII.
     */
    template <typename CharT>
    class basic_owning_file : public basic_file<CharT> {
    public:
        using char_type = CharT;

        /// Open an empty file
        basic_owning_file() = default;
        /// Open a file, with fopen arguments
        basic_owning_file(const char* f, const char* mode)
            : basic_file<CharT>(std::fopen(f, mode))
        {
        }

        /// Steal ownership of a FILE*
        explicit basic_owning_file(FILE* f) : basic_file<CharT>(f) {}

        ~basic_owning_file()
        {
            if (is_open()) {
                close();
            }
        }

        /// fopen
        bool open(const char* f, const char* mode)
        {
            SCN_EXPECT(!is_open());

            auto h = std::fopen(f, mode);
            if (!h) {
                return false;
            }

            const bool is_wide = sizeof(CharT) > 1;
            auto ret = std::fwide(h, is_wide ? 1 : -1);
            if ((is_wide && ret > 0) || (!is_wide && ret < 0) || ret == 0) {
                this->set_handle(h);
                return true;
            }
            return false;
        }
        /// Steal ownership
        bool open(FILE* f)
        {
            SCN_EXPECT(!is_open());
            if (std::ferror(f) != 0) {
                return false;
            }
            this->set_handle(f);
            return true;
        }

        /// Close file
        void close()
        {
            SCN_EXPECT(is_open());
            this->sync();
            std::fclose(this->handle());
            this->set_handle(nullptr, false);
        }

        /// Is the file open
        SCN_NODISCARD bool is_open() const
        {
            return this->valid();
        }
    };

    using owning_file = basic_owning_file<char>;
    using owning_wfile = basic_owning_file<wchar_t>;

    SCN_CLANG_PUSH
    SCN_CLANG_IGNORE("-Wexit-time-destructors")

    // Avoid documentation issues: without this, Doxygen will think
    // SCN_CLANG_PUSH is a part of the stdin_range declaration
    namespace dummy {
    }

    /**
     * Get a reference to the global stdin range
     */
    template <typename CharT>
    basic_file<CharT>& stdin_range()
    {
        static auto f = basic_file<CharT>{stdin};
        return f;
    }
    /**
     * Get a reference to the global `char`-oriented stdin range
     */
    inline file& cstdin()
    {
        return stdin_range<char>();
    }
    /**
     * Get a reference to the global `wchar_t`-oriented stdin range
     */
    inline wfile& wcstdin()
    {
        return stdin_range<wchar_t>();
    }
    SCN_CLANG_POP

    SCN_END_NAMESPACE
}  // namespace scn

#if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY && !defined(SCN_FILE_CPP)
#include "file.cpp"
#endif

#endif  // SCN_DETAIL_FILE_H