Program Listing for File memorybacked-serializer.h

Return to documentation for file (include\serialization\memorybacked-serializer.h)

/******************************************************************************
© Intel Corporation.

This software and the related documents are Intel copyrighted materials,
and your use of them is governed by the express license under which they
were provided to you ("License"). Unless the License provides otherwise,
you may not use, modify, copy, publish, distribute, disclose or transmit
this software or the related documents without Intel's prior written
permission.


 This software and the related documents are provided as is, with no express
or implied warranties, other than those that are expressly stated in the
License.

******************************************************************************/

#pragma once

#include <cstdint>
#include <cstddef>

namespace gpa {
namespace serialization {

class MemoryBackedSerializer
{
public:
    enum SeekOrigin {
        kBegin,
        kCurrent,
        kEnd,
    };

    virtual ~MemoryBackedSerializer() {}

    virtual size_t WriteRawData(void const* src, size_t size) = 0;

    virtual size_t ReadRawData(void* dst, size_t size) = 0;

    virtual bool EnsureWriteCapacity(size_t const size) = 0;

    virtual bool CheckAvailableData(size_t const size) const = 0;

    virtual void Clear() = 0;

    virtual bool Seek(int64_t offset, SeekOrigin origin = SeekOrigin::kBegin) = 0;

    virtual size_t GetPosition() const = 0;

    virtual uint64_t GetAbsolutePosition() const = 0;

    virtual void* Get(uint64_t offset) const = 0;

    template<typename T>
    size_t Write(T const& src)
    {
        size_t const size = sizeof(src);
        if (ResizeFailed() || !EnsureWriteCapacity(size)) {
            return 0;
        }
        *(T*)mCurr = src;
        Seek(size, SeekOrigin::kCurrent);
        if (mCurr > mWritten) {
            mWritten = mCurr;
        }
        return size;
    }

    template<typename T>
    size_t Read(T& dst)
    {
        // NOTE: this cast will fail for reads greater than 2GiB
        int const size = (int)Peek(dst);
        Seek(size, SeekOrigin::kCurrent);
        return (size_t)size;
    }

    template<typename T>
    size_t Peek(T& dst)
    {
        size_t const size = sizeof(dst);
        if (!CheckAvailableData(size)) {
            return 0;
        }
        dst = *(T*)mCurr;
        return size;
    }

    bool ResizeFailed() const
    {
        return mResizeFailed;
    }

    uint64_t AddRef()
    {
        mRefCount++;
        return mRefCount;
    }

    uint64_t Release()
    {
        mRefCount--;
        return mRefCount;
    }

    bool IsReferenced() const
    {
        return mRefCount > 0;
    }

protected:
    uint64_t mRefCount = 0;
    uint8_t* mCurr = nullptr;
    uint8_t* mWritten = nullptr;
    bool mResizeFailed{false};
};

}  // namespace serialization
}  // namespace gpa