Make fbstring libgcc-safe
[folly.git] / folly / File.cpp
index 3c961aaae45f6dd1c2c6100a4256a6d334f5cf68..c60dfbced7fcf7406aa5df50cac1e2a9d6f8964d 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2013 Facebook, Inc.
+ * Copyright 2014 Facebook, Inc.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -37,8 +37,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))
@@ -53,7 +55,6 @@ File::File(const char* name, int flags, mode_t mode)
 File::File(File&& other)
   : fd_(other.fd_)
   , ownsFd_(other.ownsFd_) {
-
   other.release();
 }
 
@@ -73,15 +74,17 @@ File::~File() {
   checkFopenError(tmpFile, "tmpfile() failed");
   SCOPE_EXIT { fclose(tmpFile); };
 
-  int fd = dup(fileno(tmpFile));
+  int fd = ::dup(fileno(tmpFile));
   checkUnixError(fd, "dup() failed");
 
   return File(fd, true);
 }
 
-void File::release() {
+int File::release() {
+  int released = fd_;
   fd_ = -1;
   ownsFd_ = false;
+  return released;
 }
 
 void File::swap(File& other) {
@@ -94,6 +97,17 @@ void swap(File& a, File& b) {
   a.swap(b);
 }
 
+File File::dup() const {
+  if (fd_ != -1) {
+    int fd = ::dup(fd_);
+    checkUnixError(fd, "dup() failed");
+
+    return File(fd, true);
+  }
+
+  return File();
+}
+
 void File::close() {
   if (!closeNoThrow()) {
     throwSystemError("close() failed");