-
Notifications
You must be signed in to change notification settings - Fork 0
/
yojimbo.h
5892 lines (4718 loc) · 227 KB
/
yojimbo.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Yojimbo Client/Server Network Library.
Copyright © 2016 - 2019, The Network Protocol Company, Inc.
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.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
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.
*/
#ifndef YOJIMBO_H
#define YOJIMBO_H
/** @file */
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#define YOJIMBO_MAJOR_VERSION 1
#define YOJIMBO_MINOR_VERSION 0
#define YOJIMBO_PATCH_VERSION 0
#if !defined (YOJIMBO_LITTLE_ENDIAN ) && !defined( YOJIMBO_BIG_ENDIAN )
#ifdef __BYTE_ORDER__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define YOJIMBO_LITTLE_ENDIAN 1
#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
#define YOJIMBO_BIG_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define YOJIMBO_LITTLE_ENDIAN or YOJIMBO_BIG_ENDIAN.
#endif // __BYTE_ORDER__
// Detect with GLIBC's endian.h
#elif defined(__GLIBC__)
#include <endian.h>
#if (__BYTE_ORDER == __LITTLE_ENDIAN)
#define YOJIMBO_LITTLE_ENDIAN 1
#elif (__BYTE_ORDER == __BIG_ENDIAN)
#define YOJIMBO_BIG_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define YOJIMBO_LITTLE_ENDIAN or YOJIMBO_BIG_ENDIAN.
#endif // __BYTE_ORDER
// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro
#elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
#define YOJIMBO_LITTLE_ENDIAN 1
#elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
#define YOJIMBO_BIG_ENDIAN 1
// Detect with architecture macros
#elif defined(__sparc) || defined(__sparc__) \
|| defined(_POWER) || defined(__powerpc__) \
|| defined(__ppc__) || defined(__hpux) || defined(__hppa) \
|| defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
#define YOJIMBO_BIG_ENDIAN 1
#elif defined(__i386__) || defined(__alpha__) || defined(__ia64) \
|| defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) \
|| defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) \
|| defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) \
|| defined(_M_X64) || defined(__bfin__)
#define YOJIMBO_LITTLE_ENDIAN 1
#elif defined(_MSC_VER) && defined(_M_ARM)
#define YOJIMBO_LITTLE_ENDIAN 1
#else
#error Unknown machine endianess detected. User needs to define YOJIMBO_LITTLE_ENDIAN or YOJIMBO_BIG_ENDIAN.
#endif
#endif
#ifndef YOJIMBO_LITTLE_ENDIAN
#define YOJIMBO_LITTLE_ENDIAN 0
#endif
#ifndef YOJIMBO_BIG_ENDIAN
#define YOJIMBO_BIG_ENDIAN 0
#endif
#ifndef YOJIMBO_DEFAULT_TIMEOUT
#define YOJIMBO_DEFAULT_TIMEOUT 5
#endif
#if !defined( YOJIMBO_WITH_MBEDTLS )
#define YOJIMBO_WITH_MBEDTLS 1
#endif // #if !defined( YOJIMBO_WITH_MBEDTLS )
#ifdef _MSC_VER
#pragma warning( disable : 4127 )
#pragma warning( disable : 4244 )
#endif // #ifdef _MSC_VER
#define YOJIMBO_PLATFORM_WINDOWS 1
#define YOJIMBO_PLATFORM_MAC 2
#define YOJIMBO_PLATFORM_UNIX 3
#if defined(_WIN32)
#define YOJIMBO_PLATFORM YOJIMBO_PLATFORM_WINDOWS
#elif defined(__APPLE__)
#define YOJIMBO_PLATFORM YOJIMBO_PLATFORM_MAC
#else
#define YOJIMBO_PLATFORM YOJIMBO_PLATFORM_UNIX
#endif
#define YOJIMBO_SERIALIZE_CHECKS 1
#ifndef NDEBUG
#define YOJIMBO_DEBUG_MEMORY_LEAKS 1
#define YOJIMBO_DEBUG_MESSAGE_LEAKS 1
#define YOJIMBO_DEBUG_MESSAGE_BUDGET 1
#else // #ifndef NDEBUG
#define YOJIMBO_DEBUG_MEMORY_LEAKS 0
#define YOJIMBO_DEBUG_MESSAGE_LEAKS 0
#define YOJIMBO_DEBUG_MESSAGE_BUDGET 0
#endif // #ifndef NDEBUG
#define YOJIMBO_ENABLE_LOGGING 1
#include <stdint.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include <math.h>
#include <inttypes.h>
#if YOJIMBO_DEBUG_MESSAGE_LEAKS
#include <map>
#endif // #if YOJIMBO_DEBUG_MESSAGE_LEAKS
// windows =p
#ifdef SendMessage
#undef SendMessage
#endif
struct netcode_server_t;
struct netcode_client_t;
struct reliable_endpoint_t;
/// The library namespace.
namespace yojimbo
{
const int MaxClients = 64; ///< The maximum number of clients supported by this library. You can increase this if you want, but this library is designed around patterns that work best for [2,64] player games. If your game has less than 64 clients, reducing this will save memory.
const int MaxChannels = 64; ///< The maximum number of message channels supported by this library. If you need less than 64 channels per-packet, reducing this will save memory.
const int KeyBytes = 32; ///< Size of encryption key for dedicated client/server in bytes. Must be equal to key size for libsodium encryption primitive. Do not change.
const int ConnectTokenBytes = 2048; ///< Size of the encrypted connect token data return from the matchmaker. Must equal size of NETCODE_CONNECT_TOKEN_BYTE (2048).
const uint32_t SerializeCheckValue = 0x12345678; ///< The value written to the stream for serialize checks. See WriteStream::SerializeCheck and ReadStream::SerializeCheck.
const int ConservativeMessageHeaderBits = 32; ///< Conservative number of bits per-message header.
const int ConservativeFragmentHeaderBits = 64; ///< Conservative number of bits per-fragment header.
const int ConservativeChannelHeaderBits = 32; ///< Conservative number of bits per-channel header.
const int ConservativePacketHeaderBits = 16; ///< Conservative number of bits per-packet header.
/// Determines the reliability and ordering guarantees for a channel.
enum ChannelType
{
CHANNEL_TYPE_RELIABLE_ORDERED, ///< Messages are received reliably and in the same order they were sent.
CHANNEL_TYPE_UNRELIABLE_UNORDERED ///< Messages are sent unreliably. Messages may arrive out of order, or not at all.
};
/**
Configuration properties for a message channel.
Channels let you specify different reliability and ordering guarantees for messages sent across a connection.
They may be configured as one of two types: reliable-ordered or unreliable-unordered.
Reliable ordered channels guarantee that messages (see Message) are received reliably and in the same order they were sent.
This channel type is designed for control messages and RPCs sent between the client and server.
Unreliable unordered channels are like UDP. There is no guarantee that messages will arrive, and messages may arrive out of order.
This channel type is designed for data that is time critical and should not be resent if dropped, like snapshots of world state sent rapidly
from server to client, or cosmetic events such as effects and sounds.
Both channel types support blocks of data attached to messages (see BlockMessage), but their treatment of blocks is quite different.
Reliable ordered channels are designed for blocks that must be received reliably and in-order with the rest of the messages sent over the channel.
Examples of these sort of blocks include the initial state of a level, or server configuration data sent down to a client on connect. These blocks
are sent by splitting them into fragments and resending each fragment until the other side has received the entire block. This allows for sending
blocks of data larger that maximum packet size quickly and reliably even under packet loss.
Unreliable-unordered channels send blocks as-is without splitting them up into fragments. The idea is that transport level packet fragmentation
should be used on top of the generated packet to split it up into into smaller packets that can be sent across typical Internet MTU (<1500 bytes).
Because of this, you need to make sure that the maximum block size for an unreliable-unordered channel fits within the maximum packet size.
Channels are typically configured as part of a ConnectionConfig, which is included inside the ClientServerConfig that is passed into the Client and Server constructors.
*/
struct ChannelConfig
{
ChannelType type; ///< Channel type: reliable-ordered or unreliable-unordered.
bool disableBlocks; ///< Disables blocks being sent across this channel.
int sentPacketBufferSize; ///< Number of packet entries in the sent packet sequence buffer. Please consider your packet send rate and make sure you have at least a few seconds worth of entries in this buffer.
int messageSendQueueSize; ///< Number of messages in the send queue for this channel.
int messageReceiveQueueSize; ///< Number of messages in the receive queue for this channel.
int maxMessagesPerPacket; ///< Maximum number of messages to include in each packet. Will write up to this many messages, provided the messages fit into the channel packet budget and the number of bytes remaining in the packet.
int packetBudget; ///< Maximum amount of message data to write to the packet for this channel (bytes). Specifying -1 means the channel can use up to the rest of the bytes remaining in the packet.
int maxBlockSize; ///< The size of the largest block that can be sent across this channel (bytes).
int blockFragmentSize; ///< Blocks are split up into fragments of this size (bytes). Reliable-ordered channel only.
float messageResendTime; ///< Minimum delay between message resends (seconds). Avoids sending the same message too frequently. Reliable-ordered channel only.
float blockFragmentResendTime; ///< Minimum delay between block fragment resends (seconds). Avoids sending the same fragment too frequently. Reliable-ordered channel only.
ChannelConfig() : type ( CHANNEL_TYPE_RELIABLE_ORDERED )
{
disableBlocks = false;
sentPacketBufferSize = 1024;
messageSendQueueSize = 1024;
messageReceiveQueueSize = 1024;
maxMessagesPerPacket = 256;
packetBudget = -1;
maxBlockSize = 256 * 1024;
blockFragmentSize = 1024;
messageResendTime = 0.1f;
blockFragmentResendTime = 0.25f;
}
int GetMaxFragmentsPerBlock() const
{
return maxBlockSize / blockFragmentSize;
}
};
/**
Configures connection properties and the set of channels for sending and receiving messages.
Specifies the maximum packet size to generate, and the number of message channels, and the per-channel configuration data. See ChannelConfig for details.
Typically configured as part of a ClientServerConfig which is passed into Client and Server constructors.
*/
struct ConnectionConfig
{
int numChannels; ///< Number of message channels in [1,MaxChannels]. Each message channel must have a corresponding configuration below.
int maxPacketSize; ///< The maximum size of packets generated to transmit messages between client and server (bytes).
ChannelConfig channel[MaxChannels]; ///< Per-channel configuration. See ChannelConfig for details.
ConnectionConfig()
{
numChannels = 1;
maxPacketSize = 8 * 1024;
}
};
/**
Configuration shared between client and server.
Passed to Client and Server constructors to configure their behavior.
Please make sure that the message configuration is identical between client and server.
*/
struct ClientServerConfig : public ConnectionConfig
{
uint64_t protocolId; ///< Clients can only connect to servers with the same protocol id. Use this for versioning.
int timeout; ///< Timeout value in seconds. Set to negative value to disable timeouts (for debugging only).
int clientMemory; ///< Memory allocated inside Client for packets, messages and stream allocations (bytes)
int serverGlobalMemory; ///< Memory allocated inside Server for global connection request and challenge response packets (bytes)
int serverPerClientMemory; ///< Memory allocated inside Server for packets, messages and stream allocations per-client (bytes)
bool networkSimulator; ///< If true then a network simulator is created for simulating latency, jitter, packet loss and duplicates.
int maxSimulatorPackets; ///< Maximum number of packets that can be stored in the network simulator. Additional packets are dropped.
int fragmentPacketsAbove; ///< Packets above this size (bytes) are split apart into fragments and reassembled on the other side.
int packetFragmentSize; ///< Size of each packet fragment (bytes).
int maxPacketFragments; ///< Maximum number of fragments a packet can be split up into.
int packetReassemblyBufferSize; ///< Number of packet entries in the fragmentation reassembly buffer.
int ackedPacketsBufferSize; ///< Number of packet entries in the acked packet buffer. Consider your packet send rate and aim to have at least a few seconds worth of entries.
int receivedPacketsBufferSize; ///< Number of packet entries in the received packet sequence buffer. Consider your packet send rate and aim to have at least a few seconds worth of entries.
ClientServerConfig()
{
protocolId = 0;
timeout = YOJIMBO_DEFAULT_TIMEOUT;
clientMemory = 10 * 1024 * 1024;
serverGlobalMemory = 10 * 1024 * 1024;
serverPerClientMemory = 10 * 1024 * 1024;
networkSimulator = true;
maxSimulatorPackets = 4 * 1024;
fragmentPacketsAbove = 1024;
packetFragmentSize = 1024;
maxPacketFragments = (int) ceil( maxPacketSize / packetFragmentSize );
packetReassemblyBufferSize = 64;
ackedPacketsBufferSize = 256;
receivedPacketsBufferSize = 256;
}
};
}
/**
Initialize the yojimbo library.
Call this before calling any yojimbo library functions.
@returns True if the library was successfully initialized, false otherwise.
*/
bool InitializeYojimbo();
/**
Shutdown the yojimbo library.
Call this after you finish using the library and it will run some checks for you (for example, checking for memory leaks in debug build).
*/
void ShutdownYojimbo();
/**
Template function to get the minimum of two values.
@param a The first value.
@param b The second value.
@returns The minimum of a and b.
*/
template <typename T> const T & yojimbo_min( const T & a, const T & b )
{
return ( a < b ) ? a : b;
}
/**
Template function to get the maximum of two values.
@param a The first value.
@param b The second value.
@returns The maximum of a and b.
*/
template <typename T> const T & yojimbo_max( const T & a, const T & b )
{
return ( a > b ) ? a : b;
}
/**
Template function to clamp a value.
@param value The value to be clamped.
@param a The minimum value.
@param b The minimum value.
@returns The clamped value in [a,b].
*/
template <typename T> T yojimbo_clamp( const T & value, const T & a, const T & b )
{
if ( value < a )
return a;
else if ( value > b )
return b;
else
return value;
}
/**
Swap two values.
@param a First value.
@param b Second value.
*/
template <typename T> void yojimbo_swap( T & a, T & b )
{
T tmp = a;
a = b;
b = tmp;
};
/**
Get the absolute value.
@param value The input value.
@returns The absolute value.
*/
template <typename T> T yojimbo_abs( const T & value )
{
return ( value < 0 ) ? -value : value;
}
/**
Sleep for approximately this number of seconds.
@param time number of seconds to sleep for.
*/
void yojimbo_sleep( double time );
/**
Get a high precision time in seconds since the application has started.
Please store time in doubles so you retain sufficient precision as time increases.
@returns Time value in seconds.
*/
double yojimbo_time();
#define YOJIMBO_LOG_LEVEL_NONE 0
#define YOJIMBO_LOG_LEVEL_ERROR 1
#define YOJIMBO_LOG_LEVEL_INFO 2
#define YOJIMBO_LOG_LEVEL_DEBUG 3
/**
Set the yojimbo log level.
Valid log levels are: YOJIMBO_LOG_LEVEL_NONE, YOJIMBO_LOG_LEVEL_ERROR, YOJIMBO_LOG_LEVEL_INFO and YOJIMBO_LOG_LEVEL_DEBUG
@param level The log level to set. Initially set to YOJIMBO_LOG_LEVEL_NONE.
*/
void yojimbo_log_level( int level );
/**
Printf function used by yojimbo to emit logs.
This function internally calls the printf callback set by the user.
@see yojimbo_set_printf_function
*/
void yojimbo_printf( int level, const char * format, ... );
extern void (*yojimbo_assert_function)( const char *, const char *, const char * file, int line );
/**
Assert function used by yojimbo.
This assert function lets the user override the assert presentation.
@see yojimbo_set_assert_functio
*/
#ifndef NDEBUG
#define yojimbo_assert( condition ) \
do \
{ \
if ( !(condition) ) \
{ \
yojimbo_assert_function( #condition, __FUNCTION__, __FILE__, __LINE__ ); \
exit(1); \
} \
} while(0)
#else
#define yojimbo_assert( ignore ) ((void)0)
#endif
/**
Call this to set the printf function to use for logging.
@param function The printf callback function.
*/
void yojimbo_set_printf_function( int (*function)( const char * /*format*/, ... ) );
/**
Call this to set the function to call when an assert triggers.
@param function The assert callback function.
*/
void yojimbo_set_assert_function( void (*function)( const char * /*condition*/, const char * /*function*/, const char * /*file*/, int /*line*/ ) );
#include <stdint.h>
#include <new>
#if YOJIMBO_DEBUG_MEMORY_LEAKS
#include <map>
#endif // YOJIMBO_DEBUG_MEMORY_LEAKS
typedef void* tlsf_t;
namespace yojimbo
{
/**
Get the default allocator.
Use this allocator when you just want to use malloc/free, but in the form of a yojimbo allocator.
This allocator instance is created inside InitializeYojimbo and destroyed in ShutdownYojimbo.
In debug build, it will automatically check for memory leaks and print them out for you when you shutdown the library.
@returns The default allocator instances backed by malloc and free.
*/
class Allocator & GetDefaultAllocator();
/// Macro for creating a new object instance with a yojimbo allocator.
#define YOJIMBO_NEW( a, T, ... ) ( new ( (a).Allocate( sizeof(T), __FILE__, __LINE__ ) ) T(__VA_ARGS__) )
/// Macro for deleting an object created with a yojimbo allocator.
#define YOJIMBO_DELETE( a, T, p ) do { if (p) { (p)->~T(); (a).Free( p, __FILE__, __LINE__ ); p = NULL; } } while (0)
/// Macro for allocating a block of memory with a yojimbo allocator.
#define YOJIMBO_ALLOCATE( a, bytes ) (a).Allocate( (bytes), __FILE__, __LINE__ )
/// Macro for freeing a block of memory created with a yojimbo allocator.
#define YOJIMBO_FREE( a, p ) do { if ( p ) { (a).Free( p, __FILE__, __LINE__ ); p = NULL; } } while(0)
/// Allocator error level.
enum AllocatorErrorLevel
{
ALLOCATOR_ERROR_NONE = 0, ///< No error. All is well.
ALLOCATOR_ERROR_OUT_OF_MEMORY ///< The allocator is out of memory!
};
/// Helper function to convert an allocator error to a user friendly string.
inline const char * GetAllocatorErrorString( AllocatorErrorLevel error )
{
switch ( error )
{
case ALLOCATOR_ERROR_NONE: return "none";
case ALLOCATOR_ERROR_OUT_OF_MEMORY: return "out of memory";
default:
yojimbo_assert( false );
return "(unknown)";
}
}
#if YOJIMBO_DEBUG_MEMORY_LEAKS
/**
Debug structure used to track allocations and find memory leaks.
Active in debug build only. Disabled in release builds for performance reasons.
*/
struct AllocatorEntry
{
size_t size; ///< The size of the allocation in bytes.
const char * file; ///< Filename of the source code file that made the allocation.
int line; ///< Line number in the source code where the allocation was made.
};
#endif // #if YOJIMBO_DEBUG_MEMORY_LEAKS
/**
Functionality common to all allocators.
Extend this class to hook up your own allocator to yojimbo.
IMPORTANT: This allocator is not yet thread safe. Only call it from one thread!
*/
class Allocator
{
public:
/**
Allocator constructor.
Sets the error level to ALLOCATOR_ERROR_NONE.
*/
Allocator();
/**
Allocator destructor.
Make sure all allocations made from this allocator are freed before you destroy this allocator.
In debug build, validates this is true walks the map of allocator entries. Any outstanding entries are considered memory leaks and printed to stdout.
*/
virtual ~Allocator();
/**
Allocate a block of memory.
IMPORTANT: Don't call this directly. Use the YOJIMBO_NEW or YOJIMBO_ALLOCATE macros instead, because they automatically pass in the source filename and line number for you.
@param size The size of the block of memory to allocate (bytes).
@param file The source code filename that is performing the allocation. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the allocation.
@returns A block of memory of the requested size, or NULL if the allocation could not be performed. If NULL is returned, the error level is set to ALLOCATION_ERROR_FAILED_TO_ALLOCATE.
@see Allocator::Free
@see Allocator::GetErrorLevel
*/
virtual void * Allocate( size_t size, const char * file, int line ) = 0;
/**
Free a block of memory.
IMPORTANT: Don't call this directly. Use the YOJIMBO_DELETE or YOJIMBO_FREE macros instead, because they automatically pass in the source filename and line number for you.
@param p Pointer to the block of memory to free. Must be non-NULL block of memory that was allocated with this allocator. Will assert otherwise.
@param file The source code filename that is performing the free. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the free.
@see Allocator::Allocate
@see Allocator::GetErrorLevel
*/
virtual void Free( void * p, const char * file, int line ) = 0;
/**
Get the allocator error level.
Use this function to check if an allocation has failed. This is used in the client/server to disconnect a client with a failed allocation.
@returns The allocator error level.
*/
AllocatorErrorLevel GetErrorLevel() const { return m_errorLevel; }
/**
Clear the allocator error level back to default.
*/
void ClearError() { m_errorLevel = ALLOCATOR_ERROR_NONE; }
protected:
/**
Set the error level.
For correct client/server behavior when an allocation fails, please make sure you call this method to set the error level to ALLOCATOR_ERROR_FAILED_TO_ALLOCATE.
@param error The allocator error level to set.
*/
void SetErrorLevel( AllocatorErrorLevel errorLevel );
/**
Call this function to track an allocation made by your derived allocator class.
In debug build, tracked allocations are automatically checked for leaks when the allocator is destroyed.
@param p Pointer to the memory that was allocated.
@param size The size of the allocation in bytes.
@param file The source code file that performed the allocation.
@param line The line number in the source file where the allocation was performed.
*/
void TrackAlloc( void * p, size_t size, const char * file, int line );
/**
Call this function to track a free made by your derived allocator class.
In debug build, any allocation tracked without a corresponding free is considered a memory leak when the allocator is destroyed.
@param p Pointer to the memory that was allocated.
@param file The source code file that is calling in to free the memory.
@param line The line number in the source file where the free is being called from.
*/
void TrackFree( void * p, const char * file, int line );
AllocatorErrorLevel m_errorLevel; ///< The allocator error level.
#if YOJIMBO_DEBUG_MEMORY_LEAKS
std::map<void*,AllocatorEntry> m_alloc_map; ///< Debug only data structure used to find and report memory leaks.
#endif // #if YOJIMBO_DEBUG_MEMORY_LEAKS
private:
Allocator( const Allocator & other );
Allocator & operator = ( const Allocator & other );
};
/**
The default allocator implementation based around malloc and free.
*/
class DefaultAllocator : public Allocator
{
public:
/**
Default constructor.
*/
DefaultAllocator() {}
/**
Allocates a block of memory using "malloc".
IMPORTANT: Don't call this directly. Use the YOJIMBO_NEW or YOJIMBO_ALLOCATE macros instead, because they automatically pass in the source filename and line number for you.
@param size The size of the block of memory to allocate (bytes).
@param file The source code filename that is performing the allocation. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the allocation.
@returns A block of memory of the requested size, or NULL if the allocation could not be performed. If NULL is returned, the error level is set to ALLOCATION_ERROR_FAILED_TO_ALLOCATE.
*/
void * Allocate( size_t size, const char * file, int line );
/**
Free a block of memory by calling "free".
IMPORTANT: Don't call this directly. Use the YOJIMBO_DELETE or YOJIMBO_FREE macros instead, because they automatically pass in the source filename and line number for you.
@param p Pointer to the block of memory to free. Must be non-NULL block of memory that was allocated with this allocator. Will assert otherwise.
@param file The source code filename that is performing the free. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the free.
*/
void Free( void * p, const char * file, int line );
private:
DefaultAllocator( const DefaultAllocator & other );
DefaultAllocator & operator = ( const DefaultAllocator & other );
};
/**
An allocator built on the TLSF allocator implementation by Matt Conte. Thanks Matt!
This is a fast allocator that supports multiple heaps. It's used inside the yojimbo server to silo allocations for each client to their own heap.
See https://github.com/mattconte/tlsf for details on this allocator implementation.
*/
class TLSF_Allocator : public Allocator
{
public:
/**
TLSF allocator constructor.
If you want to integrate your own allocator with yojimbo for use with the client and server, this class is a good template to start from.
Make sure your constructor has the same signature as this one, and it will work with the YOJIMBO_SERVER_ALLOCATOR and YOJIMBO_CLIENT_ALLOCATOR helper macros.
@param memory Block of memory in which the allocator will work. This block must remain valid while this allocator exists. The allocator does not assume ownership of it, you must free it elsewhere, if necessary.
@param bytes The size of the block of memory (bytes). The maximum amount of memory you can allocate will be less, due to allocator overhead.
*/
TLSF_Allocator( void * memory, size_t bytes );
/**
TLSF allocator destructor.
Checks for memory leaks in debug build. Free all memory allocated by this allocator before destroying.
*/
~TLSF_Allocator();
/**
Allocates a block of memory using TLSF.
IMPORTANT: Don't call this directly. Use the YOJIMBO_NEW or YOJIMBO_ALLOCATE macros instead, because they automatically pass in the source filename and line number for you.
@param size The size of the block of memory to allocate (bytes).
@param file The source code filename that is performing the allocation. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the allocation.
@returns A block of memory of the requested size, or NULL if the allocation could not be performed. If NULL is returned, the error level is set to ALLOCATION_ERROR_FAILED_TO_ALLOCATE.
*/
void * Allocate( size_t size, const char * file, int line );
/**
Free a block of memory using TLSF.
IMPORTANT: Don't call this directly. Use the YOJIMBO_DELETE or YOJIMBO_FREE macros instead, because they automatically pass in the source filename and line number for you.
@param p Pointer to the block of memory to free. Must be non-NULL block of memory that was allocated with this allocator. Will assert otherwise.
@param file The source code filename that is performing the free. Used for tracking allocations and reporting on memory leaks.
@param line The line number in the source code file that is performing the free.
@see Allocator::Allocate
@see Allocator::GetError
*/
void Free( void * p, const char * file, int line );
private:
tlsf_t m_tlsf; ///< The TLSF allocator instance backing this allocator.
TLSF_Allocator( const TLSF_Allocator & other );
TLSF_Allocator & operator = ( const TLSF_Allocator & other );
};
/**
Generate cryptographically secure random data.
@param data The buffer to store the random data.
@param bytes The number of bytes of random data to generate.
*/
void random_bytes( uint8_t * data, int bytes );
/**
Generate a random integer between a and b (inclusive).
IMPORTANT: This is not a cryptographically secure random. It's used only for test functions and in the network simulator.
@param a The minimum integer value to generate.
@param b The maximum integer value to generate.
@returns A pseudo random integer value in [a,b].
*/
inline int random_int( int a, int b )
{
yojimbo_assert( a < b );
int result = a + rand() % ( b - a + 1 );
yojimbo_assert( result >= a );
yojimbo_assert( result <= b );
return result;
}
/**
Generate a random float between a and b.
IMPORTANT: This is not a cryptographically secure random. It's used only for test functions and in the network simulator.
@param a The minimum integer value to generate.
@param b The maximum integer value to generate.
@returns A pseudo random float value in [a,b].
*/
inline float random_float( float a, float b )
{
yojimbo_assert( a < b );
float random = ( (float) rand() ) / (float) RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
/**
Calculates the population count of an unsigned 32 bit integer at compile time.
Population count is the number of bits in the integer that set to 1.
See "Hacker's Delight" and http://www.hackersdelight.org/hdcodetxt/popArrayHS.c.txt
@see yojimbo::Log2
@see yojimbo::BitsRequired
*/
template <uint32_t x> struct PopCount
{
enum { a = x - ( ( x >> 1 ) & 0x55555555 ),
b = ( ( ( a >> 2 ) & 0x33333333 ) + ( a & 0x33333333 ) ),
c = ( ( ( b >> 4 ) + b ) & 0x0f0f0f0f ),
d = c + ( c >> 8 ),
e = d + ( d >> 16 ),
result = e & 0x0000003f
};
};
/**
Calculates the log 2 of an unsigned 32 bit integer at compile time.
@see yojimbo::Log2
@see yojimbo::BitsRequired
*/
template <uint32_t x> struct Log2
{
enum { a = x | ( x >> 1 ),
b = a | ( a >> 2 ),
c = b | ( b >> 4 ),
d = c | ( c >> 8 ),
e = d | ( d >> 16 ),
f = e >> 1,
result = PopCount<f>::result
};
};
/**
Calculates the number of bits required to serialize an integer value in [min,max] at compile time.
@see Log2
@see PopCount
*/
template <int64_t min, int64_t max> struct BitsRequired
{
static const uint32_t result = ( min == max ) ? 0 : ( Log2<uint32_t(max-min)>::result + 1 );
};
/**
Calculates the population count of an unsigned 32 bit integer.
The population count is the number of bits in the integer set to 1.
@param x The input integer value.
@returns The number of bits set to 1 in the input value.
*/
inline uint32_t popcount( uint32_t x )
{
#ifdef __GNUC__
return __builtin_popcount( x );
#else // #ifdef __GNUC__
const uint32_t a = x - ( ( x >> 1 ) & 0x55555555 );
const uint32_t b = ( ( ( a >> 2 ) & 0x33333333 ) + ( a & 0x33333333 ) );
const uint32_t c = ( ( ( b >> 4 ) + b ) & 0x0f0f0f0f );
const uint32_t d = c + ( c >> 8 );
const uint32_t e = d + ( d >> 16 );
const uint32_t result = e & 0x0000003f;
return result;
#endif // #ifdef __GNUC__
}
/**
Calculates the log base 2 of an unsigned 32 bit integer.
@param x The input integer value.
@returns The log base 2 of the input.
*/
inline uint32_t log2( uint32_t x )
{
const uint32_t a = x | ( x >> 1 );
const uint32_t b = a | ( a >> 2 );
const uint32_t c = b | ( b >> 4 );
const uint32_t d = c | ( c >> 8 );
const uint32_t e = d | ( d >> 16 );
const uint32_t f = e >> 1;
return popcount( f );
}
/**
Calculates the number of bits required to serialize an integer in range [min,max].
@param min The minimum value.
@param max The maximum value.
@returns The number of bits required to serialize the integer.
*/
inline int bits_required( uint32_t min, uint32_t max )
{
#ifdef __GNUC__
return ( min == max ) ? 0 : 32 - __builtin_clz( max - min );
#else // #ifdef __GNUC__
return ( min == max ) ? 0 : log2( max - min ) + 1;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 64 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint64_t bswap( uint64_t value )
{
#ifdef __GNUC__
return __builtin_bswap64( value );
#else // #ifdef __GNUC__
value = ( value & 0x00000000FFFFFFFF ) << 32 | ( value & 0xFFFFFFFF00000000 ) >> 32;
value = ( value & 0x0000FFFF0000FFFF ) << 16 | ( value & 0xFFFF0000FFFF0000 ) >> 16;
value = ( value & 0x00FF00FF00FF00FF ) << 8 | ( value & 0xFF00FF00FF00FF00 ) >> 8;
return value;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 32 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint32_t bswap( uint32_t value )
{
#ifdef __GNUC__
return __builtin_bswap32( value );
#else // #ifdef __GNUC__
return ( value & 0x000000ff ) << 24 | ( value & 0x0000ff00 ) << 8 | ( value & 0x00ff0000 ) >> 8 | ( value & 0xff000000 ) >> 24;
#endif // #ifdef __GNUC__
}
/**
Reverse the order of bytes in a 16 bit integer.
@param value The input value.
@returns The input value with the byte order reversed.
*/
inline uint16_t bswap( uint16_t value )
{
return ( value & 0x00ff ) << 8 | ( value & 0xff00 ) >> 8;
}
/**
Template to convert an integer value from local byte order to network byte order.
IMPORTANT: Because most machines running yojimbo are little endian, yojimbo defines network byte order to be little endian.
@param value The input value in local byte order. Supported integer types: uint64_t, uint32_t, uint16_t.
@returns The input value converted to network byte order. If this processor is little endian the output is the same as the input. If the processor is big endian, the output is the input byte swapped.
@see yojimbo::bswap
*/
template <typename T> T host_to_network( T value )
{
#if YOJIMBO_BIG_ENDIAN
return bswap( value );
#else // #if YOJIMBO_BIG_ENDIAN
return value;
#endif // #if YOJIMBO_BIG_ENDIAN
}
/**
Template to convert an integer value from network byte order to local byte order.
IMPORTANT: Because most machines running yojimbo are little endian, yojimbo defines network byte order to be little endian.
@param value The input value in network byte order. Supported integer types: uint64_t, uint32_t, uint16_t.
@returns The input value converted to local byte order. If this processor is little endian the output is the same as the input. If the processor is big endian, the output is the input byte swapped.
@see yojimbo::bswap
*/
template <typename T> T network_to_host( T value )
{
#if YOJIMBO_BIG_ENDIAN
return bswap( value );
#else // #if YOJIMBO_BIG_ENDIAN
return value;
#endif // #if YOJIMBO_BIG_ENDIAN
}
/**
Compares two 16 bit sequence numbers and returns true if the first one is greater than the second (considering wrapping).
IMPORTANT: This is not the same as s1 > s2!
Greater than is defined specially to handle wrapping sequence numbers.
If the two sequence numbers are close together, it is as normal, but they are far apart, it is assumed that they have wrapped around.
Thus, sequence_greater_than( 1, 0 ) returns true, and so does sequence_greater_than( 0, 65535 )!
@param s1 The first sequence number.
@param s2 The second sequence number.
@returns True if the s1 is greater than s2, with sequence number wrapping considered.
*/
inline bool sequence_greater_than( uint16_t s1, uint16_t s2 )
{
return ( ( s1 > s2 ) && ( s1 - s2 <= 32768 ) ) ||
( ( s1 < s2 ) && ( s2 - s1 > 32768 ) );
}
/**
Compares two 16 bit sequence numbers and returns true if the first one is less than the second (considering wrapping).
IMPORTANT: This is not the same as s1 < s2!
Greater than is defined specially to handle wrapping sequence numbers.
If the two sequence numbers are close together, it is as normal, but they are far apart, it is assumed that they have wrapped around.
Thus, sequence_less_than( 0, 1 ) returns true, and so does sequence_greater_than( 65535, 0 )!
@param s1 The first sequence number.
@param s2 The second sequence number.
@returns True if the s1 is less than s2, with sequence number wrapping considered.
*/
inline bool sequence_less_than( uint16_t s1, uint16_t s2 )
{
return sequence_greater_than( s2, s1 );
}
/**
Convert a signed integer to an unsigned integer with zig-zag encoding.
0,-1,+1,-2,+2... becomes 0,1,2,3,4 ...
@param n The input value.
@returns The input value converted from signed to unsigned with zig-zag encoding.
*/
inline int signed_to_unsigned( int n )
{
return ( n << 1 ) ^ ( n >> 31 );