handmade/include/SafeUDPpacket.h

89 lines
1.9 KiB
C
Raw Permalink Normal View History

#pragma once
#include <memory>
#include <string>
#include <vector>
#include <SDL_assert.h>
#include <SDL_net.h>
class SafeUDPpacket
{
struct SDLNet_PacketDeleter
{
void operator () (UDPpacket* p)
{
SDLNet_FreePacket (p);
p = NULL;
}
};
std::unique_ptr<UDPpacket, SDLNet_PacketDeleter> m_packet;
void Reset (UDPpacket* p)
{
m_packet.reset (p);
}
public:
SafeUDPpacket (const void* buf, int size)
{
UDPpacket* p;
if (NULL == (p = SDLNet_AllocPacket (size)))
{
throw "SDLNet_AllocPacket: " + std::string (SDLNet_GetError ());
}
else
{
SDL_memcpy (p->data, buf, size);
Reset (p);
}
}
SafeUDPpacket (int size)
{
UDPpacket* p;
if (NULL == (p = SDLNet_AllocPacket (size)))
{
throw "SDLNet_AllocPacket: " + std::string (SDLNet_GetError ());
}
else
{
Reset (p);
}
}
SafeUDPpacket (UDPpacket* p)
{
Reset (p);
}
UDPpacket* get (void) const
{
return m_packet.get ();
}
void clear (void)
{
SDL_assert (len () > 0);
SDL_memset (data (), 0, len ());
}
void slurp (const void* buf, const size_t size)
{
SDL_memcpy (data (), buf, size);
}
int Send (UDPsocket sock)
{
return SDLNet_UDP_Send (sock, channel(), get ());
}
int channel (int channel) const { return get()->channel = channel; }
int channel (void) const { return get()->channel; }
int len (int len) const { return get()->len = len; }
int len (void) const { return get()->len; }
int maxlen (int maxlen) const { return get()->maxlen = maxlen; }
int maxlen (void) const { return get()->maxlen; }
int status (int status) const { return get()->status = status; }
int status (void) const { return get()->status; }
IPaddress address (IPaddress address) const { return get()->address = address; }
IPaddress address (void) const { return get()->address; }
Uint8 *data (Uint8* data) const { return get()->data = data; }
Uint8 *data (void) const { return get()->data; }
};