/* -*-c++-*- OpenThreads library, Copyright (C) 2008  The Open Thread Group
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#ifndef _OPENTHREADS_ATOMIC_
#define _OPENTHREADS_ATOMIC_

#include <OpenThreads/Config>

#include <atomic>

namespace OpenThreads {

/**
 *  @class Atomic
 *  @brief  This class provides an atomic increment and decrement operation.
 */
class Atomic {
 public:
    Atomic(unsigned value = 0) : _value(value)
    { }
    unsigned operator++();
    unsigned operator--();
    unsigned AND(unsigned value);
    unsigned OR(unsigned value);
    unsigned XOR(unsigned value);
    unsigned exchange(unsigned value = 0);
    operator unsigned() const;
 private:

    Atomic(const Atomic&);
    Atomic& operator=(const Atomic&);

    std::atomic<unsigned> _value;
};

/**
 *  @class AtomicPtr
 *  @brief  This class provides an atomic pointer assignment using cas operations.
 */
class AtomicPtr {
public:
    AtomicPtr(void* ptr = 0) : _ptr(ptr)
    { }
    ~AtomicPtr()
    { _ptr = 0; }

    // assigns a new pointer
    bool assign(void* ptrNew, const void* const ptrOld);
    void* get() const;

private:
    AtomicPtr(const AtomicPtr&);
    AtomicPtr& operator=(const AtomicPtr&);

    std::atomic<void*> _ptr;
};

inline unsigned
Atomic::operator++()
{
    return ++_value;
}

inline unsigned
Atomic::operator--()
{
    return --_value;
}

inline unsigned
Atomic::AND(unsigned value)
{
    return (_value &= value);
}

inline unsigned
Atomic::OR(unsigned value)
{
    return (_value |= value);
}

inline unsigned
Atomic::XOR(unsigned value)
{
    return (_value ^= value);
}

inline unsigned
Atomic::exchange(unsigned value)
{
    return _value.exchange(value);
}

inline
Atomic::operator unsigned() const
{
    return _value;
}

inline bool
AtomicPtr::assign(void* ptrNew, const void* const ptrOld)
{
    void *old = (void*) ptrOld;
    return _ptr.compare_exchange_strong(old, ptrNew);
}

inline void*
AtomicPtr::get() const
{
    return _ptr;
}

}

#endif // _OPENTHREADS_ATOMIC_
