Let Baton methods be noexcept
[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/Portability.h>
22 #include <folly/concurrency/CacheLocality.h>
23 #include <folly/lang/Align.h>
24
25 namespace folly {
26
27 /**
28  * Holds a type T, in addition to enough padding to ensure that it isn't subject
29  * to false sharing within the range used by folly.
30  *
31  * If `sizeof(T) <= alignof(T)` then the inner `T` will be entirely within one
32  * false sharing range (AKA cache line).
33  */
34 template <typename T>
35 class CachelinePadded {
36   static_assert(
37       alignof(T) <= max_align_v,
38       "CachelinePadded does not support over-aligned types.");
39
40  public:
41   template <typename... Args>
42   explicit CachelinePadded(Args&&... args)
43       : inner_(std::forward<Args>(args)...) {}
44
45   T* get() {
46     return &inner_;
47   }
48
49   const T* get() const {
50     return &inner_;
51   }
52
53   T* operator->() {
54     return get();
55   }
56
57   const T* operator->() const {
58     return get();
59   }
60
61   T& operator*() {
62     return *get();
63   }
64
65   const T& operator*() const {
66     return *get();
67   }
68
69  private:
70   static constexpr size_t paddingSize() noexcept {
71     return CacheLocality::kFalseSharingRange -
72         (alignof(T) % CacheLocality::kFalseSharingRange);
73   }
74   char paddingPre_[paddingSize()];
75   T inner_;
76   char paddingPost_[paddingSize()];
77 };
78 } // namespace folly