MappedFile.h
branchv_0
changeset 0 bb715a82a8f1
child 29 dc3c102e1264
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/MappedFile.h	Sun Nov 26 16:27:50 2023 +0100
@@ -0,0 +1,57 @@
+/**
+ * ShaderShark
+ * Copyright © 2023 František Kučera (Frantovo.cz, GlobalCode.info)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, version 3 of the License.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#pragma once
+
+#include <sys/mman.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+
+#include "Buffer.h"
+
+class MappedFile : public Buffer {
+private:
+	int fd = -1;
+public:
+
+	MappedFile(const std::string& fileName) {
+		struct stat stat;
+		fd = open(fileName.c_str(), O_RDONLY);
+		if (fd < 0) throw std::invalid_argument("unable to open file");
+
+		int result = fstat(fd, &stat);
+		if (result) throw std::invalid_argument("unable to stat file");
+
+		size = stat.st_size;
+		data = static_cast<char*> (
+				mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0));
+		if (data == MAP_FAILED) throw std::invalid_argument("unable to mmap");
+		// std::cerr << "MappedFile() / mmap()" << std::endl;
+	}
+
+	virtual ~MappedFile() {
+		int result = munmap(data, size);
+		// std::cerr << "~MappedFile() / munmap() = " << result << std::endl;
+		result = close(fd);
+		// std::cerr << "~MappedFile() / close() = " << result << std::endl;
+	}
+
+	MappedFile(const MappedFile&) = delete;
+	MappedFile& operator=(const MappedFile&) = delete;
+
+};