scoped_authorizationref.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. #include "base/compiler_specific.h"
  9. #include "base/macros.h"
  10. // ScopedAuthorizationRef maintains ownership of an AuthorizationRef. It is
  11. // patterned after the unique_ptr interface.
  12. namespace base {
  13. namespace mac {
  14. class BASE_EXPORT ScopedAuthorizationRef {
  15. public:
  16. explicit ScopedAuthorizationRef(AuthorizationRef authorization = NULL)
  17. : authorization_(authorization) {
  18. }
  19. ~ScopedAuthorizationRef() {
  20. if (authorization_) {
  21. FreeInternal();
  22. }
  23. }
  24. void reset(AuthorizationRef authorization = NULL) {
  25. if (authorization_ != authorization) {
  26. if (authorization_) {
  27. FreeInternal();
  28. }
  29. authorization_ = authorization;
  30. }
  31. }
  32. bool operator==(AuthorizationRef that) const {
  33. return authorization_ == that;
  34. }
  35. bool operator!=(AuthorizationRef that) const {
  36. return authorization_ != that;
  37. }
  38. operator AuthorizationRef() const {
  39. return authorization_;
  40. }
  41. AuthorizationRef* get_pointer() { return &authorization_; }
  42. AuthorizationRef get() const {
  43. return authorization_;
  44. }
  45. void swap(ScopedAuthorizationRef& that) {
  46. AuthorizationRef temp = that.authorization_;
  47. that.authorization_ = authorization_;
  48. authorization_ = temp;
  49. }
  50. // ScopedAuthorizationRef::release() is like std::unique_ptr<>::release. It is
  51. // NOT a wrapper for AuthorizationFree(). To force a ScopedAuthorizationRef
  52. // object to call AuthorizationFree(), use ScopedAuthorizationRef::reset().
  53. AuthorizationRef release() WARN_UNUSED_RESULT {
  54. AuthorizationRef temp = authorization_;
  55. authorization_ = NULL;
  56. return temp;
  57. }
  58. private:
  59. // Calling AuthorizationFree, defined in Security.framework, from an inline
  60. // function, results in link errors when linking dynamically with
  61. // libbase.dylib. So wrap the call in an un-inlined method. This method
  62. // doesn't check if |authorization_| is null; that check should be in the
  63. // inlined callers.
  64. void FreeInternal();
  65. AuthorizationRef authorization_;
  66. DISALLOW_COPY_AND_ASSIGN(ScopedAuthorizationRef);
  67. };
  68. } // namespace mac
  69. } // namespace base
  70. #endif // BASE_MAC_SCOPED_AUTHORIZATIONREF_H_