~vladh/peony

peony/src/stackarray.hpp -rw-r--r-- 1.4 KiB
7fc9922bVlad-Stefan Harbuz changes shaders namespace into class a month ago
                                                                                
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
/*
  Peony Game Engine
  Copyright (C) 2020 Vlad-Stefan Harbuz <vlad@vladh.net>
  All rights reserved.
*/

#pragma once

#include "memory.hpp"

template <typename T, uint32 capacity>
class StackArray {
public:
  T items[capacity] = {{}};
  uint32 length = 0;
  bool32 is_sparse = false;
  uint32 starting_idx = 0;

  T* push() {
    assert(this->length < capacity);
    uint32 new_idx = this->length;
    this->length++;
    T* new_slot = &this->items[new_idx];
    return new_slot;
  }

  T* push(T new_item) {
    T* new_slot = push();
    *new_slot = new_item;
    return new_slot;
  }

  T* get(uint32 idx) {
    assert(idx >= this->starting_idx && idx < capacity);
    if (idx >= this->length) {
      assert(this->is_sparse);
      this->length = idx + 1;
    }
    return &this->items[idx];
  }

  T* operator[](uint32 idx) {
    return get(idx);
  }

  template <typename F>
  T* find(F match) {
    for (auto item = begin(); item < end(); item++) {
      if (match(item)) {
        return item;
      }
    }
    return nullptr;
  }

  T* begin() {
    return &this->items[this->starting_idx];
  }

  T* end() {
    return &this->items[this->length];
  }

  void clear() {
    memset(this->items, 0, sizeof(this->items));
    this->length = 0;
  }

  void delete_elements_after_index(uint32 idx) {
    memset(&this->items[idx], 0, sizeof(T) * (this->length - idx));
    this->length = idx;
  }
};