//
//  ConcurrentDictionaryExtensions.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using Remora.Results;
namespace NosSmooth.Packets.Extensions;
/// 
/// Extension methods for .
/// 
public static class ConcurrentDictionaryExtensions
{
    /// 
    /// Adds the value from the factory if it doesn't exist already,
    /// otherwise returns the existing avlue.
    /// 
    /// The dictionary.
    /// The key to add the value at.
    /// The factory to obtain the value to add.
    /// The type of the key.
    /// The type of the value.
    /// The added value.
    public static Result GetOrAddResult
    (
        this ConcurrentDictionary dictionary,
        TKey key,
        Func> valueFactory
    )
        where TKey : notnull
    {
        if (dictionary.TryGetValue(key, out var val))
        {
            return val;
        }
        var result = valueFactory(key);
        if (!result.IsSuccess)
        {
            return result;
        }
        dictionary.TryAdd(key, result.Entity);
        return result;
    }
}