From 950775b65093e22ce209c947bf9da71b17ad7387 Mon Sep 17 00:00:00 2001 From: Austin Drenski Date: Wed, 17 Jan 2024 13:22:04 -0500 Subject: [PATCH] fix: Fix ArgumentOutOfRangeException for empty hooks (#187) Signed-off-by: Austin Drenski --- src/OpenFeature/Api.cs | 21 ++++++++++++++++++- src/OpenFeature/OpenFeatureClient.cs | 21 ++++++++++++++++++- .../OpenFeature.Tests/OpenFeatureHookTests.cs | 7 +++++++ 3 files changed, 47 insertions(+), 2 deletions(-) diff --git a/src/OpenFeature/Api.cs b/src/OpenFeature/Api.cs index 8d0e22f5..440242da 100644 --- a/src/OpenFeature/Api.cs +++ b/src/OpenFeature/Api.cs @@ -127,7 +127,26 @@ public FeatureClient GetClient(string name = null, string version = null, ILogge /// /// /// A list of - public void AddHooks(IEnumerable hooks) => this._hooks.PushRange(hooks.ToArray()); + public void AddHooks(IEnumerable 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 /// /// Adds a hook to global hooks list diff --git a/src/OpenFeature/OpenFeatureClient.cs b/src/OpenFeature/OpenFeatureClient.cs index 9ea9b13a..d979dae1 100644 --- a/src/OpenFeature/OpenFeatureClient.cs +++ b/src/OpenFeature/OpenFeatureClient.cs @@ -106,7 +106,26 @@ public void RemoveHandler(ProviderEventTypes type, EventHandlerDelegate handler) } /// - public void AddHooks(IEnumerable hooks) => this._hooks.PushRange(hooks.ToArray()); + public void AddHooks(IEnumerable 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 /// public IEnumerable GetHooks() => this._hooks.Reverse(); diff --git a/test/OpenFeature.Tests/OpenFeatureHookTests.cs b/test/OpenFeature.Tests/OpenFeatureHookTests.cs index a4810c04..b3aee4d8 100644 --- a/test/OpenFeature.Tests/OpenFeatureHookTests.cs +++ b/test/OpenFeature.Tests/OpenFeatureHookTests.cs @@ -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()); } + + [Fact] + public void Add_hooks_should_accept_empty_enumerable() + { + Api.Instance.ClearHooks(); + Api.Instance.AddHooks(Enumerable.Empty()); + } } }