| | | 1 | | using System.Text.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace Elsa.Workflows.Serialization.ReferenceHandlers; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// A custom reference resolver that uses a <see cref="ReferenceEqualityComparer"/> to compare objects. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <remarks>We only need this class because the built-in <c>PreserveReferenceResolver"</c> is internal</remarks> |
| | | 10 | | public class CustomPreserveReferenceResolver : ReferenceResolver |
| | | 11 | | { |
| | | 12 | | private uint _referenceCount; |
| | 444 | 13 | | private readonly Dictionary<string, object> _referenceIdToObjectMap = new(); |
| | 444 | 14 | | private readonly Dictionary<object, string> _objectToReferenceIdMap = new(ReferenceEqualityComparer.Instance); |
| | | 15 | | |
| | | 16 | | /// <inheritdoc /> |
| | | 17 | | public override void AddReference(string referenceId, object value) |
| | | 18 | | { |
| | 1193 | 19 | | if (!_referenceIdToObjectMap.TryAdd(referenceId, value)) |
| | 0 | 20 | | throw new JsonException(); |
| | 1193 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Tries to add a reference. |
| | | 25 | | /// </summary> |
| | | 26 | | public bool TryAddReference(string referenceId, object value) |
| | | 27 | | { |
| | 0 | 28 | | return _referenceIdToObjectMap.TryAdd(referenceId, value); |
| | | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc /> |
| | | 32 | | public override string GetReference(object value, out bool alreadyExists) |
| | | 33 | | { |
| | 3224 | 34 | | if (_objectToReferenceIdMap.TryGetValue(value, out var referenceId)) |
| | | 35 | | { |
| | 0 | 36 | | alreadyExists = true; |
| | | 37 | | } |
| | | 38 | | else |
| | | 39 | | { |
| | 3224 | 40 | | _referenceCount++; |
| | 3224 | 41 | | referenceId = _referenceCount.ToString(); |
| | 3224 | 42 | | _objectToReferenceIdMap.Add(value, referenceId); |
| | 3224 | 43 | | alreadyExists = false; |
| | | 44 | | } |
| | | 45 | | |
| | 3224 | 46 | | return referenceId; |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | /// <inheritdoc /> |
| | | 50 | | public override object ResolveReference(string referenceId) => |
| | 0 | 51 | | !_referenceIdToObjectMap.TryGetValue(referenceId, out var value) ? throw new JsonException() : value; |
| | | 52 | | |
| | | 53 | | /// <summary> |
| | | 54 | | /// Determines whether the specified value has a reference. |
| | | 55 | | /// </summary> |
| | | 56 | | /// <param name="value">The value.</param> |
| | | 57 | | /// <returns><c>true</c> if the specified value has a reference; otherwise, <c>false</c>.</returns> |
| | 85 | 58 | | public bool HasReference(object value) => _objectToReferenceIdMap.ContainsKey(value); |
| | | 59 | | } |