82 lines
2.3 KiB
C#
82 lines
2.3 KiB
C#
using System;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using UnityEngine;
|
|
|
|
namespace FlowScope.Save
|
|
{
|
|
public sealed class SaveService : ISaveService
|
|
{
|
|
private readonly ISaveStorage _storage;
|
|
private readonly ISaveSerializer _serializer;
|
|
|
|
public SaveService(ISaveStorage storage, ISaveSerializer serializer)
|
|
{
|
|
_storage = storage ?? throw new ArgumentNullException(nameof(storage));
|
|
_serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
|
|
}
|
|
|
|
public async Task SaveAsync<T>(string key, T data, CancellationToken cancellationToken)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
try
|
|
{
|
|
var bytes = _serializer.Serialize(data);
|
|
await _storage.WriteAsync(key, bytes, cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
throw new InvalidOperationException($"Failed to write save key '{key}'.", exception);
|
|
}
|
|
}
|
|
|
|
public async Task<T> LoadAsync<T>(string key, T defaultValue, CancellationToken cancellationToken)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
byte[] bytes;
|
|
try
|
|
{
|
|
bytes = await _storage.ReadAsync(key, cancellationToken);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
throw;
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
Debug.LogWarning($"Failed to read save key '{key}': {exception.Message}");
|
|
return defaultValue;
|
|
}
|
|
|
|
if (bytes == null)
|
|
{
|
|
return defaultValue;
|
|
}
|
|
|
|
try
|
|
{
|
|
return _serializer.Deserialize<T>(bytes);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
Debug.LogWarning($"Failed to deserialize save key '{key}': {exception.Message}");
|
|
return defaultValue;
|
|
}
|
|
}
|
|
|
|
public void Delete(string key)
|
|
{
|
|
_storage.Delete(key);
|
|
}
|
|
|
|
public bool Exists(string key)
|
|
{
|
|
return _storage.Exists(key);
|
|
}
|
|
}
|
|
}
|