aboutsummaryrefslogtreecommitdiffhomepage
path: root/tdutils/td/utils/unique_value_ptr.h
blob: 9cf6795bf51b67bcabdbe0181f7055f5112ab18d (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2026
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once

#include "td/utils/unique_ptr.h"

#include <cstddef>
#include <utility>

namespace td {

// copyable by value td::unique_ptr
template <class T>
class unique_value_ptr final {
 public:
  unique_value_ptr() noexcept = default;
  unique_value_ptr(const unique_value_ptr &other) {
    if (other != nullptr) {
      ptr_ = make_unique<T>(*other);
    }
  }
  unique_value_ptr &operator=(const unique_value_ptr &other) {
    if (other == nullptr) {
      ptr_ = nullptr;
    } else {
      ptr_ = make_unique<T>(*other);
    }
    return *this;
  }
  unique_value_ptr(unique_value_ptr &&) noexcept = default;
  unique_value_ptr &operator=(unique_value_ptr &&) = default;
  unique_value_ptr(std::nullptr_t) noexcept {
  }
  unique_value_ptr(unique_ptr<T> &&ptr) noexcept : ptr_(std::move(ptr)) {
  }
  T *get() noexcept {
    return ptr_.get();
  }
  const T *get() const noexcept {
    return ptr_.get();
  }
  T *operator->() noexcept {
    return ptr_.get();
  }
  const T *operator->() const noexcept {
    return ptr_.get();
  }
  T &operator*() noexcept {
    return *ptr_;
  }
  const T &operator*() const noexcept {
    return *ptr_;
  }
  explicit operator bool() const noexcept {
    return ptr_ != nullptr;
  }

 private:
  unique_ptr<T> ptr_;
};

template <class T>
bool operator==(const unique_value_ptr<T> &p, std::nullptr_t) {
  return !p;
}
template <class T>
bool operator!=(const unique_value_ptr<T> &p, std::nullptr_t) {
  return static_cast<bool>(p);
}

template <class T>
bool operator==(const unique_value_ptr<T> &lhs, const unique_value_ptr<T> &rhs) {
  if (lhs == nullptr) {
    return rhs == nullptr;
  }
  return rhs != nullptr && *lhs == *rhs;
}

template <class T>
bool operator!=(const unique_value_ptr<T> &lhs, const unique_value_ptr<T> &rhs) {
  return !(lhs == rhs);
}

template <class Type, class... Args>
unique_value_ptr<Type> make_unique_value(Args &&...args) {
  return unique_value_ptr<Type>(make_unique<Type>(std::forward<Args>(args)...));
}

}  // namespace td