From 74169e4b5deb805a03ebe7db0c90c3ea196edbb1 Mon Sep 17 00:00:00 2001 From: Victor Zverovich Date: Fri, 12 Sep 2014 13:53:52 -0700 Subject: [PATCH] Add a portable getpagesize() implementation --- posix.cc | 13 +++++++++++++ posix.h | 5 ++++- test/posix-test.cc | 24 ++++++++++++++++++++++++ test/posix-test.h | 1 + 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/posix.cc b/posix.cc index 9dc6b79b..4f20c6a9 100644 --- a/posix.cc +++ b/posix.cc @@ -222,3 +222,16 @@ fmt::BufferedFile fmt::File::fdopen(const char *mode) { fd_ = -1; return file; } + +long fmt::getpagesize() { +#ifdef _WIN32 + SYSTEM_INFO si = {}; + GetSystemInfo(&si); + return si.dwPageSize; +#else + long size = FMT_POSIX_CALL(sysconf(_SC_PAGESIZE)); + if (size < 0) + throw SystemError(errno, "cannot get memory page size"); + return size; +#endif +} diff --git a/posix.h b/posix.h index 6a48adb6..5ec80993 100644 --- a/posix.h +++ b/posix.h @@ -320,7 +320,10 @@ class File { // this File object from the file. BufferedFile fdopen(const char *mode); }; -} + +// Returns the memory page size. +long getpagesize(); +} // namespace fmt #if !FMT_USE_RVALUE_REFERENCES namespace std { diff --git a/test/posix-test.cc b/test/posix-test.cc index 5d5bdeb0..d7f60ed7 100644 --- a/test/posix-test.cc +++ b/test/posix-test.cc @@ -56,6 +56,7 @@ int fileno_count; std::size_t read_nbyte; std::size_t write_nbyte; bool increase_file_size; +bool sysconf_error; } #define EMULATE_EINTR(func, error_result) \ @@ -80,6 +81,15 @@ int test::fstat(int fd, struct stat *buf) { buf->st_size = max_file_size(); return result; } + +long test::sysconf(int name) { + long result = ::sysconf(name); + if (!sysconf_error) + return result; + // Simulate an error. + errno = EINVAL; + return -1; +} #else errno_t test::sopen_s( int* pfh, const char *filename, int oflag, int shflag, int pmode) { @@ -184,6 +194,20 @@ TEST(UtilTest, StaticAssert) { // a compile-time error. } +TEST(UtilTest, GetPageSize) { +#ifdef _WIN32 + SYSTEM_INFO si = {}; + GetSystemInfo(&si); + EXPECT_EQ(si.dwPageSize, fmt::getpagesize()); +#else + EXPECT_EQ(sysconf(_SC_PAGESIZE), fmt::getpagesize()); + sysconf_error = true; + EXPECT_SYSTEM_ERROR( + fmt::getpagesize(), EINVAL, "cannot get memory page size"); + sysconf_error = false; +#endif +} + TEST(FileTest, OpenRetry) { write_file("test", "there must be something here"); File *f = 0; diff --git a/test/posix-test.h b/test/posix-test.h index e960afc3..4768cb94 100644 --- a/test/posix-test.h +++ b/test/posix-test.h @@ -45,6 +45,7 @@ typedef size_t size_t; typedef ssize_t ssize_t; int open(const char *path, int oflag, int mode); int fstat(int fd, struct stat *buf); +long sysconf(int name); #else typedef unsigned size_t; typedef int ssize_t;