Skip to content

Commit

Permalink
fix: SOH issue (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
ikpil committed Jan 24, 2024
1 parent 77a8301 commit 401c955
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/DotRecast.Core/Buffers/RcRentedArray.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@ public class RcRentedArray<T> : IDisposable
{
private ArrayPool<T> _owner;
private T[] _array;
private readonly RcAtomicInteger _disposed;
private bool _disposed;

public int Length { get; }
public bool IsDisposed => _disposed;

internal RcRentedArray(ArrayPool<T> owner, T[] array, int length)
{
_owner = owner;
_array = array;
Length = length;
_disposed = new RcAtomicInteger(0);
_disposed = false;
}

public T this[int index]
Expand All @@ -53,9 +54,10 @@ public T[] AsRentedArray()

public void Dispose()
{
if (1 != _disposed.IncrementAndGet())
if (_disposed)
return;

_disposed = true;
_owner?.Return(_array, true);
_array = null;
_owner = null;
Expand Down
49 changes: 49 additions & 0 deletions test/DotRecast.Core.Test/RcRentedArrayTest.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using DotRecast.Core.Buffers;
using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Serialization;
using NUnit.Framework;

namespace DotRecast.Core.Test;
Expand Down Expand Up @@ -56,4 +59,50 @@ public void TestRentedArray()
Assert.Throws<NullReferenceException>(() => rentedArray[^1] = 0);
}
}

[Test]
public void TestSame()
{
// not same
{
using var r1 = RcRentedArray.RentDisposableArray<float>(1024);
using var r2 = RcRentedArray.RentDisposableArray<float>(1024);

Assert.That(r2.AsRentedArray() != r1.AsRentedArray(), Is.EqualTo(true));
}

// same
{
// error case
float[] r1Array;
using (var r1 = RcRentedArray.RentDisposableArray<float>(1024))
{
r1Array = r1.AsRentedArray();
for (int i = 0; i < r1.Length; ++i)
{
r1[i] = 123;
}
}

using var r2 = RcRentedArray.RentDisposableArray<float>(1024);

Assert.That(r2.AsRentedArray() == r1Array, Is.EqualTo(true));
Assert.That(r2.AsRentedArray().Sum(), Is.EqualTo(0));
}
}

[Test]
public void TestDispose()
{
var r1 = RcRentedArray.RentDisposableArray<float>(1024);
for (int i = 0; i < r1.Length; ++i)
{
r1[i] = 123;
}

Assert.That(r1.IsDisposed, Is.EqualTo(false));
r1.Dispose();
Assert.That(r1.IsDisposed, Is.EqualTo(true));
Assert.That(r1.AsRentedArray(), Is.Null);
}
}

0 comments on commit 401c955

Please sign in to comment.