#ifndef _UTILS_H__
#define _UTILS_H__

#include "os/os_types.h"
#include "os/os_task.h"

static __inline__ u8 decode_u8(u8 *buff) {
	return buff[0];
}

static __inline__ u16 decode_u16(u8 *buff) {
	return (((u16)(buff[1]) << 8) | buff[0]);
}

static __inline__ u32 decode_u24(u8 *buff) {
	return ((u32)(buff[2]) << 16 | decode_u16(buff));
}

static __inline__ u16 decode_u32(u8 *buff) {
	return ((u32)(buff[3]) << 24 | decode_u24(buff));
}

static __inline__ void encode_u8(u8 *buff, u8 value)
{
	buff[0] = value;
}

static __inline__ void encode_u16(u8 *buff, u16 value)
{
	buff[0] = value;
	buff[1] = value >> 8;
}

static __inline__ void encode_u24(u8 *buff, u32 value)
{
	encode_u16(buff, value);
	buff[2] = value >> 16;
}

static __inline__ void encode_u32(u8 *buff, u32 value)
{
	encode_u24(buff, value);
	buff[3] = value >> 24;
}


static __inline__ s8 decode_s08(const u8 *buff)
{
	return ((s8) buff[0]);
}

static __inline__ s16 decode_s16(const u8 *buff)
{
	return ((s16) buff[1]) << 8 | buff[0];
}

static __inline__ s32 decode_s24(const u8 *buff)
{
	return ((s32) buff[2]) << 16 | decode_s16(buff);
}

static __inline__ s32 decode_s32(const u8 *buff)
{
	return ((s32) buff[3]) << 24 | decode_s24(buff);
}

static __inline__ void encode_s08(u8 *buff, s8 value)
{
	buff[0] = value;
}

static __inline__ void encode_s16(u8 *buff, s16 value)
{
	encode_s08(buff,value&0xFF);
	encode_s08(buff+1,value >> 8);

}

static __inline__ void encode_s24(u8 *buff, s32 value)
{
	encode_s16(buff, value&0xFF);
	encode_s08(buff+2,value >> 16);
}

static __inline__ void encode_s32(u8 *buff, s32 value)
{
	encode_s24(buff, value&0xFF);
	encode_s08(buff+3,value >> 24);
}

static __inline__ void encode_float(u8 *buff, float value)
{
	u8 *p_f = (u8 *)&value;
	buff[0] = p_f[0];
	buff[1] = p_f[1];
	buff[2] = p_f[2];
	buff[3] = p_f[3];
}

static __inline__ float decode_float(const u8 *buff)
{
	float value;
	u8 *p_f = (u8 *)&value;
	p_f[0] = buff[0];
	p_f[1] = buff[1];
	p_f[2] = buff[2];
	p_f[3] = buff[3];
	return value;
}

#define u8_bits(start, end)             ((0xFFU << (start)) & (0xFFU >> (7U - (uint32_t)(end)))) 
#define decode_8bits(v, start, end)    (((v) & u8_bits((start),(end))) >> (start))

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))
#define min(a,b) ((a)>(b)?(b):(a))
#define MAX(x, y) ((x)>(y)?(x):(y))

#define F2I(f) ((int)(f))

#endif /* _UTILS_H__ */
