2017
[folly.git] / folly / fibers / Fiber-inl.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 #pragma once
17
18 #include <cassert>
19
20 namespace folly {
21 namespace fibers {
22
23 template <typename F>
24 void Fiber::setFunction(F&& func) {
25   assert(state_ == INVALID);
26   func_ = std::forward<F>(func);
27   state_ = NOT_STARTED;
28 }
29
30 template <typename F, typename G>
31 void Fiber::setFunctionFinally(F&& resultFunc, G&& finallyFunc) {
32   assert(state_ == INVALID);
33   resultFunc_ = std::forward<F>(resultFunc);
34   finallyFunc_ = std::forward<G>(finallyFunc);
35   state_ = NOT_STARTED;
36 }
37
38 inline void* Fiber::getUserBuffer() {
39   return &userBuffer_;
40 }
41
42 template <typename T>
43 T& Fiber::LocalData::getSlow() {
44   dataSize_ = sizeof(T);
45   dataType_ = &typeid(T);
46   if (sizeof(T) <= kBufferSize) {
47     dataDestructor_ = dataBufferDestructor<T>;
48     data_ = &buffer_;
49   } else {
50     dataDestructor_ = dataHeapDestructor<T>;
51     data_ = allocateHeapBuffer(dataSize_);
52   }
53   dataCopyConstructor_ = dataCopyConstructor<T>;
54
55   new (reinterpret_cast<T*>(data_)) T();
56
57   return *reinterpret_cast<T*>(data_);
58 }
59
60 template <typename T>
61 void Fiber::LocalData::dataCopyConstructor(void* ptr, const void* other) {
62   new (reinterpret_cast<T*>(ptr)) T(*reinterpret_cast<const T*>(other));
63 }
64
65 template <typename T>
66 void Fiber::LocalData::dataBufferDestructor(void* ptr) {
67   reinterpret_cast<T*>(ptr)->~T();
68 }
69
70 template <typename T>
71 void Fiber::LocalData::dataHeapDestructor(void* ptr) {
72   reinterpret_cast<T*>(ptr)->~T();
73   freeHeapBuffer(ptr);
74 }
75 }
76 } // folly::fibers