GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
File.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_SYSTEM_FILE_HPP
5#define GREM_CORE_SYSTEM_FILE_HPP
6
8
9#include <GREM/core/Error.hpp>
23
24#include <utility> // std::move, std::forward
25
26namespace grem {
27
31class File {
32public:
37 struct Error : grem::Error {
39 };
40
44 enum class Kind : uint8_t {
49 };
50
54 struct Metadata {
55 size_t size;
56 int64_t creationTime;
60 bool readOnly;
61 };
62
66 static constexpr size_t npos = static_cast<size_t>(-1);
67
69 File() noexcept = default;
70
76 virtual ~File() = default;
77
79 File(const File&) = default;
80
82 File(File&&) noexcept = default;
83
85 File& operator=(const File&) = default;
86
88 File& operator=(File&&) noexcept = default;
89
95 explicit operator bool() const noexcept {
96 return isOpen();
97 }
98
110 virtual void close() = 0;
111
117 [[nodiscard]] virtual bool isOpen() const noexcept = 0;
118};
119
123class InputFile : public File {
124public:
126 InputFile() noexcept = default;
127
133 [[nodiscard]] GREM_ALWAYS_INLINE operator Reader() & {
134 return Reader{this, [](void* context, Span<byte> data) -> size_t { return static_cast<InputFile*>(context)->readUntilEOF(data); }};
135 }
136
142 [[nodiscard]] virtual bool eof() const noexcept = 0;
143
150 [[nodiscard]] virtual size_t size() const noexcept = 0;
151
158 [[nodiscard]] virtual size_t tellg() const noexcept = 0;
159
171 virtual void seekg(size_t position) = 0;
172
184 virtual void skipg(ptrdiff_t offset) = 0;
185
199 [[nodiscard]] virtual Allocation<byte> readBytesIntoAllocation(size_t maxLength = Limits<size_t>::MAX) = 0;
200
214 [[nodiscard]] virtual ArrayList<byte> readBytesIntoArrayList(size_t maxLength = Limits<size_t>::MAX) = 0;
215
229 [[nodiscard]] virtual Buffer<byte> readBytesIntoBuffer(size_t maxLength = Limits<size_t>::MAX) = 0;
230
244 [[nodiscard]] virtual String readBytesIntoString(size_t maxLength = Limits<size_t>::MAX) = 0;
245
259 [[nodiscard]] virtual Allocation<char> readBytesIntoCString(size_t maxLength = Limits<size_t>::MAX) = 0;
260
286 [[nodiscard]] virtual size_t readSome(Span<byte> data) = 0;
287
314 [[nodiscard]] virtual size_t readUntilEOF(Span<byte> data) = 0;
315
331 void read(Span<byte> data) {
332 if (!tryRead(data)) {
333 throw File::Error{"Unexpected end of file."};
334 }
335 }
336
355 [[nodiscard]] bool tryRead(Span<byte> data) {
356 return readUntilEOF(data) == data.size();
357 }
358};
359
364public:
377 template <typename Implementation, typename... Args>
378 [[nodiscard]] GREM_ALWAYS_INLINE static InputFileHandle create(Args&&... args) {
379 return InputFileHandle{UniquePointer<Implementation>::create(std::forward<Args>(args)...)};
380 }
381
385 InputFileHandle() noexcept = default;
386
392 [[nodiscard]] GREM_ALWAYS_INLINE InputFile* get() noexcept {
393 return file.get();
394 }
395
401 [[nodiscard]] GREM_ALWAYS_INLINE const InputFile* get() const noexcept {
402 return file.get();
403 }
404
412 [[nodiscard]] GREM_ALWAYS_INLINE operator InputFile&() {
413 return *file;
414 }
415
423 [[nodiscard]] GREM_ALWAYS_INLINE operator const InputFile&() const {
424 return *file;
425 }
426
434 [[nodiscard]] GREM_ALWAYS_INLINE operator Reader() & {
435 return *file;
436 }
437
439 GREM_ALWAYS_INLINE explicit operator bool() const noexcept {
440 return isOpen();
441 }
442
445 if (file) {
446 file->close();
447 file = {};
448 }
449 }
450
452 [[nodiscard]] GREM_ALWAYS_INLINE bool isOpen() const noexcept {
453 return file && file->isOpen();
454 }
455
457 [[nodiscard]] GREM_ALWAYS_INLINE bool eof() const noexcept {
458 return !file || file->eof();
459 }
460
462 [[nodiscard]] GREM_ALWAYS_INLINE size_t size() const noexcept {
463 return (file) ? file->size() : 0;
464 }
465
467 [[nodiscard]] GREM_ALWAYS_INLINE size_t tellg() const noexcept {
468 return (file) ? file->tellg() : 0;
469 }
470
472 GREM_ALWAYS_INLINE void seekg(size_t position) {
473 if (!file) {
474 throw File::Error{"Invalid file handle."};
475 }
476 file->seekg(position);
477 }
478
480 GREM_ALWAYS_INLINE void skipg(ptrdiff_t offset) {
481 if (!file) {
482 throw File::Error{"Invalid file handle."};
483 }
484 file->skipg(offset);
485 }
486
489 if (!file) {
490 throw File::Error{"Invalid file handle."};
491 }
492 return file->readBytesIntoAllocation(maxLength);
493 }
494
497 if (!file) {
498 throw File::Error{"Invalid file handle."};
499 }
500 return file->readBytesIntoArrayList(maxLength);
501 }
502
505 if (!file) {
506 throw File::Error{"Invalid file handle."};
507 }
508 return file->readBytesIntoBuffer(maxLength);
509 }
510
513 if (!file) {
514 throw File::Error{"Invalid file handle."};
515 }
516 return file->readBytesIntoString(maxLength);
517 }
518
521 if (!file) {
522 throw File::Error{"Invalid file handle."};
523 }
524 return file->readBytesIntoCString(maxLength);
525 }
526
528 [[nodiscard]] GREM_ALWAYS_INLINE size_t readSome(Span<byte> data) {
529 if (!file) {
530 throw File::Error{"Invalid file handle."};
531 }
532 return file->readSome(data);
533 }
534
536 [[nodiscard]] GREM_ALWAYS_INLINE size_t readUntilEOF(Span<byte> data) {
537 if (!file) {
538 throw File::Error{"Invalid file handle."};
539 }
540 return file->readUntilEOF(data);
541 }
542
545 if (!file) {
546 throw File::Error{"Invalid file handle."};
547 }
548 file->read(data);
549 }
550
552 [[nodiscard]] GREM_ALWAYS_INLINE bool tryRead(Span<byte> data) {
553 if (!file) {
554 throw File::Error{"Invalid file handle."};
555 }
556 return file->tryRead(data);
557 }
558
559private:
560 explicit InputFileHandle(UniquePointer<InputFile> file) noexcept
561 : file(std::move(file)) {}
562
563 UniquePointer<InputFile> file{};
564};
565
569class OutputFile : public File {
570public:
572 OutputFile() noexcept = default;
573
579 [[nodiscard]] GREM_ALWAYS_INLINE operator Writer() & {
580 return Writer{
581 this,
582 [](void* context, Span<const byte> data, bool thenFlush) -> size_t {
583 OutputFile& output = *static_cast<OutputFile*>(context);
584 const size_t bytesWritten = output.writeSome(data);
585 if (thenFlush) {
586 output.flush();
587 }
588 return bytesWritten;
589 },
590 };
591 }
592
599 [[nodiscard]] virtual size_t tellp() const noexcept = 0;
600
612 virtual void seekp(size_t position) = 0;
613
625 virtual void skipp(ptrdiff_t offset) = 0;
626
642 [[nodiscard]] virtual size_t writeSome(Span<const byte> data) = 0;
643
654 void write(Span<const byte> data) {
655 while (!data.empty()) {
656 data = data.subspan(writeSome(data));
657 }
658 }
659
670 void write(StringView string) {
671 write(asBytes(Span{string}));
672 }
673
680 virtual void flush() = 0;
681};
682
687public:
700 template <typename Implementation, typename... Args>
701 [[nodiscard]] GREM_ALWAYS_INLINE static OutputFileHandle create(Args&&... args) {
702 return OutputFileHandle{UniquePointer<Implementation>::create(std::forward<Args>(args)...)};
703 }
704
708 OutputFileHandle() noexcept = default;
709
717 [[nodiscard]] GREM_ALWAYS_INLINE operator Writer() & {
718 return *file;
719 }
720
726 [[nodiscard]] GREM_ALWAYS_INLINE OutputFile* get() noexcept {
727 return file.get();
728 }
729
735 [[nodiscard]] GREM_ALWAYS_INLINE const OutputFile* get() const noexcept {
736 return file.get();
737 }
738
746 [[nodiscard]] GREM_ALWAYS_INLINE operator OutputFile&() {
747 return *file;
748 }
749
757 [[nodiscard]] GREM_ALWAYS_INLINE operator const OutputFile&() const {
758 return *file;
759 }
760
762 GREM_ALWAYS_INLINE explicit operator bool() const noexcept {
763 return isOpen();
764 }
765
768 if (file) {
769 file->close();
770 file = {};
771 }
772 }
773
775 [[nodiscard]] GREM_ALWAYS_INLINE bool isOpen() const noexcept {
776 return file && file->isOpen();
777 }
778
780 [[nodiscard]] GREM_ALWAYS_INLINE size_t tellp() const noexcept {
781 return (file) ? file->tellp() : 0;
782 }
783
785 GREM_ALWAYS_INLINE void seekp(size_t position) {
786 if (!file) {
787 throw File::Error{"Invalid file handle."};
788 }
789 file->seekp(position);
790 }
791
793 GREM_ALWAYS_INLINE void skipp(ptrdiff_t offset) {
794 if (!file) {
795 throw File::Error{"Invalid file handle."};
796 }
797 file->skipp(offset);
798 }
799
801 [[nodiscard]] GREM_ALWAYS_INLINE size_t writeSome(Span<const byte> data) {
802 if (!file) {
803 throw File::Error{"Invalid file handle."};
804 }
805 return file->writeSome(data);
806 }
807
810 if (!file) {
811 throw File::Error{"Invalid file handle."};
812 }
813 file->write(data);
814 }
815
818 if (!file) {
819 throw File::Error{"Invalid file handle."};
820 }
821 file->write(data);
822 }
823
826 if (!file) {
827 throw File::Error{"Invalid file handle."};
828 }
829 file->flush();
830 }
831
832private:
833 explicit OutputFileHandle(UniquePointer<OutputFile> file) noexcept
834 : file(std::move(file)) {}
835
836 UniquePointer<OutputFile> file{};
837};
838
839} // namespace grem
840
841#endif
#define GREM_ALWAYS_INLINE
Definition attributes.hpp:10
Definition Allocation.hpp:25
Definition ArrayList.hpp:27
Definition Buffer.hpp:28
Base exception type for runtime errors.
Definition Error.hpp:38
Error(CStringView message)
Definition Error.hpp:55
static constexpr size_t npos
Invalid value for a file offset, used as an end-of-file marker.
Definition File.hpp:66
virtual bool isOpen() const noexcept=0
Check if the file handle has an open file associated with it.
Kind
File entry type.
Definition File.hpp:44
@ OTHER
Something else, such as a network socket or a device.
Definition File.hpp:48
@ SYMLINK
Symbolic link.
Definition File.hpp:47
@ DIRECTORY
Directory/folder.
Definition File.hpp:46
@ REGULAR
Regular file.
Definition File.hpp:45
virtual void close()=0
Close the associated file so that it can no longer be accessed through this handle,...
File() noexcept=default
Default constructor.
Generic boxed unique handle to a readable file in any filesystem.
Definition File.hpp:363
GREM_ALWAYS_INLINE void close()
Close the associated file so that it can no longer be accessed through this handle,...
Definition File.hpp:444
GREM_ALWAYS_INLINE size_t tellg() const noexcept
Get the current reading position of the file.
Definition File.hpp:467
GREM_ALWAYS_INLINE bool tryRead(Span< byte > data)
Try to read an exact amount of data from an open file, starting at the current reading position.
Definition File.hpp:552
GREM_ALWAYS_INLINE void seekg(size_t position)
Set the file reading position to an absolute offset from the beginning of the file.
Definition File.hpp:472
GREM_ALWAYS_INLINE const InputFile * get() const noexcept
Get a pointer to the underlying file interface.
Definition File.hpp:401
InputFileHandle() noexcept=default
Construct a null file handle without an associated file.
GREM_ALWAYS_INLINE void read(Span< byte > data)
Read an exact amount of data from an open file, starting at the current reading position.
Definition File.hpp:544
GREM_ALWAYS_INLINE size_t size() const noexcept
Get the readable length of the full file contents, in bytes.
Definition File.hpp:462
GREM_ALWAYS_INLINE Allocation< char > readBytesIntoCString(size_t maxLength=Limits< size_t >::MAX)
Read from an open file into an allocated null-terminated string of bytes.
Definition File.hpp:520
GREM_ALWAYS_INLINE void skipg(ptrdiff_t offset)
Advance the file reading position by a relative offset, which may be negative in order to go backward...
Definition File.hpp:480
static GREM_ALWAYS_INLINE InputFileHandle create(Args &&... args)
Create a boxed file with a specific implementation.
Definition File.hpp:378
GREM_ALWAYS_INLINE String readBytesIntoString(size_t maxLength=Limits< size_t >::MAX)
Read from an open file into a string of bytes.
Definition File.hpp:512
GREM_ALWAYS_INLINE size_t readUntilEOF(Span< byte > data)
Read data from an open file into a buffer, starting at the current reading position.
Definition File.hpp:536
GREM_ALWAYS_INLINE size_t readSome(Span< byte > data)
Read some amount of data from an open file, starting at the current reading position.
Definition File.hpp:528
GREM_ALWAYS_INLINE InputFile * get() noexcept
Get a pointer to the underlying file interface.
Definition File.hpp:392
GREM_ALWAYS_INLINE Allocation< byte > readBytesIntoAllocation(size_t maxLength=Limits< size_t >::MAX)
Read from an open file into an allocation of bytes.
Definition File.hpp:488
GREM_ALWAYS_INLINE bool eof() const noexcept
Check if the end of the file has been reached.
Definition File.hpp:457
GREM_ALWAYS_INLINE Buffer< byte > readBytesIntoBuffer(size_t maxLength=Limits< size_t >::MAX)
Read from an open file into a buffer of bytes.
Definition File.hpp:504
GREM_ALWAYS_INLINE bool isOpen() const noexcept
Check if the file handle has an open file associated with it.
Definition File.hpp:452
GREM_ALWAYS_INLINE ArrayList< byte > readBytesIntoArrayList(size_t maxLength=Limits< size_t >::MAX)
Read from an open file into an array list of bytes.
Definition File.hpp:496
Base interface for a readable File in a Filesystem.
Definition File.hpp:123
virtual size_t size() const noexcept=0
Get the readable length of the full file contents, in bytes.
void read(Span< byte > data)
Read an exact amount of data from an open file, starting at the current reading position.
Definition File.hpp:331
virtual void seekg(size_t position)=0
Set the file reading position to an absolute offset from the beginning of the file.
virtual Allocation< byte > readBytesIntoAllocation(size_t maxLength=Limits< size_t >::MAX)=0
Read from an open file into an allocation of bytes.
bool tryRead(Span< byte > data)
Try to read an exact amount of data from an open file, starting at the current reading position.
Definition File.hpp:355
virtual Buffer< byte > readBytesIntoBuffer(size_t maxLength=Limits< size_t >::MAX)=0
Read from an open file into a buffer of bytes.
virtual size_t readUntilEOF(Span< byte > data)=0
Read data from an open file into a buffer, starting at the current reading position.
virtual String readBytesIntoString(size_t maxLength=Limits< size_t >::MAX)=0
Read from an open file into a string of bytes.
virtual size_t tellg() const noexcept=0
Get the current reading position of the file.
InputFile() noexcept=default
Default constructor.
virtual bool eof() const noexcept=0
Check if the end of the file has been reached.
virtual Allocation< char > readBytesIntoCString(size_t maxLength=Limits< size_t >::MAX)=0
Read from an open file into an allocated null-terminated string of bytes.
virtual ArrayList< byte > readBytesIntoArrayList(size_t maxLength=Limits< size_t >::MAX)=0
Read from an open file into an array list of bytes.
virtual void skipg(ptrdiff_t offset)=0
Advance the file reading position by a relative offset, which may be negative in order to go backward...
virtual size_t readSome(Span< byte > data)=0
Read some amount of data from an open file, starting at the current reading position.
Generic boxed unique handle to a writable file in any filesystem.
Definition File.hpp:686
GREM_ALWAYS_INLINE void seekp(size_t position)
Set the file writing position to an absolute offset from the beginning of the file.
Definition File.hpp:785
GREM_ALWAYS_INLINE bool isOpen() const noexcept
Check if the file handle has an open file associated with it.
Definition File.hpp:775
static GREM_ALWAYS_INLINE OutputFileHandle create(Args &&... args)
Create a boxed file with a specific implementation.
Definition File.hpp:701
GREM_ALWAYS_INLINE const OutputFile * get() const noexcept
Get a pointer to the underlying file interface.
Definition File.hpp:735
GREM_ALWAYS_INLINE size_t writeSome(Span< const byte > data)
Write data to the end of an open file from a buffer.
Definition File.hpp:801
GREM_ALWAYS_INLINE void skipp(ptrdiff_t offset)
Advance the file writing position by a relative offset, which may be negative in order to go backward...
Definition File.hpp:793
GREM_ALWAYS_INLINE void close()
Close the associated file so that it can no longer be accessed through this handle,...
Definition File.hpp:767
GREM_ALWAYS_INLINE void write(StringView data)
Write data to the end of an open file.
Definition File.hpp:817
GREM_ALWAYS_INLINE size_t tellp() const noexcept
Get the current writing position of the file.
Definition File.hpp:780
GREM_ALWAYS_INLINE OutputFile * get() noexcept
Get a pointer to the underlying file interface.
Definition File.hpp:726
GREM_ALWAYS_INLINE void flush()
Synchronize with the underlying file to make sure that all buffered data that has been written so far...
Definition File.hpp:825
GREM_ALWAYS_INLINE void write(Span< const byte > data)
Write data to the end of an open file.
Definition File.hpp:809
OutputFileHandle() noexcept=default
Construct a null file handle without an associated file.
Base interface for a writable file in a Filesystem.
Definition File.hpp:569
virtual void seekp(size_t position)=0
Set the file writing position to an absolute offset from the beginning of the file.
void write(Span< const byte > data)
Write data to the end of an open file.
Definition File.hpp:654
virtual void skipp(ptrdiff_t offset)=0
Advance the file writing position by a relative offset, which may be negative in order to go backward...
virtual void flush()=0
Synchronize with the underlying file to make sure that all buffered data that has been written so far...
virtual size_t tellp() const noexcept=0
Get the current writing position of the file.
OutputFile() noexcept=default
Default constructor.
virtual size_t writeSome(Span< const byte > data)=0
Write data to the end of an open file from a buffer.
void write(StringView string)
Write data from a string to the end of an open file.
Definition File.hpp:670
Definition Reader.hpp:658
Definition Span.hpp:146
constexpr size_type size() const noexcept
Definition Span.hpp:207
Nullable RAII data pointer with exclusive ownership of an object that is automatically destroyed on p...
Definition UniquePointer.hpp:77
static constexpr UniquePointer create(Args &&... args)
Allocate and construct an object of the associated type and wrap it in a pointer with unique ownershi...
Definition UniquePointer.hpp:101
Definition Writer.hpp:217
Definition aliases.hpp:9
StringBase< char, std::char_traits< char >, std::allocator< char > > String
Definition String.hpp:17
StringViewBase< char, std::char_traits< char > > StringView
Definition StringView.hpp:16
auto asBytes(Span< T, N > s) noexcept
Definition Span.hpp:359
Exception type for errors that may arise when attempting to access files through the File API.
Definition File.hpp:37
Error(CStringView message)
Definition Error.hpp:55
Record of metadata for a specific file.
Definition File.hpp:54
int64_t lastAccessTime
Last time when the file was accessed, in seconds since the Unix epoch (1970-01-01 00:00),...
Definition File.hpp:57
bool readOnly
True if the file may only be opened for reading, false if it may also be opened for writing or append...
Definition File.hpp:60
int64_t lastModificationTime
Last time when the file was modified, in seconds since the Unix epoch (1970-01-01 00:00),...
Definition File.hpp:58
Kind kind
Kind of file, such as regular file or directory.
Definition File.hpp:59
int64_t creationTime
Time when the file was created, in seconds since the Unix epoch (1970-01-01 00:00),...
Definition File.hpp:56
size_t size
File size, in bytes, or npos if unavailable.
Definition File.hpp:55
Definition fundamentals.hpp:27
static constexpr T MAX
Definition fundamentals.hpp:29