Skip to content

Commit 6c674a2

Browse files
committed
[ci skip] fully destroy immutable Scripts upon Dispose (by making the backing arrays null)
1 parent 14777b6 commit 6c674a2

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

src/Lib/Internal/ExecutableScript.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ public abstract class ExecutableScript : IDisposable
1414

1515
public ref readonly byte this[int idx] => ref GetByteAt(idx);
1616

17-
public bool IsDisposed { get; protected set; }
17+
public virtual bool IsDisposed { get; protected set; }
1818

1919
public int GetMasked(int idx) => GetByteAt(idx) & 0xFF;
2020

src/Lib/Public/Entities/Script.cs

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
1-
using Starscript.Internal;
1+
using System.Diagnostics.CodeAnalysis;
2+
using Starscript.Internal;
23

34
namespace Starscript;
45

56
public class Script : ExecutableScript
67
{
7-
private byte[] _code;
8-
private Value[] _constants;
8+
private byte[]? _code;
9+
private Value[]? _constants;
910

10-
public override ReadOnlySpan<byte> Code => _code;
11+
[MemberNotNullWhen(false, nameof(_code), nameof(_constants))]
12+
public override bool IsDisposed { get; protected set; }
1113

12-
public override ReadOnlySpan<Value> Constants => _constants;
14+
public override ReadOnlySpan<byte> Code => _code
15+
?? throw new ObjectDisposedException(nameof(Script),
16+
"Cannot access bytecode of a disposed Script.");
17+
18+
public override ReadOnlySpan<Value> Constants => _constants
19+
?? throw new ObjectDisposedException(nameof(Script),
20+
"Cannot access constants of a disposed Script.");
1321

1422
public Script(byte[] codeBuffer, Value[] constants)
1523
{
16-
_code = codeBuffer;
17-
_constants = constants;
24+
_code = codeBuffer ?? throw new NullReferenceException($"Cannot initialize a {nameof(Script)} with a null bytecode buffer.");
25+
_constants = constants ?? throw new NullReferenceException($"Cannot initialize a {nameof(Script)} with a null constants buffer.");
1826
}
1927

2028
protected override ref readonly byte GetByteAt(int idx)
@@ -29,16 +37,19 @@ public override void Dispose()
2937
{
3038
if (IsDisposed)
3139
throw new ObjectDisposedException(nameof(Script), "Cannot dispose an already disposed Script.");
32-
40+
3341
Array.Resize(ref _code, 0);
3442
Array.Resize(ref _constants, 0);
3543

44+
_code = null;
45+
_constants = null;
46+
3647
#if DEBUG
3748
Compiler.DebugLog("Destroyed script");
3849
#endif
3950

4051
IsDisposed = true;
41-
52+
4253
GC.SuppressFinalize(this);
4354
}
4455
}

0 commit comments

Comments
 (0)