Lua exception handling test
[folly.git] / folly / CachelinePadded.h
1 /*
2  * Copyright 2017 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <cstddef>
20
21 #include <folly/concurrency/CacheLocality.h>
22
23 namespace folly {
24
25 /**
26  * Holds a type T, in addition to enough padding to ensure that it isn't subject
27  * to false sharing within the range used by folly.
28  *
29  * If `sizeof(T) <= alignof(T)` then the inner `T` will be entirely within one
30  * false sharing range (AKA cache line).
31  */
32 template <typename T>
33 class CachelinePadded {
34   static_assert(
35       alignof(T) <= alignof(std::max_align_t),
36       "CachelinePadded does not support over-aligned types");
37
38  public:
39   template <typename... Args>
40   explicit CachelinePadded(Args&&... args)
41       : inner_(std::forward<Args>(args)...) {}
42
43   T* get() {
44     return &inner_;
45   }
46
47   const T* get() const {
48     return &inner_;
49   }
50
51   T* operator->() {
52     return get();
53   }
54
55   const T* operator->() const {
56     return get();
57   }
58
59   T& operator*() {
60     return *get();
61   }
62
63   const T& operator*() const {
64     return *get();
65   }
66
67  private:
68   static constexpr size_t paddingSize() noexcept {
69     return folly::CacheLocality::kFalseSharingRange -
70         (alignof(T) % folly::CacheLocality::kFalseSharingRange);
71   }
72   char paddingPre_[paddingSize()];
73   T inner_;
74   char paddingPost_[paddingSize()];
75 };
76 }