3 @brief ENet packet management functions
6 #define ENET_BUILDING_LIB 1
9 /** @defgroup Packet ENet packet functions
13 /** Creates a packet that may be sent to a peer.
14 @param dataContents initial contents of the packet's data; the packet's data will remain uninitialized if dataContents is NULL.
15 @param dataLength size of the data allocated for this packet
16 @param flags flags for this packet as described for the ENetPacket structure.
17 @returns the packet on success, NULL on failure
20 enet_packet_create (const void * data
, size_t dataLength
, enet_uint32 flags
)
22 ENetPacket
* packet
= (ENetPacket
*) enet_malloc (sizeof (ENetPacket
));
24 if (flags
& ENET_PACKET_FLAG_NO_ALLOCATE
)
25 packet
-> data
= (enet_uint8
*) data
;
28 packet
-> data
= (enet_uint8
*) enet_malloc (dataLength
);
29 if (packet
-> data
== NULL
)
36 memcpy (packet
-> data
, data
, dataLength
);
39 packet
-> referenceCount
= 0;
40 packet
-> flags
= flags
;
41 packet
-> dataLength
= dataLength
;
42 packet
-> freeCallback
= NULL
;
47 /** Destroys the packet and deallocates its data.
48 @param packet packet to be destroyed
51 enet_packet_destroy (ENetPacket
* packet
)
53 if (packet
-> freeCallback
!= NULL
)
54 (* packet
-> freeCallback
) (packet
);
55 if (! (packet
-> flags
& ENET_PACKET_FLAG_NO_ALLOCATE
))
56 enet_free (packet
-> data
);
60 /** Attempts to resize the data in the packet to length specified in the
62 @param packet packet to resize
63 @param dataLength new size for the packet data
64 @returns 0 on success, < 0 on failure
67 enet_packet_resize (ENetPacket
* packet
, size_t dataLength
)
71 if (dataLength
<= packet
-> dataLength
|| (packet
-> flags
& ENET_PACKET_FLAG_NO_ALLOCATE
))
73 packet
-> dataLength
= dataLength
;
78 newData
= (enet_uint8
*) enet_malloc (dataLength
);
82 memcpy (newData
, packet
-> data
, packet
-> dataLength
);
83 enet_free (packet
-> data
);
85 packet
-> data
= newData
;
86 packet
-> dataLength
= dataLength
;
91 static int initializedCRC32
= 0;
92 static enet_uint32 crcTable
[256];
94 static void initialize_crc32 ()
98 for (byte
= 0; byte
< 256; ++ byte
)
100 enet_uint32 crc
= byte
<< 24;
103 for(offset
= 0; offset
< 8; ++ offset
)
105 if (crc
& 0x80000000)
106 crc
= (crc
<< 1) ^ 0x04c11db7;
111 crcTable
[byte
] = crc
;
114 initializedCRC32
= 1;
118 enet_crc32 (const ENetBuffer
* buffers
, size_t bufferCount
)
120 enet_uint32 crc
= 0xFFFFFFFF;
122 if (! initializedCRC32
) initialize_crc32 ();
124 while (bufferCount
-- > 0)
126 const enet_uint8
* data
= (const enet_uint8
*) buffers
-> data
,
127 * dataEnd
= & data
[buffers
-> dataLength
];
129 while (data
< dataEnd
)
131 crc
= ((crc
<< 8) | * data
++) ^ crcTable
[crc
>> 24];
137 return ENET_HOST_TO_NET_32 (~ crc
);