summaryrefslogtreecommitdiff
path: root/util.h
blob: bba74a2b2ca30a88bc5f1c9cd41cc813db09a001 (plain)
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
/*
 * Copyright (C) 2024 Mikhail Burakov. This file is part of streamer.
 *
 * streamer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * streamer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with streamer.  If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef STREAMER_UTIL_H_
#define STREAMER_UTIL_H_

#define STR_IMPL(x) #x
#define STR(x) STR_IMPL(x)
#define FROM_HERE __FILE__ ":" STR(__LINE__) " "

template <class T>
struct Defer {
  Defer(T&& op) : op_{op} {}
  ~Defer() { op_(); }
  const T& op_;
};

template <class T>
Defer(T&&) -> Defer<T>;

template <auto dflt, auto closer>
struct PodCloser {
  struct pointer {
    decltype(dflt) value_;
    pointer() : value_{dflt} {}
    pointer(decltype(nullptr)) : value_{dflt} {}
    pointer(decltype(dflt) value) : value_{value} {}
    explicit operator bool() const { return value_ != dflt; }
    friend bool operator==(pointer, pointer) = default;
    operator decltype(dflt)() const { return value_; }
  };
  void operator()(const pointer ptr) {
    if (ptr.value_ != dflt) closer(ptr.value_);
  }
};

template <class T>
struct ClassOf;

template <class R, class C>
struct ClassOf<R C::*> {
  using T = C;
};

template <auto fun, class T, class... Args>
inline auto Trampoline(T* head, Args... tail) {
  using C = ClassOf<decltype(fun)>::T;
  auto self = static_cast<C*>(head);
  return (self->*fun)(tail...);
}

#endif  // STREAMER_UTIL_H_