-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathfinal_memory.h
More file actions
761 lines (647 loc) · 23.8 KB
/
Copy pathfinal_memory.h
File metadata and controls
761 lines (647 loc) · 23.8 KB
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
/***
final_memory.h
-------------------------------------------------------------------------------
About
-------------------------------------------------------------------------------
An open source single header file library for using heap memory like a stack.
The only dependencies are a C99 compliant compiler.
-------------------------------------------------------------------------------
Getting started
-------------------------------------------------------------------------------
- Drop this file into your main C/C++ project and include it in one place you want.
- Define FMEM_IMPLEMENTATION before including this header file in your main translation unit.
-------------------------------------------------------------------------------
Usage growable memory (Default case)
-------------------------------------------------------------------------------
#define FMEM_IMPLEMENTATION
#include <final_mem.h>
fmemMemoryBlock myMem;
if (fmemInit(&myMem, fmemFlags_Growable, FMEM_MEGABYTES(16))) {
// Uses the first memory block
uint8_t *smallData = fmemPushSize(&myMem, FMEM_MEGABYTES(3), fmemFlags_None);
// Adds another memory block
uint8_t *bigData = fmemPushSize(&myMem, FMEM_MEGABYTES(64), fmemFlags_None);
...
// Uses the first memory block
uint8_t *anotherBlock = fmemPushSize(&myMem, FMEM_MEGABYTES(5), fmemFlags_None);
// Does not fit in the first block, therefore uses the second block
uint8_t *anotherBiggerBlock = fmemPushSize(&myMem, FMEM_MEGABYTES(9), fmemFlags_None);
// Releases all memory blocks
fmemRelease(&myMem);
}
// ........................
fmemMemoryBlock myMem2;
if (fmemInit(&myMem2, fmemFlags_Growable, 0)) {
// Allocates the first block, because it was not allocated beforehand
uint8_t *data = fmemPushSize(&myMem2, FMEM_MEGABYTES(3), fmemFlags_None);
// ...
// Releases all memory blocks
fmemRelease(&myMem2);
}
// ........................
// For growable memory, init is not required when it is initialized to zero
fmemMemoryBlock myMem3 = {0};
// Allocates the first block, because it was not allocated initially
uint8_t *data = fmemPushSize(&myMem3, FMEM_MEGABYTES(3), fmemFlags_None);
// ...
// Releases all memory blocks
fmemRelease(&myMem3);
-------------------------------------------------------------------------------
Usage fixed/static memory
-------------------------------------------------------------------------------
#define FMEM_IMPLEMENTATION
#include <final_mem.h>
fmemMemoryBlock myMem;
if (fmemInit(&myMem, fmemFlags_Fixed, FMEM_MEGABYTES(16))) {
uint32_t *data = (uint32_t *)fmemPushSize(&myMem, sizeof(uint32_t) * 10, fmemFlags_None);
data[0] = 1;
data[1] = 2;
// Returns null, size does not fit in stack block
uint8_t *bigData = fmemPushSize(&myMem, FMEM_MEGABYTES(32), fmemFlags_None);
...
fmemRelease(&myMem);
}
-------------------------------------------------------------------------------
Usage temporary memory
-------------------------------------------------------------------------------
#define FMEM_IMPLEMENTATION
#include <final_mem.h>
fmemMemoryBlock myMem;
if (fmemInit(&myMem, fmemFlags_Growable, FMEM_MEGABYTES(16))) {
uint8_t *data = fmemPushSize(&myMem, FMEM_MEGABYTES(4), fmemFlags_None);
data[0] = 1;
data[1] = 2;
// Use remaining size of the source memory block
// Source memory block is locked now and cannot be used until the temporary memory is released
fmemMemoryBlock tempMem;
if (fmemBeginTemporary(&myMem, &tempMem)) {
fmemEndTemporary(&tempMem);
}
// Source memory is restored and unlocked
uint8_t *moreData = fmemPushSize(&myMem, FMEM_MEGABYTES(2), fmemFlags_None);
moreData[0] = 128;
moreData[1] = 223;
fmemRelease(&myMem);
}
-------------------------------------------------------------------------------
License
-------------------------------------------------------------------------------
Final Memory is released under the following license:
MIT License
Copyright (c) 2017-2026 Torsten Spaete
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
***/
/*!
\file final_memory.h
\version v1.0.1
\author Torsten Spaete
\brief Final Memory (FMEM) - An open source C99 single file header memory library.
*/
/*!
\page page_changelog Changelog
\tableofcontents
## v1.0.1:
- Changed: Moved FMEM_MEMSET, FMEM_MALLOC, FMEM_ASSERT into the implementation block
## v1.0.0:
- New: Added fmemPushArray() to allocate an array with a type
- New: Added fmemPushString() to allocate a zero-terminated string
## v0.3.1 alpha:
- Changed: fmemCreate() has now a minBlockSize argument, that defines the block alignment size
- New: Added fmemPushFlags_ForceBlock enum value to fmemPushFlags, that indicates that the following push always allocates a new block
## v0.3.0 alpha:
- New: Added macro fmemPushStruct()
- New: Added function fmemCreate()
## v0.2.1 alpha:
- Fixed: Two inline functions were not found in GCC
## v0.2 alpha:
- Added: New function fmemGetHeader
- Added: Safety check for fmemBeginTemporary when passing a temporary block as source
- Fixed: Memory is no longer wasted
- Fixed: Fixed crash when fmemGetTotalSize was passed a fixed-size block
- Fixed: Fixed crash when fmemGetRemainingSize was passed a fixed-size block
- Changed: fmemType_Fixed does not allocate in sized-block anymore, instead it uses the desired size + meta size
## v0.1.0 alpha:
- Initial version
*/
/*!
\page page_todo Todo
\tableofcontents
- Removal of single memory blocks
- Array allocation and pushing
- Memory partitions
- Separated but linked, not able to free linked block
- Just partitions of fixed size blocks
*/
#ifndef FMEM_H
#define FMEM_H
// Detect compiler
#if !defined(__cplusplus) && ((defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || (defined(_MSC_VER) && (_MSC_VER >= 1900)))
# define FMEM_IS_C99
#elif defined(__cplusplus)
# define FMEM_IS_CPP
#else
# error "This C/C++ compiler is not supported!"
#endif
// Api export
#if defined(FMEM_PRIVATE)
# define fmem_api static
#else
# define fmem_api extern
#endif
#if defined(FMEM_IS_C99)
//! Initialize a struct to zero (C99)
# define FMEM_ZERO_INIT {0}
#else
//! Initialize a struct to zero (C++)
# define FMEM_ZERO_INIT {}
#endif
// Includes
#include <stdint.h> // int32_t, etc.
#include <stdbool.h> // bool
#include <stddef.h> // NULL
//! Null pointer
#define fmem_null NULL
//! Returns the number of bytes for the given kilobytes
#define FMEM_KILOBYTES(value) (((value) * 1024ull))
//! Returns the number of bytes for the given megabytes
#define FMEM_MEGABYTES(value) ((FMEM_KILOBYTES(value) * 1024ull))
//! Returns the number of bytes for the given gigabytes
#define FMEM_GIGABYTES(value) ((FMEM_MEGABYTES(value) * 1024ull))
//! Returns the number of bytes for the given terabytes
#define FMEM_TERABYTES(value) ((FMEM_GIGABYTES(value) * 1024ull))
/*! \brief Flags controlling a single @ref fmemPush call. */
typedef enum fmemPushFlags {
//! No push flags
fmemPushFlags_None = 0,
//! Clear region to zero
fmemPushFlags_Clear = 1 << 0,
//! Indicates that a push always creates a memory block for the allocation
fmemPushFlags_ForceBlock = 1 << 1,
} fmemPushFlags;
/*! \brief Kind of an @ref fmemMemoryBlock — controls growth and ownership semantics. */
typedef enum fmemType {
//! Unlimited size, grows additional blocks if needed
fmemType_Growable = 0,
//! Limited to a fixed size
fmemType_Fixed,
//! Temporary memory
fmemType_Temporary,
} fmemType;
/*! \brief Push permission flag stored on a block (allow or deny further pushes). */
typedef enum fmemPermission {
//! Allowed
fmemPermission_Allowed = 0,
//! Denied
fmemPermission_Denied,
} fmemPermission;
/*! \brief Internal linked-list header that precedes the payload of each allocated block. */
typedef struct fmemBlockHeader {
//! Previous block
struct fmemMemoryBlock *prev;
//! Next block
struct fmemMemoryBlock *next;
} fmemBlockHeader;
/*! \brief A memory block used as a stack allocator (fixed, growable, or temporary). */
typedef struct fmemMemoryBlock {
//! Source memory pointer if present
void *source;
//! Base memory pointer
void *base;
//! Pointer to a temporary memory block
struct fmemMemoryBlock *temporary;
//! Total size in bytes
size_t size;
//! Used size in bytes
size_t used;
//! Total number of blocks
size_t totalBlockCount;
//! Minimum size per block, regardless of the size (If zero, the default is used: One page 4096 bytes)
size_t minBlockSize;
//! Type
fmemType type;
//! Push permission.
fmemPermission allowPush;
} fmemMemoryBlock;
//! Creates a memory block and allocates memory when size is greater than zero
fmem_api fmemMemoryBlock fmemCreate(const fmemType type, const size_t size, const size_t minBlockSize);
//! Initializes the given block or allocates memory when size is greater than zero
fmem_api bool fmemInit(fmemMemoryBlock *block, const fmemType type, const size_t size, const size_t minBlockSize);
//! Initializes the given block to a fixed size block from existing source memory
fmem_api bool fmemInitFromSource(fmemMemoryBlock *block, void *sourceMemory, const size_t sourceSize);
//! Release this and all appended memory blocks
fmem_api void fmemFree(fmemMemoryBlock *block);
//! Release all appended children memory blocks
fmem_api void fmemFreeChildren(fmemMemoryBlock *block);
//! Gets memory from the block by the given size
fmem_api uint8_t *fmemPush(fmemMemoryBlock *block, const size_t size, const fmemPushFlags flags);
//! Gets memory from the block by the given size and ensure address alignment
fmem_api uint8_t *fmemPushAligned(fmemMemoryBlock *block, const size_t size, const size_t alignment, const fmemPushFlags flags);
//! Gets memory for a new block with the given size
fmem_api bool fmemPushBlock(fmemMemoryBlock *src, fmemMemoryBlock *dst, const size_t size, const fmemPushFlags flags);
//! Returns the remaining size of all blocks starting by the given block
fmem_api size_t fmemGetRemainingSize(fmemMemoryBlock *block);
//! Returns the total size of all blocks starting by the given block
fmem_api size_t fmemGetTotalSize(fmemMemoryBlock *block);
//! Resets the given block usage to zero without freeing any memory
fmem_api void fmemReset(fmemMemoryBlock *block);
//! Initializes a temporary block with the remaining size of the source block
fmem_api bool fmemBeginTemporary(fmemMemoryBlock *source, fmemMemoryBlock *temporary);
//! Gives the memory back to source block from the temporary block
fmem_api void fmemEndTemporary(fmemMemoryBlock *temporary);
//! Returns the block header pointer for the given block
fmem_api fmemBlockHeader *fmemGetHeader(fmemMemoryBlock *block);
//! Gets memory for a struct from the block and return a pointer to the struct
#define fmemPushStruct(block, type, flags) (type *)fmemPush(block, sizeof(type), flags)
//! Gets memory for an array with the specified type from the block and returns a pointer to the array.
#define fmemPushArray(block, type, count, flags) (type *)fmemPush(block, sizeof(type) * (count), flags)
//! Gets memory for a null-terminated string with the specified length from the block and return a pointer to the base
#define fmemPushString(block, len, flags) (char *)fmemPush(block, sizeof(char) * ((len) + 1), flags)
#endif // FMEM_H
#if defined(FMEM_IMPLEMENTATION) && !defined(FMEM_IMPLEMENTED)
#define FMEM_IMPLEMENTED
// Functions override
#ifndef FMEM_MEMSET
# include <string.h>
# define FMEM_MEMSET(dst, val, size) memset(dst, val, size)
#endif
#ifndef FMEM_MALLOC
# include <malloc.h>
# define FMEM_MALLOC(size) malloc(size)
# define FMEM_FREE(ptr) free(ptr)
#endif
#if !defined(FMEM_ASSERT) || !defined(FMEM_STATIC_ASSERT)
# include <assert.h>
# define FMEM_ASSERT(exp) assert(exp)
# define FMEM_STATIC_ASSERT(exp) static_assert(exp)
#endif
//! Default spacing after the header
#define FMEM__HEADER_SPACING sizeof(uintptr_t)
//! Default block size = Page size
#define FMEM__MIN_BLOCKSIZE 4096
//! Size of the meta data for the block (Header+Spacing+Block+Spacing)
#define FMEM__BLOCK_META_SIZE (sizeof(fmemBlockHeader) + FMEM__HEADER_SPACING + sizeof(fmemMemoryBlock) + FMEM__HEADER_SPACING)
//! Offset to block from the header
#define FMEM__OFFSET_TO_BLOCK (sizeof(fmemBlockHeader) + FMEM__HEADER_SPACING)
//! Returns the header from the given block
#define FMEM__GETHEADER(block) (fmemBlockHeader *)((uint8_t *)(block)->base - (FMEM__BLOCK_META_SIZE))
//! Returns the header from the given block
#define FMEM__GETBLOCK(header) (fmemMemoryBlock *)((uint8_t *)(header) + (FMEM__OFFSET_TO_BLOCK))
static size_t fmem__GetSpaceAvailableFor(const fmemMemoryBlock *block, const size_t size) {
size_t result = ((block->size > 0) && (block->used <= block->size)) ? ((block->size - block->used) - size) : 0;
return(result);
}
static size_t fmem__RoundToSize(const size_t size, const size_t roundSize) {
size_t count = (size / roundSize) + 1;
size_t result = count * roundSize;
return(result);
}
static fmemBlockHeader *fmem__AllocateBlock(const size_t blockSize) {
FMEM_ASSERT(blockSize >= FMEM__BLOCK_META_SIZE);
void *base = FMEM_MALLOC(blockSize);
if (base == fmem_null) {
return fmem_null;
}
fmemBlockHeader *header = (fmemBlockHeader *)base;
FMEM_MEMSET(header, 0, sizeof(*header));
fmemMemoryBlock *nextBlock = FMEM__GETBLOCK(header);
FMEM_MEMSET(nextBlock, 0, sizeof(*nextBlock));
return(header);
}
static void fmem__FreeBlock(fmemBlockHeader *header) {
FMEM_ASSERT(header != fmem_null);
FMEM_FREE(header);
}
fmem_api fmemBlockHeader *fmemGetHeader(fmemMemoryBlock *block) {
if (block == fmem_null) {
return fmem_null;
}
if (block->base == fmem_null) {
return fmem_null;
}
fmemBlockHeader *header = (fmemBlockHeader *)block->base;
return(header);
}
fmem_api size_t fmemGetRemainingSize(fmemMemoryBlock *block) {
if (block == fmem_null) {
return 0;
}
size_t result = 0;
fmemMemoryBlock *testBlock = block;
while (testBlock != fmem_null) {
if (testBlock->base == fmem_null || testBlock->size == 0) {
break;
}
result += fmem__GetSpaceAvailableFor(testBlock, 0);
if (testBlock->type != fmemType_Growable) {
break;
}
fmemBlockHeader *header = FMEM__GETHEADER(testBlock);
testBlock = header->next;
}
return(result);
}
fmem_api size_t fmemGetTotalSize(fmemMemoryBlock *block) {
if (block == fmem_null) {
return 0;
}
size_t result = 0;
fmemMemoryBlock *testBlock = block;
while (testBlock != fmem_null) {
if (testBlock->base == fmem_null || testBlock->size == 0) {
break;
}
size_t sizeForBlock = testBlock->size;
result += sizeForBlock;
if (testBlock->type != fmemType_Growable) {
break;
}
fmemBlockHeader *header = FMEM__GETHEADER(testBlock);
testBlock = header->next;
}
return(result);
}
fmem_api fmemMemoryBlock fmemCreate(const fmemType type, const size_t size, const size_t minBlockSize) {
fmemMemoryBlock result;
FMEM_MEMSET(&result, 0, sizeof(result));
fmemInit(&result, type, size, minBlockSize);
return(result);
}
fmem_api bool fmemInit(fmemMemoryBlock *block, const fmemType type, const size_t size, const size_t minBlockSize) {
if (block == fmem_null) {
return(false);
}
if (type == fmemType_Fixed && size == 0) {
return(false);
}
if (type == fmemType_Temporary) {
return(false);
}
size_t actualMinBlockSize;
if (minBlockSize == 0) {
actualMinBlockSize = FMEM__MIN_BLOCKSIZE;
} else if (minBlockSize > FMEM__MIN_BLOCKSIZE) {
actualMinBlockSize = fmem__RoundToSize(minBlockSize, FMEM__MIN_BLOCKSIZE);
} else {
actualMinBlockSize = FMEM__MIN_BLOCKSIZE;
}
FMEM_MEMSET(block, 0, sizeof(*block));
block->type = type;
block->minBlockSize = actualMinBlockSize;
if (size > 0) {
size_t blockSize;
size_t requiredSize = size + FMEM__BLOCK_META_SIZE;
if (type == fmemType_Fixed) {
blockSize = requiredSize;
} else {
blockSize = fmem__RoundToSize(requiredSize, actualMinBlockSize);
}
fmemBlockHeader *header = fmem__AllocateBlock(blockSize);
if (header == fmem_null) {
return(false);
}
block->base = (uint8_t *)header + FMEM__BLOCK_META_SIZE;
block->size = blockSize - FMEM__BLOCK_META_SIZE;
}
return(true);
}
fmem_api bool fmemInitFromSource(fmemMemoryBlock *block, void *sourceMemory, const size_t sourceSize) {
if ((block == fmem_null) || (sourceSize == 0)) {
return(false);
}
if (sourceMemory == fmem_null || sourceSize == 0) {
return(false);
}
FMEM_MEMSET(block, 0, sizeof(*block));
block->type = fmemType_Fixed;
block->base = sourceMemory;
block->size = sourceSize;
block->source = sourceMemory;
return(true);
}
fmem_api void fmemFree(fmemMemoryBlock *block) {
if ((block != fmem_null) &&
(block->temporary == fmem_null) &&
(block->source != fmem_null)) {
fmemMemoryBlock *freeBlock = block;
while (freeBlock != fmem_null) {
if (freeBlock->base == fmem_null || freeBlock->size == 0 || freeBlock->source != fmem_null) {
break;
}
fmemBlockHeader *header = FMEM__GETHEADER(freeBlock);
fmemMemoryBlock *next = header->next;
fmem__FreeBlock(header);
freeBlock = next;
}
FMEM_MEMSET(block, 0, sizeof(*block));
}
}
fmem_api void fmemFreeChildren(fmemMemoryBlock *block) {
if (block != fmem_null && block->size > 0) {
fmemBlockHeader *firstHeader = FMEM__GETHEADER(block);
fmemMemoryBlock *freeBlock = firstHeader->next;
while (freeBlock != fmem_null) {
if (freeBlock->base == fmem_null || freeBlock->size == 0 || freeBlock->source != fmem_null) {
break;
}
fmemBlockHeader *header = FMEM__GETHEADER(freeBlock);
fmemMemoryBlock *next = header->next;
fmem__FreeBlock(header);
freeBlock = next;
}
firstHeader->next = firstHeader->prev = fmem_null;
block->used = 0;
block->totalBlockCount = 1;
}
}
fmem_api uint8_t *fmemPush(fmemMemoryBlock *block, const size_t size, const fmemPushFlags flags) {
if (block == fmem_null || size == 0) {
return fmem_null;
}
if (block->temporary != fmem_null) {
return fmem_null;
}
fmemMemoryBlock *bestBlock = fmem_null;
bool isForcedBlock = (flags & fmemPushFlags_ForceBlock) == fmemPushFlags_ForceBlock;
if (!isForcedBlock) {
// Find best fitting block (Most space available after append)
fmemMemoryBlock *searchBlock = block;
while (searchBlock != fmem_null) {
if (searchBlock->base == fmem_null || searchBlock->size == 0) {
// Broken block
break;
}
if (searchBlock->allowPush == fmemPermission_Allowed) {
if ((searchBlock->used + size) <= searchBlock->size) {
if (bestBlock == fmem_null || (fmem__GetSpaceAvailableFor(searchBlock, size) > fmem__GetSpaceAvailableFor(bestBlock, size))) {
bestBlock = searchBlock;
}
}
}
fmemBlockHeader *header = FMEM__GETHEADER(searchBlock);
if (searchBlock->type != fmemType_Growable) {
break;
}
searchBlock = header->next;
}
}
// Stupid compiler, i dont care about crosses initialization for labels
fmemMemoryBlock *newBlock;
fmemMemoryBlock *tailBlock;
fmemBlockHeader *newHeader;
fmemBlockHeader *tailHeader;
size_t blockSize;
// @NOTE(final): Do not initialize, because i want all code paths below to set a result
uint8_t *result;
if (bestBlock != fmem_null) {
result = (uint8_t *)bestBlock->base + bestBlock->used;
bestBlock->used += size;
goto done;
} else {
if (block->type != fmemType_Growable) {
result = fmem_null;
goto done;
}
}
// Find tail block to append on
tailBlock = fmem_null;
if (block->base != fmem_null) {
tailBlock = block;
while (tailBlock != fmem_null) {
fmemBlockHeader *thisHeader = FMEM__GETHEADER(tailBlock);
if (thisHeader->next == fmem_null) {
break;
}
tailBlock = thisHeader->next;
}
}
size_t actualMinBlockSize;
if (block->minBlockSize > 0) {
FMEM_ASSERT(block->minBlockSize % FMEM__MIN_BLOCKSIZE == 0);
actualMinBlockSize = block->minBlockSize;
} else {
actualMinBlockSize = FMEM__MIN_BLOCKSIZE;
}
// Allocate new block
blockSize = fmem__RoundToSize(size + FMEM__BLOCK_META_SIZE, actualMinBlockSize);
newHeader = fmem__AllocateBlock(blockSize);
if (newHeader == fmem_null) {
result = fmem_null;
goto done;
}
if (tailBlock == fmem_null) {
// No tail found -> Setup block argument
block->size = blockSize - FMEM__BLOCK_META_SIZE;
block->base = (uint8_t *)newHeader + FMEM__BLOCK_META_SIZE;
block->used = size;
block->source = fmem_null;
block->totalBlockCount = 1;
result = (uint8_t *)block->base;
goto done;
}
// Setup next block
newBlock = FMEM__GETBLOCK(newHeader);
newBlock->base = (uint8_t *)newHeader + FMEM__BLOCK_META_SIZE;
newBlock->size = blockSize - FMEM__BLOCK_META_SIZE;
newBlock->type = tailBlock->type;
newBlock->source = fmem_null;
newBlock->used = size;
newBlock->allowPush = isForcedBlock ? fmemPermission_Denied : fmemPermission_Allowed;
block->totalBlockCount++;
// Append next block to tail
newHeader->prev = tailBlock;
tailHeader = FMEM__GETHEADER(tailBlock);
tailHeader->next = newBlock;
result = (uint8_t *)newBlock->base;
done:
if (result != fmem_null) {
if (flags & fmemPushFlags_Clear) {
FMEM_MEMSET(result, 0, size);
}
}
return(result);
}
fmem_api uint8_t *fmemPushAligned(fmemMemoryBlock *block, const size_t size, const size_t alignment, const fmemPushFlags flags) {
if (block == fmem_null || size == 0) {
return fmem_null;
}
if (alignment < 1) {
return fmemPush(block, size, flags);
}
size_t offset = ((((alignment) > 1) && (((size) & ((alignment)-1)) != 0)) ? ((alignment)-((size) & (alignment - 1))) : 0);
size_t alignedSize = size + offset;
uint8_t *result = fmemPush(block, alignedSize, flags);
return(result);
}
fmem_api bool fmemPushBlock(fmemMemoryBlock *src, fmemMemoryBlock *dst, const size_t size, const fmemPushFlags flags) {
if (src == fmem_null || dst == fmem_null || size == 0) {
return(false);
}
uint8_t *base = fmemPush(src, size, flags);
if (base == fmem_null) {
return(false);
}
dst->base = base;
dst->size = size;
dst->used = 0;
dst->source = src;
dst->type = fmemType_Fixed;
return(true);
}
fmem_api void fmemReset(fmemMemoryBlock *block) {
if (block != fmem_null && block->temporary == fmem_null) {
block->used = 0;
}
}
fmem_api bool fmemBeginTemporary(fmemMemoryBlock *source, fmemMemoryBlock *temporary) {
if (source == fmem_null || temporary == fmem_null) {
return(false);
}
if (source->base == fmem_null || source->size == 0) {
return(false);
}
size_t remainingSize = fmemGetRemainingSize(source);
if (remainingSize == 0) {
return(false);
}
FMEM_MEMSET(temporary, 0, sizeof(*temporary));
temporary->base = (uint8_t *)source->base + source->used;
temporary->size = remainingSize;
temporary->source = source;
temporary->type = fmemType_Temporary;
// @TODO(final): Not thread-safe!
source->used += remainingSize;
source->temporary = temporary;
FMEM_ASSERT(source->used == source->size);
return(true);
}
fmem_api void fmemEndTemporary(fmemMemoryBlock *temporary) {
if (temporary == fmem_null) {
return;
}
if (temporary->type != fmemType_Temporary || temporary->source == fmem_null || temporary->size == 0) {
return;
}
fmemMemoryBlock *sourceBlock = (fmemMemoryBlock *)temporary->source;
FMEM_ASSERT(sourceBlock->temporary == temporary);
FMEM_ASSERT(sourceBlock->used == sourceBlock->size);
FMEM_ASSERT(temporary->size <= sourceBlock->size);
// @TODO(final): Not thread-safe!
sourceBlock->temporary = fmem_null;
sourceBlock->used -= temporary->size;
FMEM_MEMSET(temporary, 0, sizeof(*temporary));
}
#endif // FMEM_IMPLEMENTATION