opynsim
Unofficial C++ Documentation
Loading...
Searching...
No Matches
uid.h
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <concepts>
5#include <cstddef>
6#include <functional>
7#include <iosfwd>
8
9namespace osc
10{
11 // Unique ID
12 //
13 // an ID that is guaranteed to be unique upon non-copy/move construction
14 class UID final {
15 public:
17
18 static constexpr UID invalid()
19 {
20 return UID{-1};
21 }
22
23 static constexpr UID empty()
24 {
25 return UID{0};
26 }
27
28 template<std::integral T>
29 requires (sizeof(T) <= sizeof(element_type))
30 static constexpr UID from_int_unchecked(T i)
31 {
32 return UID{static_cast<element_type>(i)};
33 }
34
35 UID() : value_{allocate_next_id()}
36 {}
37 constexpr UID(const UID&) = default;
38 constexpr UID(UID&&) noexcept = default;
42
43 void reset()
44 {
45 value_ = allocate_next_id();
46 }
47
48 constexpr element_type get() const
49 {
50 return value_;
51 }
52
53 explicit constexpr operator bool() const
54 {
55 return value_ > 0;
56 }
57
58 friend auto operator<=>(const UID&, const UID&) = default;
59
60 private:
61 static constinit std::atomic<element_type> g_next_available_id;
62
63 static element_type allocate_next_id()
64 {
65 return g_next_available_id.fetch_add(1, std::memory_order_relaxed);
66 }
67
68 constexpr UID(element_type value) : value_{value}
69 {}
70
71 element_type value_;
72 };
73
74 std::ostream& operator<<(std::ostream&, const UID&);
75}
76
77// hashing support for LogicalIDs
78//
79// lets them be used as associative lookup keys, etc.
80template<>
81struct std::hash<osc::UID> final {
82 size_t operator()(const osc::UID& id) const noexcept
83 {
84 return static_cast<size_t>(id.get());
85 }
86};
Definition uid.h:14
constexpr element_type get() const
Definition uid.h:48
static constexpr UID empty()
Definition uid.h:23
static constexpr UID invalid()
Definition uid.h:18
static constexpr UID from_int_unchecked(T i)
Definition uid.h:30
UID()
Definition uid.h:35
void reset()
Definition uid.h:43
constexpr UID(UID &&) noexcept=default
friend auto operator<=>(const UID &, const UID &)=default
intptr_t element_type
Definition uid.h:16
constexpr UID(const UID &)=default
Definition custom_decoration_generator.h:5
std::ostream & operator<<(std::ostream &, const Object &)
constexpr U to(T &&value)
Definition conversion.h:56
size_t operator()(const osc::UID &id) const noexcept
Definition uid.h:82