Refactor FOLLY_GCC_DISABLE_WARNING to play nice with clang-format
[folly.git] / folly / File.cpp
index 56d30b0c8ae7718f40bb4814dc0901e46e6cfe9e..4df3274eb86c3f77fa3280abb49303bbee9da9f0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2017 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * limitations under the License.
  */
 
-#include "folly/File.h"
+#include <folly/File.h>
 
-#include <fcntl.h>
-#include <unistd.h>
 
-#include "folly/Exception.h"
-#include "folly/FileUtil.h"
-#include "folly/Format.h"
-#include "folly/ScopeGuard.h"
+#include <folly/Exception.h>
+#include <folly/FileUtil.h>
+#include <folly/Format.h>
+#include <folly/ScopeGuard.h>
+#include <folly/portability/Fcntl.h>
+#include <folly/portability/SysFile.h>
+#include <folly/portability/Unistd.h>
 
 #include <system_error>
 
@@ -37,8 +38,10 @@ File::File()
 
 File::File(int fd, bool ownsFd)
   : fd_(fd)
-  , ownsFd_(ownsFd)
-{}
+  , ownsFd_(ownsFd) {
+  CHECK_GE(fd, -1) << "fd must be -1 or non-negative";
+  CHECK(fd != -1 || !ownsFd) << "cannot own -1";
+}
 
 File::File(const char* name, int flags, mode_t mode)
   : fd_(::open(name, flags, mode))
@@ -50,10 +53,15 @@ File::File(const char* name, int flags, mode_t mode)
   ownsFd_ = true;
 }
 
-File::File(File&& other)
+File::File(const std::string& name, int flags, mode_t mode)
+  : File(name.c_str(), flags, mode) {}
+
+File::File(StringPiece name, int flags, mode_t mode)
+  : File(name.str(), flags, mode) {}
+
+File::File(File&& other) noexcept
   : fd_(other.fd_)
   , ownsFd_(other.ownsFd_) {
-
   other.release();
 }
 
@@ -64,7 +72,11 @@ File& File::operator=(File&& other) {
 }
 
 File::~File() {
-  closeNoThrow();  // ignore error
+  auto fd = fd_;
+  if (!closeNoThrow()) {  // ignore most errors
+    DCHECK_NE(errno, EBADF) << "closing fd " << fd << ", it may already "
+      << "have been closed. Another time, this might close the wrong FD.";
+  }
 }
 
 /* static */ File File::temporary() {
@@ -79,9 +91,11 @@ File::~File() {
   return File(fd, true);
 }
 
-void File::release() {
+int File::release() noexcept {
+  int released = fd_;
   fd_ = -1;
   ownsFd_ = false;
+  return released;
 }
 
 void File::swap(File& other) {
@@ -95,7 +109,7 @@ void swap(File& a, File& b) {
 }
 
 File File::dup() const {
-  if (fd_ >= 0) {
+  if (fd_ != -1) {
     int fd = ::dup(fd_);
     checkUnixError(fd, "dup() failed");