MappedFile.h
author František Kučera <franta-hg@frantovo.cz>
Thu, 28 Dec 2023 00:37:59 +0100
branchv_0
changeset 35 dcb2ad86e23c
parent 29 dc3c102e1264
permissions -rw-r--r--
add undocumented option: --dpi

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

};