1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18#include <cstdint>
19#include <limits>
20#include <memory>
21#include <new>
22
23#include <gtest/gtest.h>
24
25#include "arrow/allocator.h"
26#include "arrow/memory_pool.h"
27#include "arrow/test-util.h"
28
29namespace arrow {
30
31TEST(STLMemoryPool, Base) {
32 std::allocator<uint8_t> allocator;
33 STLMemoryPool<std::allocator<uint8_t>> pool(allocator);
34
35 uint8_t* data = nullptr;
36 ASSERT_OK(pool.Allocate(100, &data));
37 ASSERT_EQ(pool.max_memory(), 100);
38 ASSERT_EQ(pool.bytes_allocated(), 100);
39 ASSERT_NE(data, nullptr);
40
41 ASSERT_OK(pool.Reallocate(100, 150, &data));
42 ASSERT_EQ(pool.max_memory(), 150);
43 ASSERT_EQ(pool.bytes_allocated(), 150);
44
45 pool.Free(data, 150);
46
47 ASSERT_EQ(pool.max_memory(), 150);
48 ASSERT_EQ(pool.bytes_allocated(), 0);
49}
50
51TEST(stl_allocator, MemoryTracking) {
52 auto pool = default_memory_pool();
53 stl_allocator<uint64_t> alloc;
54 uint64_t* data = alloc.allocate(100);
55
56 ASSERT_EQ(100 * sizeof(uint64_t), pool->bytes_allocated());
57
58 alloc.deallocate(data, 100);
59 ASSERT_EQ(0, pool->bytes_allocated());
60}
61
62#if !(defined(ARROW_VALGRIND) || defined(ADDRESS_SANITIZER) || defined(ARROW_JEMALLOC))
63
64TEST(stl_allocator, TestOOM) {
65 stl_allocator<uint64_t> alloc;
66 uint64_t to_alloc = std::numeric_limits<uint64_t>::max() / 2;
67 ASSERT_THROW(alloc.allocate(to_alloc), std::bad_alloc);
68}
69
70TEST(stl_allocator, MaxMemory) {
71 auto pool = default_memory_pool();
72
73 stl_allocator<uint8_t> alloc(pool);
74 uint8_t* data = alloc.allocate(1000);
75 uint8_t* data2 = alloc.allocate(1000);
76
77 alloc.deallocate(data, 1000);
78 alloc.deallocate(data2, 1000);
79
80 ASSERT_EQ(2000, pool->max_memory());
81}
82
83#endif // ARROW_VALGRIND
84
85} // namespace arrow
86