Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions src/IAllocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ namespace SharpAllocators;

public unsafe interface IAllocator
{
public T* Allocate<T>(nuint elementCount) where T : unmanaged;
public void Free<T>(T* pointer) where T : unmanaged;
public T* Reallocate<T>(T* pointer, nuint elementCount) where T : unmanaged;
public MemorySlice<T> Allocate<T>(nuint elementCount) where T : unmanaged;
public void Free<T>(MemorySlice<T> memorySlice) where T : unmanaged;
public MemorySlice<T> Reallocate<T>(T* pointer, nuint elementCount) where T : unmanaged;
public MemorySlice<T> Reallocate<T>(MemorySlice<T> memorySlice) where T : unmanaged
{
return Reallocate(memorySlice.Pointer, memorySlice.Length);
}
}
23 changes: 23 additions & 0 deletions src/MemorySlice.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// Copyright (c) 2026 Viktor Stojanović. All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace SharpAllocators;

public readonly unsafe struct MemorySlice<T> where T : unmanaged
{
public T* Pointer { get; }
public nuint Length { get; }
public nuint ByteLength => Length * (nuint)sizeof(T);

public MemorySlice(T* pointer, nuint length)
{
Pointer = pointer;
Length = length;
}

public void Deconstruct(out T* pointer, out nuint lenght)
{
pointer = Pointer;
lenght = Length;
}
}
16 changes: 10 additions & 6 deletions src/NativeAllocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,24 @@ namespace SharpAllocators;
public readonly unsafe struct NativeAllocator : IAllocator
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T* Allocate<T>(nuint elementCount) where T : unmanaged
public MemorySlice<T> Allocate<T>(nuint elementCount) where T : unmanaged
{
return (T*)NativeMemory.Alloc(elementCount * (nuint)sizeof(T));
var pointer = (T*)NativeMemory.Alloc(elementCount * (nuint)sizeof(T));

return new(pointer, elementCount);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Free<T>(T* pointer) where T : unmanaged
public void Free<T>(MemorySlice<T> memorySlice) where T : unmanaged
{
NativeMemory.Free(pointer);
NativeMemory.Free(memorySlice.Pointer);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T* Reallocate<T>(T* pointer, nuint elementCount) where T : unmanaged
public MemorySlice<T> Reallocate<T>(T* pointer, nuint elementCount) where T : unmanaged
{
return (T*)NativeMemory.Realloc(pointer, elementCount);
var reallocatedPointer = (T*)NativeMemory.Realloc(pointer, elementCount);

return new(reallocatedPointer, elementCount);
}
}
Loading