ArchiveBase.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. namespace OpenVIII
  9. {
  10. public abstract class ArchiveBase : IReadOnlyDictionary<string, byte[]>, IEnumerator<KeyValuePair<string, byte[]>>
  11. {
  12. #region Fields
  13. protected Memory.Archive Archive;
  14. /// <summary>
  15. /// Generated File List
  16. /// </summary>
  17. protected string[] FileList;
  18. private const int MaxInCache = 5;
  19. private const int MaxLocalCache = 5;
  20. private static readonly ConcurrentDictionary<string, ArchiveBase> Cache = new ConcurrentDictionary<string, ArchiveBase>();
  21. private static readonly object LocalAddLock = new object();
  22. private static readonly ConcurrentDictionary<string, BufferWithAge> LocalCache = new ConcurrentDictionary<string, BufferWithAge>();
  23. #endregion Fields
  24. #region Properties
  25. public ArchiveMap ArchiveMap { get; protected set; }
  26. public int Count => GetListOfFiles().Length;
  27. public DateTime Created { get; protected set; }
  28. public KeyValuePair<string, byte[]> Current => GetCurrent();
  29. object IEnumerator.Current => Enumerator;
  30. public bool IsDir { get; protected set; } = false;
  31. public bool IsOpen { get; protected set; } = false;
  32. public IEnumerable<string> Keys => GetListOfFiles();
  33. public DateTime Used { get; protected set; }
  34. public IEnumerable<byte[]> Values => GetListOfFiles().Select(x => GetBinaryFile(x));
  35. protected static IOrderedEnumerable<KeyValuePair<string, BufferWithAge>> OrderByAge => LocalCache.Where(x => x.Value != null).OrderBy(x => x.Value.Used).ThenBy(x => x.Key.Length).ThenBy(x => x.Key, StringComparer.OrdinalIgnoreCase);
  36. protected IEnumerator Enumerator { get; set; }
  37. protected List<Memory.Archive> ParentPath { get; set; }
  38. private static IEnumerable<KeyValuePair<string, ArchiveBase>> NonDirOrZzz => Cache.Where(x => x.Value != null && !x.Value.IsDir && !(x.Value is ArchiveZzz));
  39. private static IEnumerable<KeyValuePair<string, ArchiveBase>> Oldest => NonDirOrZzz.OrderBy(x => x.Value.Used).ThenBy(x => x.Value.Created);
  40. #endregion Properties
  41. #region Indexers
  42. public byte[] this[string key]
  43. {
  44. get
  45. {
  46. if (TryGetValue(key, out var value))
  47. return value;
  48. return null;
  49. }
  50. }
  51. #endregion Indexers
  52. #region Methods
  53. public static ArchiveBase Load(Memory.Archive archive)
  54. {
  55. if (archive.IsDir)
  56. {
  57. return ArchiveWorker.Load(archive);
  58. }
  59. if (archive.IsFile)
  60. {
  61. if (archive.IsFileArchive || archive.IsFileIndex || archive.IsFileList)
  62. {
  63. var a = new Memory.Archive(Path.GetFileNameWithoutExtension(archive), Path.GetDirectoryName(archive));
  64. return ArchiveWorker.Load(a);
  65. }
  66. if (archive.IsZZZ)
  67. {
  68. return ArchiveZzz.Load(archive);
  69. }
  70. return ArchiveWorker.Load(archive);
  71. }
  72. return null;
  73. }
  74. public static void PurgeCache(bool all = false)
  75. {
  76. LocalCache.ForEach(x =>
  77. {
  78. if (LocalCache.TryRemove(x.Key, out var _))
  79. {
  80. Memory.Log.WriteLine($"{nameof(ArchiveBase)}::{nameof(PurgeCache)}::Evicting: \"{x.Key}\"");
  81. }
  82. });
  83. NonDirOrZzz.ForEach(x =>
  84. {
  85. if (Cache.TryRemove(x.Key, out var _))
  86. {
  87. Memory.Log.WriteLine($"{nameof(ArchiveBase)}::{nameof(PurgeCache)}::Evicting: \"{x.Key}\"");
  88. }
  89. });
  90. if (all)
  91. {
  92. Cache.ForEach(x =>
  93. {
  94. if (Cache.TryRemove(x.Key, out var _))
  95. {
  96. Memory.Log.WriteLine($"{nameof(ArchiveBase)}::{nameof(PurgeCache)}::Evicting: \"{x.Key}\"");
  97. }
  98. });
  99. }
  100. }
  101. public bool ContainsKey(string key) => FindFile(ref key) > -1;
  102. public void Dispose()
  103. { }
  104. public abstract ArchiveBase GetArchive(string fileName);
  105. public void GetArchive(Memory.Archive archive, out StreamWithRangeValues fi, out ArchiveBase fs, out StreamWithRangeValues fl)
  106. {
  107. Memory.Log.WriteLine($"{nameof(ArchiveBase)}::{nameof(GetArchive)} - Reading: {archive.FI}, {archive.FS}, {archive.FL}");
  108. fi = GetStreamWithRangeValues(archive.FI);
  109. fs = this;
  110. fl = GetStreamWithRangeValues(archive.FL);
  111. }
  112. public void GetArchive(Memory.Archive archive, out byte[] fi, out byte[] fs, out byte[] fl)
  113. {
  114. Memory.Log.WriteLine($"{nameof(ArchiveBase)}::{nameof(GetArchive)} - Reading: {archive.FI}, {archive.FS}, {archive.FL}");
  115. fi = GetBinaryFile(archive.FI);
  116. fs = GetBinaryFile(archive.FS, cache: true);
  117. fl = GetBinaryFile(archive.FL);
  118. }
  119. public abstract ArchiveBase GetArchive(Memory.Archive archive);
  120. public abstract byte[] GetBinaryFile(string fileName, bool cache = false);
  121. public IEnumerator<KeyValuePair<string, byte[]>> GetEnumerator() => this;
  122. IEnumerator IEnumerable.GetEnumerator() => this;
  123. /// <summary>
  124. /// Get current file list for loaded archive.
  125. /// </summary>
  126. public virtual string[] GetListOfFiles(bool force = false)
  127. {
  128. if (FileList != null && !force) return FileList;
  129. FileList = ProduceFileLists();
  130. Enumerator = FileList?.GetEnumerator();
  131. return FileList;
  132. }
  133. public virtual int GetMaxSize(Memory.Archive archive)
  134. {
  135. using (var s = GetStreamWithRangeValues(archive.FS))
  136. return checked((int)s.Size);
  137. }
  138. public abstract Memory.Archive GetPath();
  139. public abstract StreamWithRangeValues GetStreamWithRangeValues(string filename);
  140. public bool MoveNext() => (GetListOfFiles()?.Length ?? 0) > 0 && Enumerator.MoveNext();
  141. public void Reset()
  142. {
  143. var list = GetListOfFiles();
  144. if (list != null && list.Length > 0)
  145. Enumerator.Reset();
  146. }
  147. public override string ToString() => $"{Archive} :: {Used}";
  148. public bool TryGetValue(string key, out byte[] value) => (value = GetBinaryFile(key)) != null;
  149. protected static bool CacheTryAdd(string key, ArchiveBase value)
  150. {
  151. if (!Cache.TryAdd(key, value)) return false;
  152. if (value != null) value.Used = value.Created = DateTime.Now;
  153. if ((Oldest.Count() - MaxInCache) > 0)
  154. Oldest.Where(x => x.Key != key).Reverse().Skip(MaxInCache)
  155. .ForEach(x => Cache.TryRemove(x.Key, out var _));
  156. return true;
  157. }
  158. protected static bool CacheTryGetValue(string path, out ArchiveBase value)
  159. {
  160. if (!Cache.TryGetValue(path, out value)) return false;
  161. if (value != null)
  162. value.Used = DateTime.Now;
  163. return true;
  164. }
  165. protected static bool LocalTryAdd(string key, BufferWithAge value)
  166. {
  167. lock (LocalAddLock)
  168. {
  169. Debug.Assert(!key.EndsWith("field.fs", StringComparison.OrdinalIgnoreCase));
  170. if (!LocalCache.TryAdd(key, value)) return false;
  171. if ((OrderByAge.Count() - MaxLocalCache) > 0)
  172. {
  173. OrderByAge.Where(x => x.Key != key).Reverse().Skip(MaxLocalCache).ForEach(x =>
  174. {
  175. if (LocalCache.TryRemove(x.Key, out var _))
  176. {
  177. Memory.Log.WriteLine(
  178. $"{nameof(ArchiveBase)}::{nameof(LocalTryAdd)}::Evicting: \"{x.Key}\"");
  179. }
  180. });
  181. }
  182. return true;
  183. }
  184. }
  185. protected virtual int FindFile(ref string filename)
  186. {
  187. if (string.IsNullOrWhiteSpace(filename)) return -1;
  188. return ArchiveMap != null && ArchiveMap.Count > 1
  189. ? ArchiveMap.FindString(ref filename, out var _) == default ? -1 : 0
  190. : -1;
  191. }
  192. protected List<Memory.Archive> FindParentPath(Memory.Archive path)
  193. {
  194. if (path.Parent == null) return null;
  195. foreach (var pathParent in path.Parent)
  196. {
  197. if (pathParent.IsDir)
  198. return new List<Memory.Archive> { pathParent };
  199. if (pathParent.IsFile)
  200. return new List<Memory.Archive> { pathParent };
  201. if (pathParent.Parent == null || pathParent.Parent.Count <= 0) continue;
  202. var returnList = FindParentPath(pathParent);
  203. if (returnList == null || returnList.Count <= 0) continue;
  204. returnList.Add(pathParent);
  205. return returnList;
  206. }
  207. return null;
  208. }
  209. protected bool LocalTryGetValue(string filename, out BufferWithAge value)
  210. {
  211. if (!LocalCache.TryGetValue(filename, out value)) return false;
  212. value?.Poke();
  213. return true;
  214. }
  215. protected virtual string[] ProduceFileLists() =>
  216. ArchiveMap != null && ArchiveMap.Count > 0
  217. ? ArchiveMap.OrderedByName.Select(x => x.Key).ToArray()
  218. : null;
  219. private KeyValuePair<string, byte[]> GetCurrent()
  220. {
  221. var s = (string)(Enumerator.Current);
  222. return new KeyValuePair<string, byte[]>(s, GetBinaryFile(s));
  223. }
  224. #endregion Methods
  225. }
  226. }