1 /**
2 * Copyright 2019 Huawei Technologies Co., Ltd
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 "minddata/dataset/util/memory_pool.h"
18 #include "minddata/dataset/util/circular_pool.h"
19 #include "minddata/dataset/util/allocator.h"
20 #include "common/common.h"
21 #include "gtest/gtest.h"
22
23 using namespace mindspore::dataset;
24
25 class MindDataTestMemoryPool : public UT::Common {
26 public:
27 std::shared_ptr<MemoryPool> mp_;
MindDataTestMemoryPool()28 MindDataTestMemoryPool() {}
29
SetUp()30 void SetUp() {
31 Status rc = CircularPool::CreateCircularPool(&mp_, 1, 1, true);
32 ASSERT_TRUE(rc.IsOk());
33 }
34 };
35
TEST_F(MindDataTestMemoryPool,DumpPoolInfo)36 TEST_F(MindDataTestMemoryPool, DumpPoolInfo) {
37 MS_LOG(DEBUG) << *(std::dynamic_pointer_cast<CircularPool>(mp_)) << std::endl;
38 }
39
TEST_F(MindDataTestMemoryPool,TestOperator1)40 TEST_F(MindDataTestMemoryPool, TestOperator1) {
41 Status rc;
42 int *p = new (&rc, mp_) int;
43 ASSERT_TRUE(rc.IsOk());
44 *p = 2048;
45 ::operator delete(p, mp_);
46 }
47
TEST_F(MindDataTestMemoryPool,TestOperator3)48 TEST_F(MindDataTestMemoryPool, TestOperator3) {
49 Status rc;
50 int *p = new (&rc, mp_) int[100];
51 ASSERT_TRUE(rc.IsOk());
52 for (int i = 0; i < 100; i++) {
53 p[i] = i;
54 }
55 for (int i = 0; i < 100; i++) {
56 ASSERT_EQ(p[i], i);
57 }
58 }
59
TEST_F(MindDataTestMemoryPool,TestAllocator)60 TEST_F(MindDataTestMemoryPool, TestAllocator) {
61 class A {
62 public:
63 explicit A(int x) : a(x) {}
64 int val_a() const { return a; }
65
66 private:
67 int a;
68 };
69 Allocator<A> alloc(mp_);
70 std::shared_ptr<A> obj_a = std::allocate_shared<A>(alloc, 3);
71 int v = obj_a->val_a();
72 ASSERT_EQ(v, 3);
73 MS_LOG(DEBUG) << *(std::dynamic_pointer_cast<CircularPool>(mp_)) << std::endl;
74 }
75
TEST_F(MindDataTestMemoryPool,TestMemGuard)76 TEST_F(MindDataTestMemoryPool, TestMemGuard) {
77 MemGuard<uint8_t> mem;
78 // Try some large value.
79 int64_t sz = 5LL * 1024LL * 1024LL * 1024LL;
80 Status rc = mem.allocate(sz);
81 ASSERT_TRUE(rc.IsOk() || rc == StatusCode::kMDOutOfMemory);
82 if (rc.IsOk()) {
83 // Try write a character half way.
84 auto *p = mem.GetMutablePointer();
85 p[sz / 2] = 'a';
86 }
87 }
88