1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  */
7 
8 #include <fcntl.h>
9 #include <sys/mman.h>
10 
11 #include <ABI48_0_0cxxreact/ABI48_0_0JSBigString.h>
12 #include <folly/File.h>
13 #include <gtest/gtest.h>
14 
15 using namespace ABI48_0_0facebook::ABI48_0_0React;
16 
17 namespace {
tempFileFromString(std::string contents)18 int tempFileFromString(std::string contents) {
19   const char *tmpDir = getenv("TMPDIR");
20   if (tmpDir == nullptr)
21     tmpDir = "/tmp";
22   std::string tmp{tmpDir};
23   tmp += "/temp.XXXXXX";
24 
25   std::vector<char> tmpBuf{tmp.begin(), tmp.end()};
26   tmpBuf.push_back('\0');
27 
28   const int fd = mkstemp(tmpBuf.data());
29   write(fd, contents.c_str(), contents.size() + 1);
30 
31   return fd;
32 }
33 }; // namespace
34 
TEST(JSBigFileString,MapWholeFileTest)35 TEST(JSBigFileString, MapWholeFileTest) {
36   std::string data{"Hello, world"};
37   const auto size = data.length() + 1;
38 
39   // Initialise Big String
40   int fd = tempFileFromString("Hello, world");
41   JSBigFileString bigStr{fd, size};
42 
43   // Test
44   ASSERT_STREQ(data.c_str(), bigStr.c_str());
45 }
46 
TEST(JSBigFileString,MapPartTest)47 TEST(JSBigFileString, MapPartTest) {
48   std::string data{"Hello, world"};
49 
50   // Sub-string to actually map
51   std::string needle{"or"};
52   off_t offset = data.find(needle);
53 
54   // Initialise Big String
55   int fd = tempFileFromString(data);
56   JSBigFileString bigStr{fd, needle.size(), offset};
57 
58   // Test
59   ABI48_0_0EXPECT_EQ(needle.length(), bigStr.size());
60   for (unsigned int i = 0; i < needle.length(); ++i) {
61     ABI48_0_0EXPECT_EQ(needle[i], bigStr.c_str()[i]);
62   }
63 }
64