Skip to content

Commit ce9b713

Browse files
committed
Make Result<TValue> directly equatable
1 parent c40bf81 commit ce9b713

File tree

1 file changed

+35
-1
lines changed
  • CommunityToolkit.Mvvm.SourceGenerators/Models

1 file changed

+35
-1
lines changed

CommunityToolkit.Mvvm.SourceGenerators/Models/Result.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@
55
// This file is ported and adapted from ComputeSharp (Sergio0694/ComputeSharp),
66
// more info in ThirdPartyNotices.txt in the root of the project.
77

8+
using System;
9+
using System.Collections.Generic;
810
using System.Collections.Immutable;
11+
using System.Linq;
12+
using CommunityToolkit.Mvvm.SourceGenerators.Extensions;
13+
using CommunityToolkit.Mvvm.SourceGenerators.Helpers;
914

1015
namespace CommunityToolkit.Mvvm.SourceGenerators.Models;
1116

@@ -15,4 +20,33 @@ namespace CommunityToolkit.Mvvm.SourceGenerators.Models;
1520
/// <typeparam name="TValue">The type of the wrapped value.</typeparam>
1621
/// <param name="Value">The wrapped value for the current result.</param>
1722
/// <param name="Errors">The associated diagnostic errors, if any.</param>
18-
internal sealed record Result<TValue>(TValue Value, ImmutableArray<DiagnosticInfo> Errors);
23+
internal sealed record Result<TValue>(TValue Value, ImmutableArray<DiagnosticInfo> Errors)
24+
where TValue : IEquatable<TValue>?
25+
{
26+
/// <inheritdoc/>
27+
public bool Equals(Result<TValue>? obj) => Comparer.Default.Equals(this, obj);
28+
29+
/// <inheritdoc/>
30+
public override int GetHashCode() => Comparer.Default.GetHashCode(this);
31+
32+
/// <summary>
33+
/// An <see cref="IEqualityComparer{T}"/> implementation for <see cref="Result{TValue}"/>.
34+
/// </summary>
35+
private sealed class Comparer : Comparer<Result<TValue>, Comparer>
36+
{
37+
/// <inheritdoc/>
38+
protected override void AddToHashCode(ref HashCode hashCode, Result<TValue> obj)
39+
{
40+
hashCode.Add(obj.Value);
41+
hashCode.AddRange(obj.Errors);
42+
}
43+
44+
/// <inheritdoc/>
45+
protected override bool AreEqual(Result<TValue> x, Result<TValue> y)
46+
{
47+
return
48+
EqualityComparer<TValue>.Default.Equals(x.Value, y.Value) &&
49+
x.Errors.SequenceEqual(y.Errors);
50+
}
51+
}
52+
}

0 commit comments

Comments
 (0)