namespace Sandbox; /// /// Allows storing files by hashed keys, rather than by actual filename. This is sometimes useful. /// public sealed class KeyStore { private BaseFileSystem _fs { get; set; } private KeyStore() { } /// /// Creates a keystore which is in a global cache position. The folder can be /// deleted at any time, and it's all fine and no-one cares. /// public static KeyStore CreateGlobalCache() { var ks = new KeyStore(); // make sure this folder exists EngineFileSystem.Root.CreateDirectory( "/.source2/cache" ); ks._fs = EngineFileSystem.Root.CreateSubSystem( "/.source2/cache" ); return ks; } private string GetPath( string key ) { key ??= "null"; return $"{key.Md5()}.bin"; } /// /// Store a bunch of bytes /// public void Set( string key, byte[] data ) { if ( key is null ) throw new ArgumentNullException( nameof( key ) ); if ( data is null ) throw new ArgumentNullException( nameof( data ) ); _fs.WriteAllBytes( GetPath( key ), data ); } /// /// Get stored bytes, or return null /// public byte[] Get( string key ) { var path = GetPath( key ); return _fs.FileExists( path ) ? _fs.ReadAllBytes( path ).ToArray() : null; } /// /// Get stored bytes, or return false /// public bool TryGet( string key, out byte[] data ) { var path = GetPath( key ); if ( _fs.FileExists( path ) ) { data = _fs.ReadAllBytes( path ).ToArray(); return true; } data = Array.Empty(); return false; } /// /// Check if a key exists /// public bool Exists( string key ) { return _fs.FileExists( GetPath( key ) ); } /// /// Remove a key /// public void Remove( string key ) { var path = GetPath( key ); if ( _fs.FileExists( path ) ) _fs.DeleteFile( path ); } }