From 9d7cc509a90f551b1db5906895997146bc923a57 Mon Sep 17 00:00:00 2001 From: Tom Jackson Date: Tue, 5 Mar 2013 11:05:42 -0800 Subject: [PATCH] Truthy File 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 | 7 +++++++ folly/test/FileTest.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/folly/File.h b/folly/File.h index 1f30c988..e990c91b 100644 --- a/folly/File.h +++ b/folly/File.h @@ -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. diff --git a/folly/test/FileTest.cpp b/folly/test/FileTest.cpp index 14b027c9..4f47f0fe 100644 --- a/folly/test/FileTest.cpp +++ b/folly/test/FileTest.cpp @@ -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); + } +} -- 2.34.1