#pragma once

#include <library/cpp/deprecated/atomic/atomic.h>

namespace NSrvKernel {
    class TAtomicState {
    public:
        bool IsAlive() const noexcept {
            return AtomicGet(State_) == ALIVE;
        }

        bool SetKilled() noexcept {
            return AtomicCas(&State_, KILLED, ALIVE);
        }

    private:
        TAtomic State_ = ALIVE;
        static const constexpr TAtomicBase ALIVE = 0;
        static const constexpr TAtomicBase KILLED = 1;
    };

    class IDisposable {
    public:
        virtual ~IDisposable() = default;

        void Dispose() noexcept {
            if (State_.SetKilled()) {
                DoDispose();
            }
        }

        bool IsAlive() const noexcept {
            return State_.IsAlive();
        }

    private:
        virtual void DoDispose() noexcept {
        }

    private:
        TAtomicState State_;
    };
}

