// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using CommunityToolkit.Helpers;
namespace CommunityToolkit.Common.Extensions;
///
/// Helpers methods for working with implementations.
///
public static class ISettingsStorageHelperExtensions
{
///
/// Attempts to read the provided key and return the value.
/// If the key is not found, the fallback value will be used instead.
///
/// The type of key used to lookup the object.
/// The type of object value expected.
/// The storage helper instance fo read from.
/// The key of the target object.
/// An alternative value returned if the read fails.
/// The value of the target object, or the fallback value.
public static TValue? GetValueOrDefault(this ISettingsStorageHelper storageHelper, TKey key, TValue? fallback = default)
where TKey : notnull
{
if (storageHelper.TryRead(key, out TValue? storedValue))
{
return storedValue;
}
else
{
return fallback;
}
}
///
/// Read the key in the storage helper instance and get the value.
///
/// The type of key used to lookup the object.
/// The type of object value expected.
/// The storage helper instance fo read from.
/// The key of the target object.
/// The value of the target object
/// Throws when the key is not found in storage.
public static TValue? Read(this ISettingsStorageHelper storageHelper, TKey key)
where TKey : notnull
{
if (storageHelper.TryRead(key, out TValue? value))
{
return value;
}
else
{
ThrowKeyNotFoundException(key);
return default;
}
}
///
/// Deletes a key from storage.
///
/// The type of key used to lookup the object.
/// The storage helper instance to delete from.
/// The key of the target object.
/// Throws when the key is not found in storage.
public static void Delete(this ISettingsStorageHelper storageHelper, TKey key)
where TKey : notnull
{
if (!storageHelper.TryDelete(key))
{
ThrowKeyNotFoundException(key);
}
}
private static void ThrowKeyNotFoundException(TKey key)
{
throw new KeyNotFoundException($"The given key '{key}' was not present.");
}
}