aspclassic-core/AspClassic.Scripting/Runtime/ContextId.cs
Jelle Luteijn 484dbfc9d9 progress
2022-05-15 11:19:49 +02:00

78 lines
1.4 KiB
C#

using System;
using System.Collections.Generic;
namespace AspClassic.Scripting.Runtime;
[Serializable]
public struct ContextId : IEquatable<ContextId>
{
private int _id;
private static Dictionary<object, ContextId> _contexts = new Dictionary<object, ContextId>();
private static int _maxId = 1;
public static readonly ContextId Empty = default(ContextId);
public int Id => _id;
internal ContextId(int id)
{
_id = id;
}
public static ContextId RegisterContext(object identifier)
{
lock (_contexts)
{
if (_contexts.TryGetValue(identifier, out var _))
{
throw Error.LanguageRegistered();
}
ContextId result = default(ContextId);
result._id = _maxId++;
return result;
}
}
public static ContextId LookupContext(object identifier)
{
lock (_contexts)
{
if (_contexts.TryGetValue(identifier, out var value))
{
return value;
}
}
return Empty;
}
public bool Equals(ContextId other)
{
return _id == other._id;
}
public override int GetHashCode()
{
return _id;
}
public override bool Equals(object obj)
{
if (!(obj is ContextId contextId))
{
return false;
}
return contextId._id == _id;
}
public static bool operator ==(ContextId self, ContextId other)
{
return self.Equals(other);
}
public static bool operator !=(ContextId self, ContextId other)
{
return !self.Equals(other);
}
}