-
-
Save riemannulus/7405e0d361364c6afa0ab433905ae81c to your computer and use it in GitHub Desktop.
Registry suggestion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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