/**
 * Copyright 2020 German Tischler-Höhle
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **/
#if ! defined(LIBSECRECY_GCMSTREAMBLOCKHEADER_HPP)
#define LIBSECRECY_GCMSTREAMBLOCKHEADER_HPP

#include <libsecrecy/GCMStreamBase.hpp>

namespace libsecrecy
{
	struct GCMStreamBlockHeader
	{
		typedef uint32_t fixed_size_number_type;

		std::size_t const blocksize;

		GCMStreamBlockHeader(std::size_t const rblocksize)
		: blocksize(rblocksize)
		{

		}

		GCMStreamBlockHeader(char const * cp)
		: blocksize(decodeNumber(reinterpret_cast<uint8_t const *>(cp),sizeof(fixed_size_number_type)))
		{

		}

		static std::size_t size()
		{
			return sizeof(fixed_size_number_type);
		}

		static std::size_t decodeNumber(uint8_t const * p, unsigned int const fixed_size_number_type_length)
		{
			std::size_t n = 0;

			for ( unsigned int i = 0; i < fixed_size_number_type_length; ++i )
			{
				n <<= CHAR_BIT;
				n |= static_cast<std::size_t>(*(p++));
			}

			return n;
		}

		static void encodeNumber(
			uint8_t * & p,
			std::size_t const blocksize,
			unsigned int const fixed_size_number_type_length
		)
		{
			unsigned int shift = CHAR_BIT * fixed_size_number_type_length;
			std::size_t const mask = GCMStreamBase::getMask(CHAR_BIT);

			for ( unsigned int i = 0; i < fixed_size_number_type_length; ++i )
			{
				shift -= CHAR_BIT;
				*p++ = (blocksize >> shift)&mask;
			}
		}

		void encode(char * cp) const
		{
			static_assert(sizeof(char) == sizeof(uint8_t));
			static_assert(CHAR_BIT == 8);
			uint8_t * p = reinterpret_cast<uint8_t *>(cp);
			encodeNumber(p,blocksize,sizeof(fixed_size_number_type));
		}
	};
}
#endif
