xref: /aosp_15_r20/external/fmtlib/test/mock-allocator.h (revision 5c90c05cd622c0a81b57953a4d343e0e489f2e08)
1 // Formatting library for C++ - mock allocator
2 //
3 // Copyright (c) 2012 - present, Victor Zverovich
4 // All rights reserved.
5 //
6 // For the license information refer to format.h.
7 
8 #ifndef FMT_MOCK_ALLOCATOR_H_
9 #define FMT_MOCK_ALLOCATOR_H_
10 
11 #include <assert.h>  // assert
12 #include <stddef.h>  // size_t
13 
14 #include <memory>  // std::allocator_traits
15 
16 #include "gmock/gmock.h"
17 
18 template <typename T> class mock_allocator {
19  public:
20   using value_type = T;
21   using size_type = size_t;
22 
23   using pointer = T*;
24   using const_pointer = const T*;
25   using reference = T&;
26   using const_reference = const T&;
27   using difference_type = ptrdiff_t;
28 
29   template <typename U> struct rebind {
30     using other = mock_allocator<U>;
31   };
32 
mock_allocator()33   mock_allocator() {}
mock_allocator(const mock_allocator &)34   mock_allocator(const mock_allocator&) {}
35 
36   MOCK_METHOD(T*, allocate, (size_t));
37   MOCK_METHOD(void, deallocate, (T*, size_t));
38 };
39 
40 template <typename Allocator> class allocator_ref {
41  private:
42   Allocator* alloc_;
43 
move(allocator_ref & other)44   void move(allocator_ref& other) {
45     alloc_ = other.alloc_;
46     other.alloc_ = nullptr;
47   }
48 
49  public:
50   using value_type = typename Allocator::value_type;
51 
alloc_(alloc)52   explicit allocator_ref(Allocator* alloc = nullptr) : alloc_(alloc) {}
53 
allocator_ref(const allocator_ref & other)54   allocator_ref(const allocator_ref& other) : alloc_(other.alloc_) {}
allocator_ref(allocator_ref && other)55   allocator_ref(allocator_ref&& other) { move(other); }
56 
57   allocator_ref& operator=(allocator_ref&& other) {
58     assert(this != &other);
59     move(other);
60     return *this;
61   }
62 
63   allocator_ref& operator=(const allocator_ref& other) {
64     alloc_ = other.alloc_;
65     return *this;
66   }
67 
68  public:
get()69   Allocator* get() const { return alloc_; }
70 
allocate(size_t n)71   value_type* allocate(size_t n) {
72     return std::allocator_traits<Allocator>::allocate(*alloc_, n);
73   }
deallocate(value_type * p,size_t n)74   void deallocate(value_type* p, size_t n) { alloc_->deallocate(p, n); }
75 };
76 
77 #endif  // FMT_MOCK_ALLOCATOR_H_
78