-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
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
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
50 changes: 50 additions & 0 deletions
50
framework/OpenMod.Core/Persistence/YamlNullableEnumTypeConverter.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
using System; | ||
using OpenMod.API; | ||
using YamlDotNet.Core; | ||
using YamlDotNet.Core.Events; | ||
using YamlDotNet.Serialization; | ||
|
||
namespace OpenMod.Core.Persistence | ||
{ | ||
/// Fixes an issue introduced in YamlDotNet 9.1 | ||
/// https://github.com/aaubry/YamlDotNet/issues/544 | ||
[OpenModInternal] | ||
public class YamlNullableEnumTypeConverter : IYamlTypeConverter | ||
{ | ||
public bool Accepts(Type type) | ||
{ | ||
return Nullable.GetUnderlyingType(type)?.IsEnum ?? false; | ||
} | ||
|
||
public object ReadYaml(IParser parser, Type type) | ||
{ | ||
type = Nullable.GetUnderlyingType(type) ?? throw new ArgumentException("Expected nullable enum type for ReadYaml"); | ||
var scalar = parser.Consume<Scalar>(); | ||
|
||
if (string.IsNullOrWhiteSpace(scalar.Value)) | ||
{ | ||
return null; | ||
} | ||
|
||
try | ||
{ | ||
return Enum.Parse(type, scalar.Value); | ||
} | ||
catch(Exception ex) | ||
{ | ||
throw new Exception($"Invalid value: \"{scalar.Value}\" for {type.Name}", ex); | ||
} | ||
} | ||
|
||
public void WriteYaml(IEmitter emitter, object value, Type type) | ||
{ | ||
type = Nullable.GetUnderlyingType(type) ?? throw new ArgumentException("Expected nullable enum type for WriteYaml"); | ||
|
||
if (value != null) | ||
{ | ||
var toWrite = Enum.GetName(type, value) ?? throw new InvalidOperationException($"Invalid value {value} for enum: {type}"); | ||
emitter.Emit(new Scalar(null, null, toWrite, ScalarStyle.Any, true, false)); | ||
} | ||
} | ||
} | ||
} |