File: MemoryMappedConnection.h

package info (click to toggle)
r-cran-sourcetools 0.1.7-1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 308 kB
  • sloc: cpp: 1,985; ansic: 505; sh: 10; makefile: 2
file content (55 lines) | stat: -rw-r--r-- 1,085 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#ifndef SOURCETOOLS_READ_POSIX_MEMORY_MAPPED_CONNECTION_H
#define SOURCETOOLS_READ_POSIX_MEMORY_MAPPED_CONNECTION_H

#include <cstdlib>
#include <fcntl.h>
#include <sys/mman.h>

#include <sourcetools/platform/platform.h>

namespace sourcetools {
namespace detail {

class MemoryMappedConnection
{
public:

  MemoryMappedConnection(int fd, std::size_t size)
    : size_(size)
  {
#ifdef MAP_POPULATE
    map_ = (char*) ::mmap(0, size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);
#else
    map_ = (char*) ::mmap(0, size, PROT_READ, MAP_SHARED, fd, 0);
#endif

#if defined(POSIX_MADV_SEQUENTIAL) && defined(POSIX_MADV_WILLNEED)
    ::posix_madvise((void*) map_, size, POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED);
#endif
  }

  ~MemoryMappedConnection()
  {
    if (map_ != MAP_FAILED)
      ::munmap(map_, size_);
  }

  bool open()
  {
    return map_ != MAP_FAILED;
  }

  operator char*() const
  {
    return map_;
  }

private:
  char* map_;
  std::size_t size_;
};

} // namespace detail
} // namespace sourcetools

#endif /* SOURCETOOLS_READ_POSIX_MEMORY_MAPPED_CONNECTION_H */