From cadc9a10a42f0ea365f266938884f79c695116ca Mon Sep 17 00:00:00 2001 From: Ionite Date: Fri, 15 Dec 2023 16:38:00 -0500 Subject: [PATCH] Switch to immutable collections in ProcessArgsBuilder --- .../Processes/ProcessArgsBuilder.cs | 54 +++++++++++-------- 1 file changed, 32 insertions(+), 22 deletions(-) diff --git a/StabilityMatrix.Core/Processes/ProcessArgsBuilder.cs b/StabilityMatrix.Core/Processes/ProcessArgsBuilder.cs index 00a0e812..e1e9ffc5 100644 --- a/StabilityMatrix.Core/Processes/ProcessArgsBuilder.cs +++ b/StabilityMatrix.Core/Processes/ProcessArgsBuilder.cs @@ -1,6 +1,5 @@ -using System.Diagnostics; +using System.Collections.Immutable; using System.Diagnostics.Contracts; -using OneOf; namespace StabilityMatrix.Core.Processes; @@ -9,14 +8,7 @@ namespace StabilityMatrix.Core.Processes; /// public record ProcessArgsBuilder { - protected ProcessArgsBuilder() { } - - public ProcessArgsBuilder(params Argument[] arguments) - { - Arguments = arguments.ToList(); - } - - public List Arguments { get; init; } = new(); + public IImmutableList Arguments { get; init; } = ImmutableArray.Empty; private IEnumerable ToStringArgs() { @@ -34,6 +26,11 @@ public record ProcessArgsBuilder } } + public ProcessArgsBuilder(params Argument[] arguments) + { + Arguments = arguments.ToImmutableArray(); + } + /// public override string ToString() { @@ -45,8 +42,7 @@ public record ProcessArgsBuilder return ToStringArgs().ToArray(); } - public static implicit operator ProcessArgs(ProcessArgsBuilder builder) => - builder.ToProcessArgs(); + public static implicit operator ProcessArgs(ProcessArgsBuilder builder) => builder.ToProcessArgs(); } public static class ProcessArgBuilderExtensions @@ -55,7 +51,26 @@ public static class ProcessArgBuilderExtensions public static T AddArg(this T builder, Argument argument) where T : ProcessArgsBuilder { - return builder with { Arguments = builder.Arguments.Append(argument).ToList() }; + return builder with { Arguments = builder.Arguments.Add(argument) }; + } + + [Pure] + public static T UpdateArg(this T builder, string key, Argument argument) + where T : ProcessArgsBuilder + { + var oldArg = builder + .Arguments + .FirstOrDefault(x => x.Match(stringArg => stringArg == key, tupleArg => tupleArg.Item1 == key)); + + if (oldArg is null) + { + return builder.AddArg(argument); + } + + return builder with + { + Arguments = builder.Arguments.Replace(oldArg, argument) + }; } [Pure] @@ -64,15 +79,10 @@ public static class ProcessArgBuilderExtensions { return builder with { - Arguments = builder.Arguments - .Where( - x => - x.Match( - stringArg => stringArg != argumentKey, - tupleArg => tupleArg.Item1 != argumentKey - ) - ) - .ToList() + Arguments = builder + .Arguments + .Where(x => x.Match(stringArg => stringArg != argumentKey, tupleArg => tupleArg.Item1 != argumentKey)) + .ToImmutableArray() }; } }