Truthy File
authorTom Jackson <tjackson@fb.com>
Tue, 5 Mar 2013 19:05:42 +0000 (11:05 -0800)
committerJordan DeLong <jdelong@fb.com>
Tue, 19 Mar 2013 00:08:14 +0000 (17:08 -0700)
Summary:
File has a default constructor so it can be initialized late, but it
doesn't have a good canonical way to see if it's been initialized. This adds an
//explicit// operator bool so you can test files like `if (file) ...`.

Test Plan: Unit tests

Reviewed By: chaoyc@fb.com

FB internal diff: D726914

folly/File.h
folly/test/FileTest.cpp

index 1f30c988be6058d58656e264dad4668415403fdb..e990c91bfc14efcd0274dc01c6c84edf63237315 100644 (file)
@@ -59,6 +59,13 @@ class File {
    */
   int fd() const { return fd_; }
 
+  /**
+   * Returns 'true' iff the file was successfully opened.
+   */
+  explicit operator bool() const {
+    return fd_ >= 0;
+  }
+
   /**
    * If we own the file descriptor, close the file and throw on error.
    * Otherwise, do nothing.
index 14b027c98bb2d6cdceaa63b4ab617a0773c1819a..4f47f0fec2b2e6328e9d29941acdb657165b8258 100644 (file)
@@ -96,3 +96,29 @@ TEST(File, UsefulError) {
     EXPECT_CONTAINS(e.what(), "0666");
   }
 }
+
+TEST(File, Truthy) {
+  File temp = File::temporary();
+
+  EXPECT_TRUE(bool(temp));
+
+  if (temp) {
+    ;
+  } else {
+    EXPECT_FALSE(true);
+  }
+
+  if (File file = File::temporary()) {
+    ;
+  } else {
+    EXPECT_FALSE(true);
+  }
+
+  EXPECT_FALSE(bool(File()));
+  if (File()) {
+    EXPECT_TRUE(false);
+  }
+  if (File notOpened = File()) {
+    EXPECT_TRUE(false);
+  }
+}