// // Created by Mindaugas Vinkelis on 2016-11-11. // #ifndef PROJECT_TEMPLATE_BUFFER_READER_H #define PROJECT_TEMPLATE_BUFFER_READER_H #include "Common.h" #include #include namespace bitsery { struct BufferReader { using value_type = uint8_t; BufferReader(const std::vector &buf) : _buf{buf}, _pos{std::begin(buf)} { } template bool readBytes(T &v) { static_assert(std::is_integral(), ""); static_assert(sizeof(T) == SIZE, ""); using UT = typename std::make_unsigned::type; return !m_scratch ? directRead(&v, 1) : readBits(reinterpret_cast(v), BITS_SIZE); } template bool readBuffer(T *buf, size_t count) { static_assert(std::is_integral(), ""); static_assert(sizeof(T) == SIZE, ""); if (!m_scratchBits) { return directRead(buf, count); } else { using UT = typename std::make_unsigned::type; //todo improve implementation const auto end = buf + count; for (auto it = buf; it != end; ++it) { if (!readBits(reinterpret_cast(*it), BITS_SIZE)) return false; } } return true; } template bool readBits(T &v, size_t bitsCount) { static_assert(std::is_integral() && std::is_unsigned(), ""); assert(bitsCount <= BITS_SIZE); const auto bytesRequired = bitsCount > m_scratchBits ? ((bitsCount - 1 - m_scratchBits) >> 3) + 1u : 0u; if (static_cast(std::distance(_pos, std::end(_buf))) < bytesRequired) return false; readBitsInternal(v, bitsCount); return true; } bool align() { if (m_scratchBits) { SCRATCH_TYPE tmp{}; readBitsInternal(tmp, BITS_SIZE - m_scratchBits); return tmp == 0; } return true; } bool isCompleted() const { return _pos == std::end(_buf); } private: const std::vector &_buf; decltype(std::begin(_buf)) _pos; template bool directRead(T *v, size_t count) { static_assert(!std::is_const::value, ""); const auto bytesCount = sizeof(T) * count; if (static_cast(std::distance(_pos, std::end(_buf))) < bytesCount) return false; std::copy_n(_pos, bytesCount, reinterpret_cast(v)); std::advance(_pos, bytesCount); return true; } template void readBitsInternal(T &v, size_t size) { auto bitsLeft = size; T res{}; while (bitsLeft > 0) { auto bits = std::min(bitsLeft, BITS_SIZE); if (m_scratchBits < bits) { value_type tmp; std::copy_n(_pos, 1, reinterpret_cast(&tmp)); std::advance(_pos, 1); m_scratch |= static_cast(tmp) << m_scratchBits; m_scratchBits += BITS_SIZE; } auto shiftedRes = static_cast(m_scratch & ((static_cast(1) << bits) - 1)) << (size - bitsLeft); res |= shiftedRes; m_scratch >>= bits; m_scratchBits -= bits; bitsLeft -= bits; } v = res; } using SCRATCH_TYPE = typename BIGGER_TYPE::type; SCRATCH_TYPE m_scratch{}; size_t m_scratchBits{}; ///< Number of bits currently in the scratch buffer. If the user wants to read more bits than this, we have to go fetch another dword from memory. }; } #endif //PROJECT_TEMPLATE_BUFFER_READER_H