File: pool.hpp

package info (click to toggle)
higan 098-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 11,904 kB
  • ctags: 13,286
  • sloc: cpp: 108,285; ansic: 778; makefile: 32; sh: 18
file content (62 lines) | stat: -rw-r--r-- 1,640 bytes parent folder | download
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
#pragma once

namespace nall {
namespace memory {

template<unsigned Capacity, unsigned Size>
struct pool_spsc {
  signed* list = nullptr;
  uint8_t* data = nullptr;
  unsigned slot = 0;

  pool_spsc() {
    list = (signed*)memory::allocate(Capacity * sizeof(signed));
    data = (uint8_t*)memory::allocate(Capacity * Size);
    for(unsigned n = 0; n < Capacity; n++) list[n] = n;
  }

  ~pool_spsc() {
    memory::free(list);
    memory::free(data);
  }

  auto allocate(unsigned size) -> void* {
    if(size == 0) return nullptr;
    if(size > Size) return memory::allocate(size);
    signed offset = list[slot];
    if(offset < 0) return memory::allocate(size);
    list[slot] = -1;
    slot = (slot + 1) % Capacity;
    return (void*)(data + offset * Size);
  }

  auto allocate(unsigned size, uint8_t data) -> void* {
    auto result = allocate(size);
    memset(result, data, size);
    return result;
  }

  auto resize(void* target, unsigned size) -> void* {
    if(target == nullptr) return allocate(size);
    signed offset = ((uint8_t*)target - data) / Size;
    if(offset < 0 || offset >= Capacity) return memory::resize(target, size);
    if(size <= Size) return target;
    slot = (slot - 1) % Capacity;
    list[slot] = offset;
    return memory::allocate(size);
  }

  auto free(void* target) -> void {
    if(target == nullptr) return;
    signed offset = ((uint8_t*)target - data) / Size;
    if(offset < 0 || offset >= Capacity) return memory::free(target);
    slot = (slot - 1) % Capacity;
    list[slot] = offset;
  }

  pool_spsc(const pool_spsc&) = delete;
  pool_spsc& operator=(const pool_spsc&) = delete;
};

}
}