using GFramework.Core.Abstractions.storage;
using GFramework.Game.Abstractions.storage;
namespace GFramework.Game.storage;
///
/// 提供带有作用域前缀的存储包装器,将所有键都加上指定的前缀
///
/// 内部的实际存储实现
/// 用于所有键的前缀字符串
public sealed class ScopedStorage(IStorage inner, string prefix) : IScopedStorage
{
///
/// 检查指定键是否存在
///
/// 要检查的键
/// 如果键存在则返回true,否则返回false
public bool Exists(string key)
{
return inner.Exists(Key(key));
}
///
/// 异步检查指定键是否存在
///
/// 要检查的键
/// 如果键存在则返回true,否则返回false
public Task ExistsAsync(string key)
{
return inner.ExistsAsync(Key(key));
}
///
/// 读取指定键的值
///
/// 要读取的值的类型
/// 要读取的键
/// 键对应的值
public T Read(string key)
{
return inner.Read(Key(key));
}
///
/// 读取指定键的值,如果键不存在则返回默认值
///
/// 要读取的值的类型
/// 要读取的键
/// 当键不存在时返回的默认值
/// 键对应的值或默认值
public T Read(string key, T defaultValue)
{
return inner.Read(Key(key), defaultValue);
}
///
/// 异步读取指定键的值
///
/// 要读取的值的类型
/// 要读取的键
/// 键对应的值的任务
public Task ReadAsync(string key)
{
return inner.ReadAsync(Key(key));
}
///
/// 写入指定键值对
///
/// 要写入的值的类型
/// 要写入的键
/// 要写入的值
public void Write(string key, T value)
{
inner.Write(Key(key), value);
}
///
/// 异步写入指定键值对
///
/// 要写入的值的类型
/// 要写入的键
/// 要写入的值
public Task WriteAsync(string key, T value)
{
return inner.WriteAsync(Key(key), value);
}
///
/// 删除指定键
///
/// 要删除的键
public void Delete(string key)
{
inner.Delete(Key(key));
}
///
/// 异步删除指定键
///
/// 要删除的键
/// 异步操作任务
public async Task DeleteAsync(string key)
{
await inner.DeleteAsync(Key(key));
}
///
/// 为给定的键添加前缀
///
/// 原始键
/// 添加前缀后的键
private string Key(string key)
{
return string.IsNullOrEmpty(prefix)
? key
: $"{prefix}/{key}";
}
///
/// 创建一个新的作用域存储实例
///
/// 新的作用域名称
/// 新的作用域存储实例
public IStorage Scope(string scope)
{
return new ScopedStorage(inner, Key(scope));
}
}