JD2022-TU1/main/tools/apps/DataFileAnalyzer/FileLibrary/FileKeyManager.cs

126 lines
No EOL
3.7 KiB
C#

using System;
using System.Collections.Generic;
using UAF;
using UAF.Interfaces.Logging;
namespace DataFileAnalyzer
{
/// <summary>
/// Manages the keys of the data file.
/// Knows all the keys and all the files. Can create new keys.
/// </summary>
public class FileKeyManager
{
private ILog m_logger = new ConsoleLog();
private Dictionary<string, DataFileKey> m_pathToKey = new Dictionary<string, DataFileKey>();
private Dictionary<DataFileKey, string> m_keyToPath = new Dictionary<DataFileKey, string>();
/// <summary>
/// Constructor
/// </summary>
public FileKeyManager()
{
}
/// <summary>
/// Delete all the keys
/// </summary>
public void Clear()
{
m_pathToKey.Clear();
m_keyToPath.Clear();
}
/// <summary>
/// The logger. Cannot be set to a null value.
/// </summary>
public ILog Logger
{
get { return m_logger; }
set { if (value != null) m_logger = value; }
}
/// <summary>
/// Get the path of a file from its key
/// </summary>
public bool GetFilePath(DataFileKey _key, out string _path)
{
return m_keyToPath.TryGetValue(_key, out _path);
}
/// <summary>
/// Get the key of a file from its path
/// </summary>
public bool GetFileKey(string _path, out DataFileKey _key)
{
return m_pathToKey.TryGetValue(_path, out _key);
}
/// <summary>
/// Create a new key.
/// </summary>
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;
}
/// <summary>
/// Get a key that has not yet been created.
/// <returns> false if this key already exists.
/// </summary>
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;
}
/// <summary>
/// Register an existing key.
/// <returns> false if this key already exists.
/// </summary>
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;
}
/// <summary>
/// Remove a key.
/// </summary>
public void RemoveKey(DataFileKey _key)
{
string path;
if (m_keyToPath.TryGetValue(_key, out path))
{
m_keyToPath.Remove(_key);
m_pathToKey.Remove(path);
}
}
}
}