2 * Copyright 2013 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include <gtest/gtest.h>
19 #include "folly/MemoryMapping.h"
23 TEST(MemoryMapping, Basic) {
24 File f = File::temporary();
26 WritableMemoryMapping m(f.fd(), 0, sizeof(double));
27 double volatile* d = m.asWritableRange<double>().data();
31 MemoryMapping m(f.fd(), 0, 3);
32 EXPECT_EQ(0, m.asRange<int>().size()); //not big enough
35 MemoryMapping m(f.fd(), 0, sizeof(double));
36 const double volatile* d = m.asRange<double>().data();
37 EXPECT_EQ(*d, 37 * M_PI);
41 TEST(MemoryMapping, DoublyMapped) {
42 File f = File::temporary();
43 // two mappings of the same memory, different addresses.
44 WritableMemoryMapping mw(f.fd(), 0, sizeof(double));
45 MemoryMapping mr(f.fd(), 0, sizeof(double));
47 double volatile* dw = mw.asWritableRange<double>().data();
48 const double volatile* dr = mr.asRange<double>().data();
50 // Show that it's truly the same value, even though the pointers differ
53 EXPECT_EQ(*dr, 42 * M_PI);
55 EXPECT_EQ(*dr, 43 * M_PI);
60 void writeStringToFileOrDie(const std::string& str, int fd) {
61 const char* b = str.c_str();
62 size_t count = str.size();
63 ssize_t total_bytes = 0;
66 r = write(fd, b, count);
77 } while (r != 0 && count);
80 } // anonymous namespace
82 TEST(MemoryMapping, Simple) {
83 File f = File::temporary();
84 writeStringToFileOrDie("hello", f.fd());
87 MemoryMapping m(f.fd());
88 EXPECT_EQ("hello", m.data());
91 MemoryMapping m(f.fd(), 1, 2);
92 EXPECT_EQ("el", m.data());
96 TEST(MemoryMapping, LargeFile) {
98 size_t fileSize = sysconf(_SC_PAGESIZE) * 3 + 10;
99 fileData.reserve(fileSize);
100 for (size_t i = 0; i < fileSize; i++) {
101 fileData.push_back(0xff & random());
104 File f = File::temporary();
105 writeStringToFileOrDie(fileData, f.fd());
108 MemoryMapping m(f.fd());
109 EXPECT_EQ(fileData, m.data());
112 size_t size = sysconf(_SC_PAGESIZE) * 2;
113 StringPiece s(fileData.data() + 9, size - 9);
114 MemoryMapping m(f.fd(), 9, size - 9);
115 EXPECT_EQ(s.toString(), m.data());
119 TEST(MemoryMapping, ZeroLength) {
120 File f = File::temporary();
121 MemoryMapping m(f.fd());
122 EXPECT_TRUE(m.mlock(MemoryMapping::LockMode::MUST_LOCK));
123 EXPECT_TRUE(m.mlocked());
124 EXPECT_EQ(0, m.data().size());