2018-08-02 09:09:54 +08:00
|
|
|
/*
|
|
|
|
* Util.h
|
|
|
|
*
|
|
|
|
* This source file is part of the FoundationDB open source project
|
|
|
|
*
|
|
|
|
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
|
|
|
|
*
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
*
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
*
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
* limitations under the License.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#ifndef _FLOW_UTIL_H_
|
|
|
|
#define _FLOW_UTIL_H_
|
2018-08-09 07:05:49 +08:00
|
|
|
#pragma once
|
2018-08-02 09:09:54 +08:00
|
|
|
|
2018-08-11 07:18:24 +08:00
|
|
|
#include <algorithm>
|
|
|
|
|
2018-08-02 09:09:54 +08:00
|
|
|
template <typename C>
|
|
|
|
void swapAndPop(C* container, int index) {
|
2021-03-11 02:06:03 +08:00
|
|
|
if (index != container->size() - 1) {
|
2018-08-02 09:09:54 +08:00
|
|
|
using std::swap;
|
|
|
|
swap((*container)[index], container->back());
|
|
|
|
}
|
|
|
|
|
|
|
|
container->pop_back();
|
|
|
|
}
|
|
|
|
|
2020-06-23 14:45:47 +08:00
|
|
|
// Adds n to pCount upon construction, subtracts in upon destruction
|
2021-03-11 02:06:03 +08:00
|
|
|
template <typename T>
|
2020-06-23 14:45:47 +08:00
|
|
|
struct Hold {
|
2021-03-11 02:06:03 +08:00
|
|
|
Hold(T* pCount = nullptr, T n = 1) : pCount(pCount), n(n) {
|
|
|
|
if (pCount != nullptr) {
|
2020-06-23 14:45:47 +08:00
|
|
|
*pCount += n;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
~Hold() {
|
2021-03-11 02:06:03 +08:00
|
|
|
if (pCount != nullptr) {
|
2020-06-23 14:45:47 +08:00
|
|
|
*pCount -= n;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 02:06:03 +08:00
|
|
|
Hold(Hold&& other) {
|
2020-06-23 14:45:47 +08:00
|
|
|
pCount = other.pCount;
|
|
|
|
other.pCount = nullptr;
|
|
|
|
n = other.n;
|
|
|
|
}
|
|
|
|
|
2021-03-11 02:06:03 +08:00
|
|
|
Hold& operator=(Hold&& other) {
|
|
|
|
if (pCount != nullptr) {
|
2020-06-23 14:45:47 +08:00
|
|
|
*pCount -= n;
|
|
|
|
}
|
|
|
|
pCount = other.pCount;
|
|
|
|
other.pCount = nullptr;
|
|
|
|
n = other.n;
|
|
|
|
return *this;
|
|
|
|
};
|
|
|
|
|
|
|
|
void release() {
|
2021-03-11 02:06:03 +08:00
|
|
|
if (pCount != nullptr) {
|
2020-06-23 14:45:47 +08:00
|
|
|
*pCount -= n;
|
|
|
|
pCount = nullptr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 02:06:03 +08:00
|
|
|
T* pCount;
|
2020-06-23 14:45:47 +08:00
|
|
|
T n;
|
|
|
|
|
2021-03-11 02:06:03 +08:00
|
|
|
void operator=(const Hold& other) = delete;
|
2020-06-23 14:45:47 +08:00
|
|
|
};
|
|
|
|
|
2021-03-11 02:06:03 +08:00
|
|
|
#endif // _FLOW_UTIL_H_
|