aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/memory.h
blob: b2c0544491517795124e2b3439a09649c300dd0b (plain) (blame)
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
#pragma once

#ifndef CACHE_LINE_SIZE
#define CACHE_LINE_SIZE 64
#endif

#define CONCAT(a, b) a##b
#define LABEL(a) CONCAT(UniqueName_, a)
#define UNIQUE_NAME LABEL(__LINE__)

#define CACHE_LINE_PADDING char UNIQUE_NAME[CACHE_LINE_SIZE];

static inline void* MallocAligned(size_t size, size_t alignment) {
    void** ptr = (void**)malloc(size + alignment + sizeof(size_t*));
    if (!ptr) {
        return nullptr;
    }

    size_t mask = ~(alignment - 1);
    intptr_t roundedDown = intptr_t(ptr) & mask;
    void** alignedPtr = (void**)(roundedDown + alignment);
    alignedPtr[-1] = ptr;
    return alignedPtr;
}

static inline void FreeAligned(void* ptr) {
    if (!ptr) {
        return;
    }

    void** typedPtr = (void**)ptr;
    void* originalPtr = typedPtr[-1];
    free(originalPtr);
}

static inline void* MallocCacheAligned(size_t size) {
    return MallocAligned(size, CACHE_LINE_SIZE);
}

static inline void FreeCacheAligned(void* ptr) {
    return FreeAligned(ptr);
}