using System.Collections.Immutable; using System.Diagnostics.Contracts; namespace StabilityMatrix.Core.Processes; /// /// Builder for . /// public record ProcessArgsBuilder { public IImmutableList Arguments { get; init; } = ImmutableArray.Empty; private IEnumerable ToStringArgs() { foreach (var argument in Arguments) { if (argument.IsT0) { yield return argument.AsT0; } else { yield return argument.AsT1.Item1; yield return argument.AsT1.Item2; } } } public ProcessArgsBuilder(params Argument[] arguments) { Arguments = arguments.ToImmutableArray(); } /// public override string ToString() { return ToProcessArgs().ToString(); } public ProcessArgs ToProcessArgs() { return ToStringArgs().ToArray(); } public static implicit operator ProcessArgs(ProcessArgsBuilder builder) => builder.ToProcessArgs(); } public static class ProcessArgBuilderExtensions { [Pure] public static T AddArg(this T builder, Argument argument) where T : ProcessArgsBuilder { return builder with { Arguments = builder.Arguments.Add(argument) }; } [Pure] public static T AddArgs(this T builder, params Argument[] argument) where T : ProcessArgsBuilder { return builder with { Arguments = builder.Arguments.AddRange(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] public static T RemoveArgKey(this T builder, string argumentKey) where T : ProcessArgsBuilder { return builder with { Arguments = builder .Arguments .Where(x => x.Match(stringArg => stringArg != argumentKey, tupleArg => tupleArg.Item1 != argumentKey)) .ToImmutableArray() }; } }