#include "hpack_integers.h"

namespace NSrvKernel::NHTTP2 {

    TErrorOr<ui32> ReadIntSuffix(TInputRegion& input) noexcept {
        ui32 bitOffset = 0;
        ui32 suffix = 0;
        const auto end = input.begin() + std::min<size_t>(input.SizeAvailable(), IMPL_HPACK_INT_SUFFIX_BYTES_LIMIT);
        auto iter = input.begin();
        ui32 val = 0x80;

        while ((val & 0x80) && (iter < end)) {
            val = *iter;
            suffix |= (val & 0x7F) << bitOffset;
            bitOffset += 7;
            ++iter;
        }

        Y_REQUIRE(!(val & 0x80),
            CompressionError(ECompressionError::InvalidInteger));

        input.Consume(iter - input.begin());
        return suffix;
    }

    void WriteIntSuffix(ui32 value, ui32 length, TOutputRegion& output) noexcept {
        Y_VERIFY(length);
        Y_VERIFY(output.SizeAvailable() >= length);

        for (size_t n = 0; n < length - 1; ++n) {
            *(output.begin() + n) = (value & 0x7F) | 0x80;
            value >>= 7;
        }
        *(output.begin() + length - 1) = value & 0x7F;
        output.Consume(length);
    }
}
