folly/folly/synchronization/AtomicRef.h

/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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.
 */

#pragma once

#include <atomic>
#include <cassert>
#include <cstddef>
#include <type_traits>

#include <folly/Traits.h>
#include <folly/lang/SafeAssert.h>

namespace folly {

namespace detail {

template <typename T>
struct atomic_ref_base {};

template <typename T>
struct atomic_ref_integral_base : atomic_ref_base<T> {};

atomic_ref_select;

} // namespace detail

//  atomic_ref
//
//  A very partial backport of std::atomic_ref from C++20, limited for now to
//  the common operations on counters for now. May become a complete backport
//  in the future.
//
//  Relies on the assumption that `T&` is reinterpretable as `std::atomic<T>&`.
//  And that the required alignment for that reinterpretation is `alignof(T)`.
//  When that is not the case, *kaboom*.
//
//  mimic: std::atomic_ref, C++20
template <typename T>
class atomic_ref : public detail::atomic_ref_select<T> {};

template <typename T>
atomic_ref(T&) -> atomic_ref<T>;

struct make_atomic_ref_t {};

inline constexpr make_atomic_ref_t make_atomic_ref;

} // namespace folly