Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games. 2 : * 3 : * Permission is hereby granted, free of charge, to any person obtaining 4 : * a copy of this software and associated documentation files (the 5 : * "Software"), to deal in the Software without restriction, including 6 : * without limitation the rights to use, copy, modify, merge, publish, 7 : * distribute, sublicense, and/or sell copies of the Software, and to 8 : * permit persons to whom the Software is furnished to do so, subject to 9 : * the following conditions: 10 : * 11 : * The above copyright notice and this permission notice shall be included 12 : * in all copies or substantial portions of the Software. 13 : * 14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 : */ 22 : 23 : #ifndef INCLUDED_WRITE_BUFFER 24 : #define INCLUDED_WRITE_BUFFER 25 : 26 : #include "lib/code_annotation.h" 27 : #include "lib/file/file.h" 28 : #include "lib/posix/posix_types.h" 29 : #include "lib/status.h" 30 : 31 : #include <cstddef> 32 : #include <memory> 33 : 34 15626 : class WriteBuffer 35 : { 36 : public: 37 : WriteBuffer(); 38 : 39 : void Append(const void* data, size_t size); 40 : void Reserve(size_t size); 41 : void Overwrite(const void* data, size_t size, size_t offset); 42 : 43 7812 : std::shared_ptr<std::uint8_t> Data() const 44 : { 45 7812 : return m_data; 46 : } 47 : 48 460342 : size_t Size() const 49 : { 50 452535 : return m_size; 51 : } 52 : 53 : private: 54 : void EnsureSufficientCapacity(size_t size); 55 : 56 : size_t m_capacity; // must come first (init order) 57 : 58 : std::shared_ptr<std::uint8_t> m_data; 59 : size_t m_size; 60 : }; 61 : 62 : 63 : class UnalignedWriter 64 : { 65 : NONCOPYABLE(UnalignedWriter); 66 : public: 67 : UnalignedWriter(const PFile& file, off_t ofs); 68 : ~UnalignedWriter(); 69 : 70 : /** 71 : * add data to the align buffer, writing it out to disk if full. 72 : **/ 73 : Status Append(const std::uint8_t* data, size_t size) const; 74 : 75 : /** 76 : * zero-initialize any remaining space in the align buffer and write 77 : * it to the file. this is called by the destructor. 78 : **/ 79 : void Flush() const; 80 : 81 : private: 82 : Status WriteBlock() const; 83 : 84 : PFile m_file; 85 : std::shared_ptr<std::uint8_t> m_alignedBuf; 86 : mutable off_t m_alignedOfs; 87 : mutable size_t m_bytesUsed; 88 : }; 89 : 90 : typedef std::shared_ptr<UnalignedWriter> PUnalignedWriter; 91 : 92 : #endif // #ifndef INCLUDED_WRITE_BUFFER