#include "geners/GenericIO.hh"

namespace gs {
    template <typename T>
    inline void Reference<T>::restore(const unsigned long index, T* obj) const
    {
        const unsigned long long itemId = this->id(index);
        assert(itemId);
        restore_item(this->positionInputStream(itemId), obj, true);
    }

    template <typename T>
    inline T* Reference<T>::getPtr(const unsigned long index) const
    {
        const unsigned long long itemId = this->id(index);
        assert(itemId);
        T* barePtr = 0;
        std::vector<ClassId> state;
        if (GenericReader<std::istream, std::vector<ClassId>, T*,
            Int2Type<IOTraits<int>::ISNULLPOINTER> >::process(
                barePtr, this->positionInputStream(itemId), &state, true))
            assert(barePtr);
        else
        {
            delete barePtr;
            barePtr = 0;
        }
        if (!barePtr)
            throw IOInvalidData("In gs::Reference::getPtr: "
                                "failed to read in the object");
        return barePtr;
    }

    template <typename T>
    inline CPP11_auto_ptr<T> Reference<T>::get(const unsigned long index) const
    {
        return CPP11_auto_ptr<T>(getPtr(index));
    }

    template <typename T>
    inline CPP11_shared_ptr<T> Reference<T>::getShared(
        const unsigned long index) const
    {
        return CPP11_shared_ptr<T>(getPtr(index));
    }
}
