File ctor should take StringPiece.
authorYedidya Feldblum <yfeldblum@fb.com>
Mon, 13 Jul 2015 20:25:25 +0000 (13:25 -0700)
committerSara Golemon <sgolemon@fb.com>
Wed, 15 Jul 2015 20:25:09 +0000 (13:25 -0700)
Summary: [Folly] File ctor should take StringPiece.

This way we can use it with `std::string` and `folly::fbstring` a touch more easily.

Reviewed By: @luciang

Differential Revision: D2235870

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

index 253d005472a0a80f52c5bb67452071d0b9538c69..3c53573355fc6a9d2dec13e50d36a323d83680e2 100644 (file)
@@ -53,6 +53,12 @@ File::File(const char* name, int flags, mode_t mode)
   ownsFd_ = true;
 }
 
+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_) {
index cf8fdc7f71167b464ef5455e56370189a99efb67..459251428d370b37431e191493b55f57f72000d5 100644 (file)
 #ifndef FOLLY_FILE_H_
 #define FOLLY_FILE_H_
 
+#include <fcntl.h>
 #include <sys/stat.h>
 #include <sys/types.h>
-#include <fcntl.h>
 #include <unistd.h>
 
+#include <string>
+
 #include <folly/Portability.h>
+#include <folly/Range.h>
 
 namespace folly {
 
@@ -46,6 +49,9 @@ class File {
    * Open and create a file object.  Throws on error.
    */
   explicit File(const char* name, int flags = O_RDONLY, mode_t mode = 0666);
+  explicit File(
+      const std::string& name, int flags = O_RDONLY, mode_t mode = 0666);
+  explicit File(StringPiece name, int flags = O_RDONLY, mode_t mode = 0666);
 
   ~File();
 
index 613982d0be9f209f9205bea5fab813fd0f615106..3a120c54c68637dc8986002337ccabe7a4bd7ccd 100644 (file)
@@ -55,6 +55,15 @@ TEST(File, Simple) {
   }
 }
 
+TEST(File, SimpleStringPiece) {
+  char buf = 'x';
+  File f(StringPiece("/etc/hosts"));
+  EXPECT_NE(-1, f.fd());
+  EXPECT_EQ(1, ::read(f.fd(), &buf, 1));
+  f.close();
+  EXPECT_EQ(-1, f.fd());
+}
+
 TEST(File, OwnsFd) {
   // Wrap a file descriptor, make sure that ownsFd works
   // We'll test that the file descriptor is closed by closing the writing