FUD Allocator

Table of Contents

Published on 29 October 2024.

Last modified 29 October 2024.

All snippets on this page are licensed under the Apache License, Version 2.0 and copyrighted by myself, Dominick Allen. Code may be reformatted and truncated from its original form; don't consider what's written on this page as the actual version, but for illustrative purposes.

If you haven't read my introduction to libfud (the library), I recommend you start there.

1. Allocators

class alignas(std::max_align_t) Allocator {
  public:
    virtual ~Allocator() = default;

    virtual Result<void*, FudStatus> allocate(
        size_t bytes,
        size_t alignment = alignof(std::max_align_t)) = 0;

    virtual FudStatus deallocate(void* pointer, size_t bytes) = 0;

    virtual bool isEqual(const Allocator& rhs) const = 0;
};

constexpr bool operator==(const Allocator& lhs, const Allocator& rhs) {
    return &lhs == &rhs;
}

class FudAllocator : public Allocator {
  public:
    virtual ~FudAllocator() override = default;

    virtual Result<void*, FudStatus> allocate(
        size_t bytes,
        size_t alignment = alignof(std::max_align_t)) override;

    virtual FudStatus deallocate(void* pointer, size_t bytes) override;

    virtual bool isEqual(const Allocator& rhs) const override;
};

extern FudAllocator globalFudAllocator;

/** \brief The default allocation function for globalFudAllocator. */
extern void* fudAlloc(size_t size);

/** \brief The default deallocation function for globalFudAllocator. */
extern void fudFree(void* ptr);