Last active
April 3, 2016 14:47
-
-
Save satoruhiga/4319632 to your computer and use it in GitHub Desktop.
Mmap.hpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <sys/stat.h> | |
#include "ofMain.h" | |
class Mmap | |
{ | |
public: | |
enum Mode | |
{ | |
READ_ONLY, | |
READ_WRITE | |
}; | |
Mmap() : ptr_(NULL), fd_(-1), size_(0), mode_(READ_ONLY) {} | |
Mmap(string path, Mode mode = READ_ONLY) : ptr_(NULL), fd_(-1), size_(0), mode_(mode) | |
{ | |
open(path, mode); | |
} | |
~Mmap() | |
{ | |
sync(); | |
close(); | |
} | |
void open(string path, Mode mode = READ_ONLY) | |
{ | |
int open_mode; | |
path = ofToDataPath(path); | |
mode_ = mode; | |
if (mode_ == READ_ONLY) | |
fd_ = ::open(path.c_str(), O_RDONLY); | |
else | |
fd_ = ::open(path.c_str(), O_RDWR | O_CREAT, 0666); | |
assert(fd_ != -1); | |
size_ = getFileSize(); | |
map(); | |
} | |
void close() | |
{ | |
unmap(); | |
if (fd_ != -1) | |
{ | |
::close(fd_); | |
fd_ = -1; | |
} | |
} | |
void sync() | |
{ | |
if (ptr_) msync(ptr_, size_, 0); | |
} | |
void resize(size_t size) | |
{ | |
unmap(); | |
this->size_ = size; | |
ftruncate(fd_, size_); | |
map(); | |
} | |
size_t size() const { return size_; } | |
void* get() { return ptr_; } | |
private: | |
int fd_; | |
size_t size_; | |
void *ptr_; | |
Mode mode_; | |
Mmap(const Mmap&); | |
Mmap& operator=(const Mmap); | |
size_t getFileSize() | |
{ | |
assert(fd_ != -1); | |
struct stat s; | |
fstat(fd_, &s); | |
return s.st_size; | |
} | |
void map() | |
{ | |
unmap(); | |
int prot = PROT_READ; | |
int frags = MAP_FILE | MAP_SHARED; | |
if (mode_ == READ_WRITE) | |
{ | |
prot |= PROT_WRITE; | |
} | |
ptr_ = mmap(NULL, size_, prot, frags, fd_, 0); | |
assert(ptr_ != NULL); | |
} | |
void unmap() | |
{ | |
if (ptr_ == NULL) return; | |
munmap(ptr_, size_); | |
ptr_ = NULL; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment