/*
    libmaus2
    Copyright (C) 2020 German Tischler

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
#if ! defined(LIBMAUS2_PARALLEL_THREADPOOL_BGZF_BGZFHEADERDECODERBASE_HPP)
#define LIBMAUS2_PARALLEL_THREADPOOL_BGZF_BGZFHEADERDECODERBASE_HPP

#include <libmaus2/types/types.hpp>

namespace libmaus2
{
	namespace parallel
	{
		namespace threadpool
		{
			namespace bgzf
			{
				struct BgzfHeaderDecoderBase
				{

					static uint32_t get8(char const * p, std::size_t const offset)
					{
						unsigned char const * u = reinterpret_cast<unsigned char const *>(p);
						return static_cast<uint8_t>(u[offset]);
					}

					static uint32_t get16(char const * p, std::size_t const offset)
					{
						return get8(p,offset) | (get8(p,offset+1)<<8);
					}

					static uint32_t get32(char const * p, std::size_t const offset)
					{
						return get16(p,offset) | (get16(p,offset+2)<<16);
					}

					// decode 32 bit 2s complement encoded signed number
					static int32_t geti32(char const * p, std::size_t const offset)
					{
						uint32_t const u = get32(p,offset);

						if ( u & (0x8000000ul) )
						{
							return (-(1ll << 31)) + static_cast<int32_t>(u & 0x7FFFFFFFl);
						}
						else
						{
							return static_cast<int32_t>(u);
						}
					}

					static ::std::size_t getMaxBlockSize()
					{
						return 64*1024;
					}

					static void put8(char * p, std::size_t const offset, uint8_t const v)
					{
						unsigned char * u = reinterpret_cast<unsigned char *>(p);
						u[offset] = static_cast<unsigned char>(v);
					}

					static void put16(char * p, std::size_t const offset, uint16_t const v)
					{
						put8(p,offset+0,((v>>0)&0xFFu));
						put8(p,offset+1,((v>>8)&0xFFu));
					}

					static void put32(char * p, std::size_t const offset, uint32_t const v)
					{
						put8(p,offset+0,((v>> 0)&0xFFFFu));
						put8(p,offset+2,((v>>16)&0xFFFFu));
					}
				};
			}
		}
	}
}
#endif
