wibble  1.1
mmap_v2.h
Go to the documentation of this file.
1 // -*- C++ -*- (c) 2013 Vladimír Štill <xstill@fi.muni.cz>
2 /* mmap support using C++11
3  *
4  * mmaped file can be shared accross threads without memory overhead,
5  * but obviously it is not therad safe. It has shared_ptr semantics.
6  *
7  * redistributable under BSD licence
8  */
9 
10 #if __cplusplus < 201103L
11 #error "mmap_v2 is only supported with c++11 or newer"
12 #endif
13 
14 #include <wibble/strongenumflags.h>
15 
16 #include <memory>
17 #include <string>
18 
19 #ifndef WIBBLE_SYS_MMAP_V2
20 #define WIBBLE_SYS_MMAP_V2
21 
22 namespace wibble {
23 namespace sys {
24 inline namespace v2 {
25 
26 struct MMap
27 {
28  enum class ProtectMode {
29  Read = 0x1, Write = 0x2, Execute = 0x4,
30  Shared = 0x8, Private = 0x10
31  };
32 #define DEFAULT_MODE (ProtectMode::Read | ProtectMode::Shared)
34 
35  constexpr const static ProtectModeFlags defaultMode = DEFAULT_MODE;
36 
37  MMap() : _size( 0 ) { }
38  MMap( const std::string &, ProtectModeFlags = DEFAULT_MODE );
39  MMap( int fd, ProtectModeFlags );
40 
41  void map( const std::string &, ProtectModeFlags = DEFAULT_MODE );
42  void map( int fd, ProtectModeFlags = DEFAULT_MODE );
43  void unmap();
44 
45 #undef DEFAULT_MODE
46 
47  size_t size() { return _size; }
48  explicit operator bool() { return bool( _ptr ); }
49  bool valid() { return bool( _ptr ); }
50  ProtectModeFlags mode() { return _flags; }
51 
52  // get value on begining offset bites
53  template< typename T >
54  T &get( size_t offset ) {
55  return *reinterpret_cast< T * >(
56  reinterpret_cast< char * >( _ptr.get() ) + offset );
57  }
58 
59  template< typename T >
60  const T &cget( size_t offset ) const {
61  return *reinterpret_cast< T * >(
62  reinterpret_cast< char * >( _ptr.get() ) + offset );
63  }
64 
65  template< typename T >
66  const T &get( size_t offset ) const { return cget< T >( offset ); }
67 
68  template< typename T >
69  T *asArrayOf() {
70  return reinterpret_cast< T * >( _ptr.get() );
71  }
72 
73  template< typename T >
74  const T *asConstArrayOf() const {
75  return reinterpret_cast< const T * >( _ptr.get() );
76  }
77 
78  template< typename T >
79  const T *asArrayOf() const {
80  return asConstArrayOf< T >();
81  }
82 
83  char &operator[]( size_t offset ) {
84  return asArrayOf< char >()[ offset ];
85  }
86 
87  const char &operator[]( size_t offset ) const {
88  return asArrayOf< char >()[ offset ];
89  }
90 
91  private:
92  std::shared_ptr< void > _ptr;
93  ProtectModeFlags _flags;
94  size_t _size;
95  void _map( int );
96  void _map( const std::string & );
97 };
98 
99 }
100 }
101 }
102 
103 #endif // WIBBLE_SYS_MMAP_V2