Commit 9d7cc509 authored by Tom Jackson's avatar Tom Jackson Committed by Jordan DeLong

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
parent f4cbf351
......@@ -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.
......
......@@ -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);
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment