ALib C++ Framework
by
Library Version: 2605 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
mappedfile.hpp
Go to the documentation of this file.
1//==================================================================================================
2/// \file
3/// This header-file is part of the \aliblong.
4///
5/// Copyright 2013-2026 A-Worx GmbH, Germany.
6/// Published under #"mainpage_license".
7//==================================================================================================
8ALIB_EXPORT namespace alib { namespace system {
9
10/// File-to-memory loader with optional mmap backend.
11/// This class loads a file into memory and provides a stable pointer + length, which is only
12/// allowed to be read sequentially.
13///
14/// ### Backend options: ###
15/// - <b>mmap</b>-mapping where supported.
16/// - Portable "read-all" into an internal buffer (always available, i.e on WindowsOS).
18 public:
19 /// A minimal sequential-only cursor over the file data.
20 /// Enforces the "forward-only" usage pattern in calling code.
21 /// @tparam T The data type to sequentially load from this cursor.
22 template<typename T>
23 class Data {
24 protected:
25 const T* start; ///< Current pointer position.
26 const T* end; ///< Pointer to the end of the data.
27
28 public:
29 /// Defaulted default-constructor.
30 Data() : start(nullptr), end(nullptr) {}
31
32 /// Constructor.
33 /// @param pStart Pointer to the start of the data.
34 /// @param length The length of the data.
35 Data(const void* pStart, size_t length)
36 : start(static_cast<const T*>(pStart))
37 , end (static_cast<const T*>(pStart) + length/sizeof(T)) {
38 ALIB_ASSERT_ERROR((reinterpret_cast<size_t>(start) & (alignof(T) - 1)) == 0,
39 "SYSTEM", "MappedFile::Data: start pointer is not aligned to T.")
40 ALIB_ASSERT_ERROR((length % sizeof(T)) == 0,
41 "SYSTEM", "MappedFile::Data: byte length is not a multiple of sizeof(T).")
42 ALIB_ASSERT_ERROR((reinterpret_cast<size_t>(end) & (alignof(T) - 1)) == 0,
43 "SYSTEM", "MappedFile::Data: end pointer is not aligned to T.")
44 }
45
46 /// Remaining value.
47 /// @return The number of bytes from current position to end.
48 integer Remaining() const noexcept
49 { return integer( ( end - start ) / std::ptrdiff_t(sizeof(T))); }
50
51 /// True if at end.
52 /// @return \c true if the current position reached #".end", \c false otherwise.
53 bool IsEOF() const noexcept { return start >= end; }
54
55 /// Get the next value and advance.
56 /// @tparam TCheck Defaults to #"alib::CHK;2", which is the normal invocation mode.
57 /// If #"alib::NC;2" is given, no range check is performed.
58 /// In debug builds, an assertion is raised if the cursor is at end.
59 /// @return The value at current position.
60 template <typename TCheck = alib::CHK>
61 T Next() {
62 if constexpr ( TCheck::value ) {
63 if (start>= end)
64 return T{0};
65 } else
66 ALIB_ASSERT_ERROR( start < end, "SYSTEM", "MappedFile::Data::Next: overflow." )
67 return *start++;
68 }
69
70 /// Shortcut to method #".Next".
71 /// @tparam TCheck Defaults to #"alib::CHK;2", which is the normal invocation mode.
72 /// If #"alib::NC;2" is given, no range check is performed.
73 /// In debug builds, an assertion is raised if the cursor is at end.
74 /// @return The value at current position.
75 template <typename TCheck = alib::CHK>
76 T operator ()() { return Next(); }
77
78 /// Get a pointer to the current position (read-only).
79 /// @return Pointer to current position.
80 const T Current() const noexcept { return *start; }
81
82 /// Same as #".Current".
83 /// @return Pointer to current position.
84 const T operator*() const noexcept { return *start; }
85
86 /// Advance by n values (must stay within range).
87 /// @param n Number of values to advance.
88 /// @tparam TIntegral The type of the parameter \p{n}.
89 template <typename TIntegral>
90 requires std::integral<TIntegral>
91 void Skip(TIntegral n) { start+=n; }
92
93 /// Clones this object to represent values of template type \p{U}.
94 /// @tparam U The type of the cloned data instance
95 /// @return A clone of this instance.
96 template <typename U>
97 Data<U> Clone() const noexcept
98 { return Data<U>(start, size_t(end - start) * sizeof(T)); }
99 };
100
101 protected:
102 std::size_t size = 0; ///< Size of the loaded data.
103 std::vector<std::max_align_t> noMMapBuf; ///< Internal buffer used for fallback read mode.
104 #if defined(_POSIX_MAPPED_FILES) && _POSIX_MAPPED_FILES > 0
105 void* mapAddr = nullptr; ///< Address of the memory-mapped region.
106 #endif
107
108 public:
109 /// Default constructor. Creates an empty view.
110 MappedFile() =default;
111
112 MappedFile(const MappedFile&) = delete; ///< Deleted copy constructor.
113 MappedFile(MappedFile&&) = delete; ///< Deleted move constructor.
114 MappedFile& operator=(const MappedFile&)= delete; ///< Deleted copy assignment operator.
115 MappedFile& operator=(MappedFile&& ) = delete; ///< Deleted assignment operator.
116 ///< @return Void (deleted).
117 ~MappedFile() { Close(); } ///< Destructor. Calls #".Close".
118
119 /// Load a file (replaces previous contents).
120 /// @param path The file's path.
121 /// @param knownSize File size in bytes if known. Defaults to \c max() , which
122 /// triggers size detection.
123 /// @param disableMMap If \c true, skips \e mmap mode and uses standard read methods.
124 /// Defaults to \c false.
125 /// @param willNeed If \c true (the default), \b MADV_WILLNEED is passed to the function
126 /// <c>::madvise</c>. Otherwise \b MADV_SEQUENTIAL is passed.
127 /// @throws std::runtime_error on failure to open/read/map the file.
128 /// @return The error code of the operation.
129 std::errc Open( const CPathString& path,
130 std::size_t knownSize = (std::numeric_limits<std::size_t>::max)(),
131 bool disableMMap= false,
132 bool willNeed = true );
133
134 /// Release resources (unmap / free buffer).
135 void Close() noexcept;
136
137 /// @return \c true if the file was read with \e mmap mode, \c false otherwise.
138 bool IsMMap() const noexcept {
139 #if defined(_POSIX_MAPPED_FILES) && _POSIX_MAPPED_FILES > 0
140 return mapAddr != nullptr;
141 #else
142 return false;
143 #endif
144 }
145
146 /// Returns a data-cursor for sequential read operations of the buffer.
147 /// @tparam T The data type to sequentially load from this cursor.
148 /// @return The data-cursor.
149 template<typename T>
150 Data<T> GetData() const noexcept {
151 static_assert( alignof(T) <= alignof(std::max_align_t),
152 "MappedFile fallback buffer cannot guarantee this over-alignment." );
153 #if defined(_POSIX_MAPPED_FILES) && _POSIX_MAPPED_FILES > 0
154 return Data<T>(mapAddr ? mapAddr : noMMapBuf.data(), size);
155 #else
156 return Data<T>(noMMapBuf.data(), size);
157 #endif
158 }
159
160 /// @return File size in bytes.
161 std::size_t Size() const noexcept { return size; }
162
163 /// @return \c true if the view is empty.
164 bool IsEmpty() const noexcept { return size == 0; }
165};
166
167
168
169} // namespace alib[::system]
170
171/// Type alias in namespace #"%alib".
173
174} // namespace [alib]
#define ALIB_EXPORT
#define ALIB_ASSERT_ERROR(cond, domain,...)
const T operator*() const noexcept
Data(const void *pStart, size_t length)
Data< U > Clone() const noexcept
const T * end
Pointer to the end of the data.
Data()
Defaulted default-constructor.
integer Remaining() const noexcept
bool IsEOF() const noexcept
const T * start
Current pointer position.
const T Current() const noexcept
MappedFile & operator=(MappedFile &&)=delete
MappedFile()=default
Default constructor. Creates an empty view.
MappedFile(MappedFile &&)=delete
Deleted move constructor.
~MappedFile()
Destructor. Calls #".Close".
void Close() noexcept
Release resources (unmap / free buffer).
std::size_t Size() const noexcept
MappedFile(const MappedFile &)=delete
Deleted copy constructor.
bool IsEmpty() const noexcept
bool IsMMap() const noexcept
std::size_t size
Size of the loaded data.
MappedFile & operator=(const MappedFile &)=delete
Deleted copy assignment operator.
std::vector< std::max_align_t > noMMapBuf
Internal buffer used for fallback read mode.
std::errc Open(const CPathString &path, std::size_t knownSize=(std::numeric_limits< std::size_t >::max)(), bool disableMMap=false, bool willNeed=true)
Definition mappedfile.cpp:9
Data< T > GetData() const noexcept
Definition alox.cpp:14
lang::integer integer
Type alias in namespace #"%alib".
Definition integers.hpp:149
strings::TCString< PathCharType > CPathString
The string-type used with this ALib Module.
Definition path.hpp:37
system::MappedFile MappedFile
Type alias in namespace #"%alib".