Browse Source

Added new TempAllocator implementation that can fall back to malloc when it runs out of its fixed size buffer

Jorrit Rouwe 1 year ago
parent
commit
3c67be7924
1 changed files with 68 additions and 2 deletions
  1. 68 2
      Jolt/Core/TempAllocator.h

+ 68 - 2
Jolt/Core/TempAllocator.h

@@ -86,16 +86,40 @@ public:
 		}
 	}
 
-	// Check if no allocations have been made
+	/// Check if no allocations have been made
 	bool							IsEmpty() const
 	{
 		return mTop == 0;
 	}
 
+	/// Get the total size of the fixed buffer
+	uint							GetSize() const
+	{
+		return mSize;
+	}
+
+	/// Get current usage in bytes of the buffer
+	uint							GetUsage() const
+	{
+		return mTop;
+	}
+
+	/// Check if an allocation of inSize can be made in this fixed buffer allocator
+	bool							CanAllocate(uint inSize) const
+	{
+		return mTop + AlignUp(inSize, JPH_RVECTOR_ALIGNMENT) <= mSize;
+	}
+
+	/// Check if memory block at inAddress is owned by this allocator
+	bool							OwnsMemory(const void *inAddress) const
+	{
+		return inAddress >= mBase && inAddress < mBase + mSize;
+	}
+
 private:
 	uint8 *							mBase;							///< Base address of the memory block
 	uint							mSize;							///< Size of the memory block
-	uint							mTop = 0;						///< Current top of the stack
+	uint							mTop = 0;						///< End of currently allocated area
 };
 
 /// Implementation of the TempAllocator that just falls back to malloc/free
@@ -119,4 +143,46 @@ public:
 	}
 };
 
+/// Implementation of the TempAllocator that tries to allocate from a large preallocated block, but falls back to malloc when it is exhausted
+class JPH_EXPORT TempAllocatorImplWithMallocFallback final : public TempAllocator
+{
+public:
+	JPH_OVERRIDE_NEW_DELETE
+
+	/// Constructs the allocator with an initial fixed block if inSize
+	explicit						TempAllocatorImplWithMallocFallback(uint inSize) :
+		mAllocator(inSize)
+	{
+	}
+
+	// See: TempAllocator
+	virtual void *					Allocate(uint inSize) override
+	{
+		if (mAllocator.CanAllocate(inSize))
+			return mAllocator.Allocate(inSize);
+		else
+			return mFallbackAllocator.Allocate(inSize);
+	}
+
+	// See: TempAllocator
+	virtual void					Free(void *inAddress, uint inSize) override
+	{
+		if (inAddress == nullptr)
+		{
+			JPH_ASSERT(inSize == 0);
+		}
+		else
+		{
+			if (mAllocator.OwnsMemory(inAddress))
+				mAllocator.Free(inAddress, inSize);
+			else
+				mFallbackAllocator.Free(inAddress, inSize);
+		}
+	}
+
+private:
+	TempAllocatorImpl				mAllocator;
+	TempAllocatorMalloc				mFallbackAllocator;
+};
+
 JPH_NAMESPACE_END