badd344718fceb5dbc86fb4d18b9e9cbd4d8e96f
[folly.git] / folly / test / MemcpyTest.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 #include <gtest/gtest.h>
18
19 namespace {
20
21 constexpr size_t SIZE = 4096 * 4;
22 char src[SIZE];
23 char dst[SIZE];
24
25 void init() {
26   for (size_t i = 0; i < SIZE; ++i) {
27     src[i] = static_cast<char>(i);
28     dst[i] = static_cast<char>(255 - i);
29   }
30 }
31 }
32
33 TEST(memcpy, zero_len) {
34   // If length is 0, we shouldn't touch any memory.  So this should
35   // not crash.
36   char* srcNull = nullptr;
37   char* dstNull = nullptr;
38   memcpy(dstNull, srcNull, 0);
39 }
40
41 // Test copy `len' bytes and verify that exactly `len' bytes are copied.
42 void testLen(size_t len) {
43   if (len > SIZE) {
44     return;
45   }
46   init();
47   memcpy(dst, src, len);
48   for (size_t i = 0; i < len; ++i) {
49     EXPECT_EQ(src[i], static_cast<char>(i));
50     EXPECT_EQ(src[i], dst[i]);
51   }
52   if (len < SIZE) {
53     EXPECT_EQ(src[len], static_cast<char>(len));
54     EXPECT_EQ(dst[len], static_cast<char>(255 - len));
55   }
56 }
57
58 TEST(memcpy, small) {
59   for (size_t len = 1; len < 8; ++len) {
60     testLen(len);
61   }
62 }
63
64 TEST(memcpy, main) {
65   for (size_t len = 8; len < 128; ++len) {
66     testLen(len);
67   }
68
69   for (size_t len = 128; len < SIZE; len += 128) {
70     testLen(len);
71   }
72
73   for (size_t len = 128; len < SIZE; len += 73) {
74     testLen(len);
75   }
76 }