xref: /aosp_15_r20/external/pigweed/pw_allocator/public/pw_allocator/null_allocator.h (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2023 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #pragma once
15 
16 #include <cstddef>
17 
18 #include "pw_allocator/allocator.h"
19 #include "pw_allocator/capability.h"
20 
21 namespace pw::allocator {
22 
23 /// A memory allocator that always fails to allocate memory.
24 ///
25 /// A null allocator may be useful as part of a larger framework if allocation
26 /// should be disallowed under certain circumstances. For example, a function
27 /// that returns different allocators based on an input parameter may return a
28 /// null allocator when given an invalid or unsupported parameter value.
29 class NullAllocator : public Allocator {
30  public:
31   static constexpr Capabilities kCapabilities = 0;
32 
33   // TODO(b/326509341): Make the constructor private once downstream consumers
34   // are migrated.
35   friend NullAllocator& GetNullAllocator();
NullAllocator()36   constexpr NullAllocator() : Allocator(kCapabilities) {}
37 
38  private:
39   /// @copydoc Allocator::Allocate
DoAllocate(Layout)40   void* DoAllocate(Layout) override { return nullptr; }
41 
42   /// @copydoc Allocator::Deallocate
DoDeallocate(void *)43   void DoDeallocate(void*) override {}
44 
45   /// @copydoc Allocator::Deallocate
DoDeallocate(void * ptr,Layout)46   void DoDeallocate(void* ptr, Layout) override { DoDeallocate(ptr); }
47 };
48 
49 /// Returns a reference to the NullAllocator singleton.
50 NullAllocator& GetNullAllocator();
51 
52 }  // namespace pw::allocator
53