Skip to content

Commit

Permalink
fix: Fix ArgumentOutOfRangeException for empty hooks (open-feature#187)
Browse files Browse the repository at this point in the history
Signed-off-by: Austin Drenski <[email protected]>
  • Loading branch information
austindrenski authored Jan 17, 2024
1 parent a6062fe commit 950775b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
21 changes: 20 additions & 1 deletion src/OpenFeature/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,26 @@ public FeatureClient GetClient(string name = null, string version = null, ILogge
/// </para>
/// </summary>
/// <param name="hooks">A list of <see cref="Hook"/></param>
public void AddHooks(IEnumerable<Hook> hooks) => this._hooks.PushRange(hooks.ToArray());
public void AddHooks(IEnumerable<Hook> hooks)
#if NET7_0_OR_GREATER
=> this._hooks.PushRange(hooks as Hook[] ?? hooks.ToArray());
#else
{
// See: https://github.com/dotnet/runtime/issues/62121
if (hooks is Hook[] array)
{
if (array.Length > 0)
this._hooks.PushRange(array);

return;
}

array = hooks.ToArray();

if (array.Length > 0)
this._hooks.PushRange(array);
}
#endif

/// <summary>
/// Adds a hook to global hooks list
Expand Down
21 changes: 20 additions & 1 deletion src/OpenFeature/OpenFeatureClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,26 @@ public void RemoveHandler(ProviderEventTypes type, EventHandlerDelegate handler)
}

/// <inheritdoc />
public void AddHooks(IEnumerable<Hook> hooks) => this._hooks.PushRange(hooks.ToArray());
public void AddHooks(IEnumerable<Hook> hooks)
#if NET7_0_OR_GREATER
=> this._hooks.PushRange(hooks as Hook[] ?? hooks.ToArray());
#else
{
// See: https://github.com/dotnet/runtime/issues/62121
if (hooks is Hook[] array)
{
if (array.Length > 0)
this._hooks.PushRange(array);

return;
}

array = hooks.ToArray();

if (array.Length > 0)
this._hooks.PushRange(array);
}
#endif

/// <inheritdoc />
public IEnumerable<Hook> GetHooks() => this._hooks.Reverse();
Expand Down
7 changes: 7 additions & 0 deletions test/OpenFeature.Tests/OpenFeatureHookTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -553,5 +553,12 @@ public async Task When_Error_Occurs_In_After_Hook_Should_Invoke_Error_Hook()

await featureProvider.DidNotReceive().ResolveBooleanValue("test", false, Arg.Any<EvaluationContext>());
}

[Fact]
public void Add_hooks_should_accept_empty_enumerable()
{
Api.Instance.ClearHooks();
Api.Instance.AddHooks(Enumerable.Empty<Hook>());
}
}
}

0 comments on commit 950775b

Please sign in to comment.