1 // Copyright 2013 The Flutter 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 5 #ifndef FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_ 6 #define FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_ 7 8 #include <Block.h> 9 10 #include "flutter/fml/compiler_specific.h" 11 12 namespace fml { 13 14 // ScopedBlock<> is patterned after ScopedCFTypeRef<>, but uses Block_copy() and 15 // Block_release() instead of CFRetain() and CFRelease(). 16 17 enum class OwnershipPolicy { 18 // The scoped object takes ownership of an object by taking over an existing 19 // ownership claim. 20 Assume, 21 22 // The scoped object will retain the the object and any initial ownership is 23 // not changed. 24 Retain, 25 }; 26 27 template <typename B> 28 class ScopedBlock { 29 public: 30 explicit ScopedBlock(B block = nullptr, 31 OwnershipPolicy policy = OwnershipPolicy::Assume) block_(block)32 : block_(block) { 33 if (block_ && policy == OwnershipPolicy::Retain) 34 block_ = Block_copy(block); 35 } 36 ScopedBlock(const ScopedBlock<B> & that)37 ScopedBlock(const ScopedBlock<B>& that) : block_(that.block_) { 38 if (block_) 39 block_ = Block_copy(block_); 40 } 41 ~ScopedBlock()42 ~ScopedBlock() { 43 if (block_) 44 Block_release(block_); 45 } 46 47 ScopedBlock& operator=(const ScopedBlock<B>& that) { 48 reset(that.get(), OwnershipPolicy::Retain); 49 return *this; 50 } 51 52 void reset(B block = nullptr, 53 OwnershipPolicy policy = OwnershipPolicy::Assume) { 54 if (block && policy == OwnershipPolicy::Retain) 55 block = Block_copy(block); 56 if (block_) 57 Block_release(block_); 58 block_ = block; 59 } 60 61 bool operator==(B that) const { return block_ == that; } 62 63 bool operator!=(B that) const { return block_ != that; } 64 B()65 operator B() const { return block_; } 66 get()67 B get() const { return block_; } 68 swap(ScopedBlock & that)69 void swap(ScopedBlock& that) { 70 B temp = that.block_; 71 that.block_ = block_; 72 block_ = temp; 73 } 74 release()75 B release() FML_WARN_UNUSED_RESULT { 76 B temp = block_; 77 block_ = nullptr; 78 return temp; 79 } 80 81 private: 82 B block_; 83 }; 84 85 } // namespace fml 86 87 #endif // FLUTTER_FML_PLATFORM_DARWIN_SCOPED_BLOCK_H_ 88