using System; using System.Collections.Generic; using UAF; using UAF.Interfaces.Logging; namespace DataFileAnalyzer { /// /// Manages the keys of the data file. /// Knows all the keys and all the files. Can create new keys. /// public class FileKeyManager { private ILog m_logger = new ConsoleLog(); private Dictionary m_pathToKey = new Dictionary(); private Dictionary m_keyToPath = new Dictionary(); /// /// Constructor /// public FileKeyManager() { } /// /// Delete all the keys /// public void Clear() { m_pathToKey.Clear(); m_keyToPath.Clear(); } /// /// The logger. Cannot be set to a null value. /// public ILog Logger { get { return m_logger; } set { if (value != null) m_logger = value; } } /// /// Get the path of a file from its key /// public bool GetFilePath(DataFileKey _key, out string _path) { return m_keyToPath.TryGetValue(_key, out _path); } /// /// Get the key of a file from its path /// public bool GetFileKey(string _path, out DataFileKey _key) { return m_pathToKey.TryGetValue(_path, out _key); } /// /// Create a new key. /// public bool AddFile(string _path, out DataFileKey _newKey) { if (GetUnusedKey(_path, out _newKey)) { m_pathToKey[_path] = _newKey; m_keyToPath[_newKey] = _path; return true; } return false; } /// /// Get a key that has not yet been created. /// false if this key already exists. /// public bool GetUnusedKey(string _newPath, out DataFileKey _newKey) { // Try with a hash code UInt64 hashCode = HashCode.GetUInt64HashCode(_newPath); DataFileKey newKey = new DataFileKey(hashCode); string path; if (m_keyToPath.TryGetValue(newKey, out path)) { // This hash code already exists. Look for an unused key by iterating // from 0 to the maximum possible value newKey.KeyValue = 0; while (m_keyToPath.TryGetValue(newKey, out path) && newKey != DataFileKey.Invalid) { ++newKey.KeyValue; } } _newKey = newKey; return newKey != DataFileKey.Invalid; } /// /// Register an existing key. /// false if this key already exists. /// public bool RegisterFile(DataFileKey _newKey, string _path) { string path; if (m_keyToPath.TryGetValue(_newKey, out path)) return false; m_keyToPath.Add(_newKey, _path); m_pathToKey.Add(_path, _newKey); return true; } /// /// Remove a key. /// public void RemoveKey(DataFileKey _key) { string path; if (m_keyToPath.TryGetValue(_key, out path)) { m_keyToPath.Remove(_key); m_pathToKey.Remove(path); } } } }