Skip to main content

BytesReader

private @safe struct BytesReader(A = const ubyte[])
{
    A arr;
    size_t currIdx;

    this(A a)
    {
        arr = a;
    }

    T* read(T)() @trusted
    {
        const incremented = currIdx + T.sizeof;

        // Malformed buffer?
        if(incremented > arr.length)
            throw new AnswerException(ExceptionType.FATAL_ERROR, null);

        auto ret = cast(T*) &arr[currIdx];

        currIdx = incremented;

        return ret;
    }

    A readBuff(size_t len)
    in(len >= 0) // <-- here -------------------------------------------------------------------
    {
        const incremented = currIdx + len;

        // Malformed buffer?
        if(incremented > arr.length)
            throw new AnswerException(ExceptionType.FATAL_ERROR, null);

        auto ret = arr[currIdx .. incremented];

        currIdx = incremented;

        return ret;
    }
}