Handle.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Badge.h>
  8. #include <AK/Noncopyable.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/RefPtr.h>
  11. #include <LibJS/Forward.h>
  12. namespace JS {
  13. class HandleImpl : public RefCounted<HandleImpl> {
  14. AK_MAKE_NONCOPYABLE(HandleImpl);
  15. AK_MAKE_NONMOVABLE(HandleImpl);
  16. public:
  17. ~HandleImpl();
  18. Cell* cell() { return m_cell; }
  19. const Cell* cell() const { return m_cell; }
  20. private:
  21. template<class T>
  22. friend class Handle;
  23. explicit HandleImpl(Cell*);
  24. Cell* m_cell { nullptr };
  25. };
  26. template<class T>
  27. class Handle {
  28. public:
  29. Handle() { }
  30. static Handle create(T* cell)
  31. {
  32. return Handle(adopt_ref(*new HandleImpl(cell)));
  33. }
  34. T* cell() { return static_cast<T*>(m_impl->cell()); }
  35. const T* cell() const { return static_cast<const T*>(m_impl->cell()); }
  36. bool is_null() const { return m_impl.is_null(); }
  37. private:
  38. explicit Handle(NonnullRefPtr<HandleImpl> impl)
  39. : m_impl(move(impl))
  40. {
  41. }
  42. RefPtr<HandleImpl> m_impl;
  43. };
  44. template<class T>
  45. inline Handle<T> make_handle(T* cell)
  46. {
  47. return Handle<T>::create(cell);
  48. }
  49. }