scoped_authorizationref.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #ifndef BASE_MAC_SCOPED_AUTHORIZATIONREF_H_
  5. #define BASE_MAC_SCOPED_AUTHORIZATIONREF_H_
  6. #include <Security/Authorization.h>
  7. #include "base/base_export.h"
  8. // ScopedAuthorizationRef maintains ownership of an AuthorizationRef. It is
  9. // patterned after the unique_ptr interface.
  10. namespace base::mac {
  11. class BASE_EXPORT ScopedAuthorizationRef {
  12. public:
  13. explicit ScopedAuthorizationRef(AuthorizationRef authorization = NULL)
  14. : authorization_(authorization) {
  15. }
  16. ScopedAuthorizationRef(const ScopedAuthorizationRef&) = delete;
  17. ScopedAuthorizationRef& operator=(const ScopedAuthorizationRef&) = delete;
  18. ~ScopedAuthorizationRef() {
  19. if (authorization_) {
  20. FreeInternal();
  21. }
  22. }
  23. void reset(AuthorizationRef authorization = NULL) {
  24. if (authorization_ != authorization) {
  25. if (authorization_) {
  26. FreeInternal();
  27. }
  28. authorization_ = authorization;
  29. }
  30. }
  31. bool operator==(AuthorizationRef that) const {
  32. return authorization_ == that;
  33. }
  34. bool operator!=(AuthorizationRef that) const {
  35. return authorization_ != that;
  36. }
  37. operator AuthorizationRef() const {
  38. return authorization_;
  39. }
  40. AuthorizationRef* get_pointer() { return &authorization_; }
  41. AuthorizationRef get() const {
  42. return authorization_;
  43. }
  44. void swap(ScopedAuthorizationRef& that) {
  45. AuthorizationRef temp = that.authorization_;
  46. that.authorization_ = authorization_;
  47. authorization_ = temp;
  48. }
  49. // ScopedAuthorizationRef::release() is like std::unique_ptr<>::release. It is
  50. // NOT a wrapper for AuthorizationFree(). To force a ScopedAuthorizationRef
  51. // object to call AuthorizationFree(), use ScopedAuthorizationRef::reset().
  52. [[nodiscard]] AuthorizationRef release() {
  53. AuthorizationRef temp = authorization_;
  54. authorization_ = NULL;
  55. return temp;
  56. }
  57. private:
  58. // Calling AuthorizationFree, defined in Security.framework, from an inline
  59. // function, results in link errors when linking dynamically with
  60. // libbase.dylib. So wrap the call in an un-inlined method. This method
  61. // doesn't check if |authorization_| is null; that check should be in the
  62. // inlined callers.
  63. void FreeInternal();
  64. AuthorizationRef authorization_;
  65. };
  66. } // namespace base::mac
  67. #endif // BASE_MAC_SCOPED_AUTHORIZATIONREF_H_