carb/eventdispatcher/EventDispatcherTypes.h

File members: carb/eventdispatcher/EventDispatcherTypes.h

// Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved.
//
// NVIDIA CORPORATION and its licensors retain all intellectual property
// and proprietary rights in and to this software, related documentation
// and any modifications thereto. Any use, reproduction, disclosure or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA CORPORATION is strictly prohibited.
//

#pragma once

#include "../Strong.h"
#include "../variant/VariantUtils.h"

namespace carb
{
namespace eventdispatcher
{

CARB_STRONGTYPE(Observer, size_t);

constexpr Observer kInvalidObserver{};

struct NamedVariant
{
    RStringKey name;
    variant::Variant value;
};
static_assert(std::is_standard_layout<NamedVariant>::value, ""); // Not interop-safe as it is not trivially copyable

struct EventData
{
    RString eventName;
    size_t numVariants;
    NamedVariant const* variants;
};
CARB_ASSERT_INTEROP_SAFE(EventData);

class Event final : public EventData
{
    CARB_PREVENT_COPY_AND_MOVE(Event);

public:
    bool hasKey(RStringKey key) const;

    const variant::Variant* get(RStringKey key) const;

    template <class T>
    cpp::optional<T> getValue(RStringKey key) const;

    template <class T>
    T getValueOr(RStringKey key, T&& defaultValue) const;
};
static_assert(sizeof(Event) == sizeof(EventData), "");

using ObserverFn = void (*)(const Event&, void*);

using CleanupFn = void (*)(void*);

class ObserverGuard
{
public:
    CARB_PREVENT_COPY(ObserverGuard);

    constexpr ObserverGuard() noexcept;

    constexpr explicit ObserverGuard(Observer o) noexcept;

    ObserverGuard(ObserverGuard&& other) noexcept;

    ~ObserverGuard() noexcept;

    ObserverGuard& operator=(ObserverGuard&& other) noexcept;

    Observer release() noexcept;

    void reset(Observer o = kInvalidObserver) noexcept;

    void swap(ObserverGuard& o) noexcept;

    constexpr Observer get() const noexcept;

    explicit operator bool() const noexcept;

private:
    Observer m_o;
};

} // namespace eventdispatcher
} // namespace carb