Home | History | Annotate | Download | only in mac
      1 // Copyright 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 
      5 #ifndef BASE_MAC_SCOPED_CFFILEDESCRIPTORREF_H_
      6 #define BASE_MAC_SCOPED_CFFILEDESCRIPTORREF_H_
      7 
      8 #include <CoreFoundation/CoreFoundation.h>
      9 
     10 #include "base/basictypes.h"
     11 #include "base/compiler_specific.h"
     12 
     13 namespace base {
     14 namespace mac {
     15 
     16 // ScopedCFFileDescriptorRef is designed after ScopedCFTypeRef<>. On
     17 // destruction, it will invalidate the file descriptor.
     18 // ScopedCFFileDescriptorRef (unlike ScopedCFTypeRef<>) does not support RETAIN
     19 // semantics, copying, or assignment, as doing so would increase the chances
     20 // that a file descriptor is invalidated while still in use.
     21 class ScopedCFFileDescriptorRef {
     22  public:
     23   explicit ScopedCFFileDescriptorRef(CFFileDescriptorRef fdref = NULL)
     24       : fdref_(fdref) {
     25   }
     26 
     27   ~ScopedCFFileDescriptorRef() {
     28     if (fdref_) {
     29       CFFileDescriptorInvalidate(fdref_);
     30       CFRelease(fdref_);
     31     }
     32   }
     33 
     34   void reset(CFFileDescriptorRef fdref = NULL) {
     35     if (fdref_ == fdref)
     36       return;
     37     if (fdref_) {
     38       CFFileDescriptorInvalidate(fdref_);
     39       CFRelease(fdref_);
     40     }
     41     fdref_ = fdref;
     42   }
     43 
     44   bool operator==(CFFileDescriptorRef that) const {
     45     return fdref_ == that;
     46   }
     47 
     48   bool operator!=(CFFileDescriptorRef that) const {
     49     return fdref_ != that;
     50   }
     51 
     52   operator CFFileDescriptorRef() const {
     53     return fdref_;
     54   }
     55 
     56   CFFileDescriptorRef get() const {
     57     return fdref_;
     58   }
     59 
     60   CFFileDescriptorRef release() WARN_UNUSED_RESULT {
     61     CFFileDescriptorRef temp = fdref_;
     62     fdref_ = NULL;
     63     return temp;
     64   }
     65 
     66  private:
     67   CFFileDescriptorRef fdref_;
     68 
     69   DISALLOW_COPY_AND_ASSIGN(ScopedCFFileDescriptorRef);
     70 };
     71 
     72 }  // namespace mac
     73 }  // namespace base
     74 
     75 #endif  // BASE_MAC_SCOPED_CFFILEDESCRIPTORREF_H_
     76