aboutsummaryrefslogtreecommitdiff
path: root/pw_allocator/pw_allocator_private/allocator_testing.h
blob: 03bf07365c7106a22ad1d4180388a12644e8cd2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright 2023 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once

#include <array>
#include <cstddef>

#include "pw_allocator/allocator.h"
#include "pw_allocator/block.h"
#include "pw_bytes/span.h"

namespace pw::allocator::test {

/// Fake memory allocator for testing.
///
/// This allocator can return a fixed number of allocations made using an
/// internal buffer. It records the most recent parameters passed to the
/// `Allocator` interface methods, and returns them via accessors.
class FakeAllocator : public Allocator {
 public:
  constexpr FakeAllocator() = default;

  size_t allocate_size() const { return allocate_size_; }
  void* deallocate_ptr() const { return deallocate_ptr_; }
  size_t deallocate_size() const { return deallocate_size_; }
  void* resize_ptr() const { return resize_ptr_; }
  size_t resize_old_size() const { return resize_old_size_; }
  size_t resize_new_size() const { return resize_new_size_; }

  /// Provides memory for the allocator to allocate from.
  Status Initialize(ByteSpan buffer);

  /// Allocates all the memory from this object.
  void Exhaust();

  /// Resets the recorded parameters to an initial state.
  void ResetParameters();

 private:
  /// @copydoc Allocator::Query
  Status DoQuery(const void* ptr, size_t size, size_t alignment) const override;

  /// @copydoc Allocator::Allocate
  void* DoAllocate(size_t size, size_t alignment) override;

  /// @copydoc Allocator::Deallocate
  void DoDeallocate(void* ptr, size_t size, size_t alignment) override;

  /// @copydoc Allocator::Resize
  bool DoResize(void* ptr,
                size_t old_size,
                size_t old_alignment,
                size_t new_size) override;

  Block* head_ = nullptr;
  size_t allocate_size_ = 0;
  void* deallocate_ptr_ = nullptr;
  size_t deallocate_size_ = 0;
  void* resize_ptr_ = nullptr;
  size_t resize_old_size_ = 0;
  size_t resize_new_size_ = 0;
};

}  // namespace pw::allocator::test