chromium/third_party/pdfium/core/fxcrt/maybe_owned.h

// Copyright 2016 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef CORE_FXCRT_MAYBE_OWNED_H_
#define CORE_FXCRT_MAYBE_OWNED_H_

#include <memory>
#include <utility>

#include "core/fxcrt/unowned_ptr.h"
#include "third_party/abseil-cpp/absl/types/variant.h"

namespace fxcrt {

// A template that can hold either owned or unowned references, and cleans up
// appropriately.  Possibly the most pernicious anti-pattern imaginable, but
// it crops up throughout the codebase due to a desire to avoid copying-in
// objects or data.
template <typename T, typename D = std::default_delete<T>>
class MaybeOwned {
 public:
  using OwnedType = std::unique_ptr<T, D>;
  using UnownedType = UnownedPtr<T>;

  MaybeOwned() = default;
  explicit MaybeOwned(T* ptr) :{}
  explicit MaybeOwned(const UnownedType& ptr) :{}
  explicit MaybeOwned(OwnedType ptr) :{}

  MaybeOwned(const MaybeOwned& that) = delete;
  MaybeOwned(MaybeOwned&& that) noexcept = default;

  MaybeOwned& operator=(const MaybeOwned& that) = delete;
  MaybeOwned& operator=(MaybeOwned&& that) noexcept = default;

  ~MaybeOwned() = default;

  void Reset(T* ptr = nullptr) {}
  void Reset(OwnedType ptr) {}

  bool IsOwned() const {}

  // Helpful for untangling a collection of intertwined MaybeOwned<>.
  void ResetIfUnowned() {}

  T* Get() const& {}
  T* Get() && {}

  // Downgrades to unowned, caller takes ownership.
  OwnedType Release() {}

  // Downgrades to empty, caller takes ownership.
  OwnedType ReleaseAndClear() {}

  MaybeOwned& operator=(T* ptr) {}
  MaybeOwned& operator=(const UnownedType& ptr) {}
  MaybeOwned& operator=(OwnedType ptr) {}

  bool operator==(const MaybeOwned& that) const {}
  bool operator==(const OwnedType& ptr) const {}
  bool operator==(T* ptr) const {}

  bool operator!=(const MaybeOwned& that) const {}
  bool operator!=(const OwnedType ptr) const {}
  bool operator!=(T* ptr) const {}

  explicit operator bool() const { return !!Get(); }
  T& operator*() const {}
  T* operator->() const {}

 private:
  absl::variant<UnownedType, OwnedType> ptr_;
};

}  // namespace fxcrt

MaybeOwned;

#endif  // CORE_FXCRT_MAYBE_OWNED_H_