chromium/v8/src/base/contextual.h

// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef V8_BASE_CONTEXTUAL_H_
#define V8_BASE_CONTEXTUAL_H_

#include <type_traits>

#include "src/base/export-template.h"
#include "src/base/macros.h"
#include "src/base/platform/platform.h"

namespace v8::base {

// {ContextualVariable} provides a clean alternative to a global variable.
// The contextual variable is mutable, and supports managing the value of
// a variable in a well-nested fashion via the {Scope} class.
// {ContextualVariable} only stores a pointer to the current value, which
// is stored in a {Scope} object. The most recent value can be retrieved
// via Get(). Because only {Scope} has actual storage, there must be at
// least one active {Scope} (i.e. in a surrounding C++ scope), whenever Get()
// is called.
// Note that contextual variables must only be used from the same thread,
// i.e. {Scope} and Get() have to be in the same thread.
template <class Derived, class VarType>
class V8_EXPORT_PRIVATE ContextualVariable {};

// Usage: DECLARE_CONTEXTUAL_VARIABLE(VarName, VarType)
#define DECLARE_CONTEXTUAL_VARIABLE(VarName, ...)

// Contextual variables that are accessed in tests need to be
// exported. For this, place the following macro in the global namespace inside
// of a .cc file.
#define EXPORT_CONTEXTUAL_VARIABLE(VarName)

// By inheriting from {ContextualClass} a class can become a contextual variable
// of itself, which is very similar to a singleton.
ContextualClass;

// {ContextualVariableWithDefault} is similar to a {ContextualVariable},
// with the difference that a default value is used if there is no active
// {Scope} object.
template <class Derived, class VarType, auto... default_args>
class V8_EXPORT_PRIVATE ContextualVariableWithDefault
    : public ContextualVariable<Derived, VarType> {};

// Usage: DECLARE_CONTEXTUAL_VARIABLE_WITH_DEFAULT(VarName, VarType, Args...)
#define DECLARE_CONTEXTUAL_VARIABLE_WITH_DEFAULT(VarName, ...)

}  // namespace v8::base

#endif  // V8_BASE_CONTEXTUAL_H_