Skip to content

Instantly share code, notes, and snippets.

@riemannulus
Created September 2, 2022 10:13
Show Gist options
  • Save riemannulus/7405e0d361364c6afa0ab433905ae81c to your computer and use it in GitHub Desktop.
Save riemannulus/7405e0d361364c6afa0ab433905ae81c to your computer and use it in GitHub Desktop.
Registry suggestion
public static IAction Deserialize(Bencodex.Types.Dictionary serialized)
{
if (!serialized.TryGetValue((Text)"type_id", out IValue typeIdValue))
{
throw new ArgumentException("No type_id field found.", nameof(serialized));
}
if (!serialized.TryGetValue((Text)"values", out IValue values))
{
throw new ArgumentException("No values field found.", nameof(serialized));
}
if (!(typeIdValue is Bencodex.Types.Integer typeIdInt))
{
throw new ArgumentException(
"type_id field is not an integer.",
nameof(serialized)
);
}
var typeId = (TypeId)(short)typeIdInt;
Type actionType = Instantiate(typeId);
var actionObject = Activator.CreateInstance(actionType, new List().Add(values));
if (actionObject is IAction action)
{
return action;
}
throw new ArgumentException(
"Cannot initialize action.",
nameof(serialized)
);
}
private static Type Instantiate(TypeId typeId) =>
typeId switch
{
TypeId.Mint => typeof(Mint),
TypeId.Transfer => typeof(Transfer),
_ => throw new ArgumentOutOfRangeException(
nameof(typeId),
typeId,
"Unknown system type ID."
),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment