MappedFile.h
author František Kučera <franta-hg@frantovo.cz>
Tue, 26 Dec 2023 23:46:45 +0100
branchv_0
changeset 28 4cbd9c0beb4c
parent 0 bb715a82a8f1
child 34 8cf3812a92eb
permissions -rw-r--r--
pass texture xattr 'shader-shark.texture.scale' to the shaders as 'uTextureScale' + update variable locations on each shader reload

/**
 * 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;

};