Import YamlDotNet.

This commit is contained in:
2022-12-12 22:23:49 +08:00
parent f559cea826
commit 1477e907e6
462 changed files with 27142 additions and 0 deletions

View File

@@ -0,0 +1,119 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using YamlDotNet.Core;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class ArrayNodeDeserializer : INodeDeserializer
{
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
if (!expectedType.IsArray)
{
value = false;
return false;
}
var itemType = expectedType.GetElementType()!; // Arrays always have an element type
var items = new ArrayList();
CollectionNodeDeserializer.DeserializeHelper(itemType, parser, nestedObjectDeserializer, items, true);
var array = Array.CreateInstance(itemType, items.Count);
items.CopyTo(array, 0);
value = array;
return true;
}
private sealed class ArrayList : IList
{
private object?[] data;
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Initialized inside Clear()
public ArrayList()
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
{
Clear();
}
public int Add(object? value)
{
if (Count == data.Length)
{
Array.Resize(ref data, data.Length * 2);
}
data[Count] = value;
return Count++;
}
public void Clear()
{
data = new object[10];
Count = 0;
}
bool IList.Contains(object? value) => throw new NotSupportedException();
int IList.IndexOf(object? value) => throw new NotSupportedException();
void IList.Insert(int index, object? value) => throw new NotSupportedException();
void IList.Remove(object? value) => throw new NotSupportedException();
void IList.RemoveAt(int index) => throw new NotSupportedException();
public bool IsFixedSize => false;
public bool IsReadOnly => false;
public object? this[int index]
{
get
{
return data[index];
}
set
{
data[index] = value;
}
}
public void CopyTo(Array array, int index)
{
Array.Copy(data, 0, array, index, Count);
}
public int Count { get; private set; }
public bool IsSynchronized => false;
public object SyncRoot => data;
public IEnumerator GetEnumerator()
{
for (var i = 0; i < Count; ++i)
{
yield return data[i];
}
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 20118ab09905856488b432270429ae5b
timeCreated: 1427145263
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,111 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class CollectionNodeDeserializer : INodeDeserializer
{
private readonly IObjectFactory objectFactory;
public CollectionNodeDeserializer(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory ?? throw new ArgumentNullException(nameof(objectFactory));
}
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
IList? list;
var canUpdate = true;
Type itemType;
var genericCollectionType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>));
if (genericCollectionType != null)
{
var genericArguments = genericCollectionType.GetGenericArguments();
itemType = genericArguments[0];
value = objectFactory.Create(expectedType);
list = value as IList;
if (list == null)
{
// Uncommon case where a type implements IList<T> but not IList
var genericListType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>));
canUpdate = genericListType != null;
list = (IList?)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(itemType), value);
}
}
else if (typeof(IList).IsAssignableFrom(expectedType))
{
itemType = typeof(object);
value = objectFactory.Create(expectedType);
list = (IList)value;
}
else
{
value = null;
return false;
}
DeserializeHelper(itemType, parser, nestedObjectDeserializer, list!, canUpdate);
return true;
}
internal static void DeserializeHelper(Type tItem, IParser parser, Func<IParser, Type, object?> nestedObjectDeserializer, IList result, bool canUpdate)
{
parser.Consume<SequenceStart>();
while (!parser.TryConsume<SequenceEnd>(out var _))
{
var current = parser.Current;
var value = nestedObjectDeserializer(parser, tItem);
if (value is IValuePromise promise)
{
if (canUpdate)
{
var index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null);
promise.ValueAvailable += v => result[index] = TypeConverter.ChangeType(v, tItem);
}
else
{
throw new ForwardAnchorNotSupportedException(
current?.Start ?? Mark.Empty,
current?.End ?? Mark.Empty,
"Forward alias references are not allowed because this type does not implement IList<>"
);
}
}
else
{
result.Add(TypeConverter.ChangeType(value, tItem));
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a3d1d09d7ca82fa46841cf8b486dc14e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,144 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class DictionaryNodeDeserializer : INodeDeserializer
{
private readonly IObjectFactory objectFactory;
public DictionaryNodeDeserializer(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory ?? throw new ArgumentNullException(nameof(objectFactory));
}
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
IDictionary? dictionary;
Type keyType, valueType;
var genericDictionaryType = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<,>));
if (genericDictionaryType != null)
{
var genericArguments = genericDictionaryType.GetGenericArguments();
keyType = genericArguments[0];
valueType = genericArguments[1];
value = objectFactory.Create(expectedType);
dictionary = value as IDictionary;
if (dictionary == null)
{
// Uncommon case where a type implements IDictionary<TKey, TValue> but not IDictionary
dictionary = (IDictionary?)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<,>).MakeGenericType(keyType, valueType), value);
}
}
else if (typeof(IDictionary).IsAssignableFrom(expectedType))
{
keyType = typeof(object);
valueType = typeof(object);
value = objectFactory.Create(expectedType);
dictionary = (IDictionary)value;
}
else
{
value = null;
return false;
}
DeserializeHelper(keyType, valueType, parser, nestedObjectDeserializer, dictionary!);
return true;
}
private static void DeserializeHelper(Type tKey, Type tValue, IParser parser, Func<IParser, Type, object?> nestedObjectDeserializer, IDictionary result)
{
parser.Consume<MappingStart>();
while (!parser.TryConsume<MappingEnd>(out var _))
{
var key = nestedObjectDeserializer(parser, tKey);
var value = nestedObjectDeserializer(parser, tValue);
var valuePromise = value as IValuePromise;
if (key is IValuePromise keyPromise)
{
if (valuePromise == null)
{
// Key is pending, value is known
keyPromise.ValueAvailable += v => result[v!] = value!;
}
else
{
// Both key and value are pending. We need to wait until both of them become available.
var hasFirstPart = false;
keyPromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
result[v!] = value!;
}
else
{
key = v!;
hasFirstPart = true;
}
};
valuePromise.ValueAvailable += v =>
{
if (hasFirstPart)
{
result[key] = v!;
}
else
{
value = v;
hasFirstPart = true;
}
};
}
}
else
{
if (valuePromise == null)
{
// Happy path: both key and value are known
result[key!] = value!;
}
else
{
// Key is known, value is pending
valuePromise.ValueAvailable += v => result[key!] = v!;
}
}
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0fe68add59e580848b7d981ac8f2f0a1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,57 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections;
using System.Collections.Generic;
using YamlDotNet.Core;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class EnumerableNodeDeserializer : INodeDeserializer
{
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
Type itemsType;
if (expectedType == typeof(IEnumerable))
{
itemsType = typeof(object);
}
else
{
var iEnumerable = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>));
if (iEnumerable != expectedType)
{
value = null;
return false;
}
itemsType = iEnumerable.GetGenericArguments()[0];
}
var collectionType = typeof(List<>).MakeGenericType(itemsType);
value = nestedObjectDeserializer(parser, collectionType);
return true;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4b63af2cc4a9f5d4cbbadbdac863e5df
timeCreated: 1427145264
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,63 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class NullNodeDeserializer : INodeDeserializer
{
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
value = null;
if (parser.Accept<NodeEvent>(out var evt))
{
if (NodeIsNull(evt))
{
parser.SkipThisAndNestedEvents();
return true;
}
}
return false;
}
private bool NodeIsNull(NodeEvent nodeEvent)
{
// http://yaml.org/type/null.html
if (nodeEvent.Tag == "tag:yaml.org,2002:null")
{
return true;
}
if (nodeEvent is Scalar scalar && scalar.Style == Core.ScalarStyle.Plain)
{
var value = scalar.Value;
return value == "" || value == "~" || value == "null" || value == "Null" || value == "NULL";
}
return false;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 2dc4eb3386e00254a90e737f7663d298
timeCreated: 1427145263
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,100 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Runtime.Serialization;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class ObjectNodeDeserializer : INodeDeserializer
{
private readonly IObjectFactory objectFactory;
private readonly ITypeInspector typeDescriptor;
private readonly bool ignoreUnmatched;
public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched)
{
this.objectFactory = objectFactory ?? throw new ArgumentNullException(nameof(objectFactory));
this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException(nameof(typeDescriptor));
this.ignoreUnmatched = ignoreUnmatched;
}
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
if (!parser.TryConsume<MappingStart>(out var mapping))
{
value = null;
return false;
}
// Strip off the nullable type, if present. This is needed for nullable structs.
var implementationType = Nullable.GetUnderlyingType(expectedType) ?? expectedType;
value = objectFactory.Create(implementationType);
while (!parser.TryConsume<MappingEnd>(out var _))
{
var propertyName = parser.Consume<Scalar>();
try
{
var property = typeDescriptor.GetProperty(implementationType, null, propertyName.Value, ignoreUnmatched);
if (property == null)
{
parser.SkipThisAndNestedEvents();
continue;
}
var propertyValue = nestedObjectDeserializer(parser, property.Type);
if (propertyValue is IValuePromise propertyValuePromise)
{
var valueRef = value;
propertyValuePromise.ValueAvailable += v =>
{
var convertedValue = TypeConverter.ChangeType(v, property.Type);
property.Write(valueRef, convertedValue);
};
}
else
{
var convertedValue = TypeConverter.ChangeType(propertyValue, property.Type);
property.Write(value, convertedValue);
}
}
catch (SerializationException ex)
{
throw new YamlException(propertyName.Start, propertyName.End, ex.Message);
}
catch (YamlException)
{
throw;
}
catch (Exception ex)
{
throw new YamlException(propertyName.Start, propertyName.End, "Exception during deserialization", ex);
}
}
return true;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 203cafd2ca433854ab6bb7dcc51b861a
timeCreated: 1427145263
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,282 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization.Utilities;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class ScalarNodeDeserializer : INodeDeserializer
{
private const string BooleanTruePattern = "^(true|y|yes|on)$";
private const string BooleanFalsePattern = "^(false|n|no|off)$";
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
if (!parser.TryConsume<Scalar>(out var scalar))
{
value = null;
return false;
}
// Strip off the nullable type, if present
var underlyingType = Nullable.GetUnderlyingType(expectedType) ?? expectedType;
if (underlyingType.IsEnum())
{
value = Enum.Parse(underlyingType, scalar.Value, true);
return true;
}
var typeCode = underlyingType.GetTypeCode();
switch (typeCode)
{
case TypeCode.Boolean:
value = DeserializeBooleanHelper(scalar.Value);
break;
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.SByte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
value = DeserializeIntegerHelper(typeCode, scalar.Value);
break;
case TypeCode.Single:
value = float.Parse(scalar.Value, YamlFormatter.NumberFormat);
break;
case TypeCode.Double:
value = double.Parse(scalar.Value, YamlFormatter.NumberFormat);
break;
case TypeCode.Decimal:
value = decimal.Parse(scalar.Value, YamlFormatter.NumberFormat);
break;
case TypeCode.String:
value = scalar.Value;
break;
case TypeCode.Char:
value = scalar.Value[0];
break;
case TypeCode.DateTime:
// TODO: This is probably incorrect. Use the correct regular expression.
value = DateTime.Parse(scalar.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
break;
default:
if (expectedType == typeof(object))
{
// Default to string
value = scalar.Value;
}
else
{
value = TypeConverter.ChangeType(scalar.Value, expectedType);
}
break;
}
return true;
}
private object DeserializeBooleanHelper(string value)
{
bool result;
if (Regex.IsMatch(value, BooleanTruePattern, RegexOptions.IgnoreCase))
{
result = true;
}
else if (Regex.IsMatch(value, BooleanFalsePattern, RegexOptions.IgnoreCase))
{
result = false;
}
else
{
throw new FormatException($"The value \"{value}\" is not a valid YAML Boolean");
}
return result;
}
private object DeserializeIntegerHelper(TypeCode typeCode, string value)
{
var numberBuilder = new StringBuilder();
var currentIndex = 0;
var isNegative = false;
int numberBase;
ulong result = 0;
if (value[0] == '-')
{
currentIndex++;
isNegative = true;
}
else if (value[0] == '+')
{
currentIndex++;
}
if (value[currentIndex] == '0')
{
// Could be binary, octal, hex, decimal (0)
// If there are no characters remaining, it's a decimal zero
if (currentIndex == value.Length - 1)
{
numberBase = 10;
result = 0;
}
else
{
// Check the next character
currentIndex++;
if (value[currentIndex] == 'b')
{
// Binary
numberBase = 2;
currentIndex++;
}
else if (value[currentIndex] == 'x')
{
// Hex
numberBase = 16;
currentIndex++;
}
else
{
// Octal
numberBase = 8;
}
}
// Copy remaining digits to the number buffer (skip underscores)
while (currentIndex < value.Length)
{
if (value[currentIndex] != '_')
{
numberBuilder.Append(value[currentIndex]);
}
currentIndex++;
}
// Parse the magnitude of the number
switch (numberBase)
{
case 2:
case 8:
// TODO: how to incorporate the numberFormat?
result = Convert.ToUInt64(numberBuilder.ToString(), numberBase);
break;
case 16:
result = ulong.Parse(numberBuilder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat);
break;
case 10:
// Result is already zero
break;
}
}
else
{
// Could be decimal or base 60
var chunks = value.Substring(currentIndex).Split(':');
result = 0;
for (var chunkIndex = 0; chunkIndex < chunks.Length; chunkIndex++)
{
result *= 60;
// TODO: verify that chunks after the first are non-negative and less than 60
result += ulong.Parse(chunks[chunkIndex].Replace("_", ""));
}
}
if (isNegative)
{
return CastInteger(checked(-(long)result), typeCode);
}
else
{
return CastInteger(result, typeCode);
}
}
private static object CastInteger(long number, TypeCode typeCode)
{
checked
{
return typeCode switch
{
TypeCode.Byte => (byte)number,
TypeCode.Int16 => (short)number,
TypeCode.Int32 => (int)number,
TypeCode.Int64 => number,
TypeCode.SByte => (sbyte)number,
TypeCode.UInt16 => (ushort)number,
TypeCode.UInt32 => (uint)number,
TypeCode.UInt64 => (ulong)number,
_ => number,
};
}
}
private static object CastInteger(ulong number, TypeCode typeCode)
{
checked
{
return typeCode switch
{
TypeCode.Byte => (byte)number,
TypeCode.Int16 => (short)number,
TypeCode.Int32 => (int)number,
TypeCode.Int64 => (long)number,
TypeCode.SByte => (sbyte)number,
TypeCode.UInt16 => (ushort)number,
TypeCode.UInt32 => (uint)number,
TypeCode.UInt64 => number,
_ => number,
};
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: acae7a1311005a143be6454d8b86b947
timeCreated: 1427145265
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using YamlDotNet.Core;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class TypeConverterNodeDeserializer : INodeDeserializer
{
private readonly IEnumerable<IYamlTypeConverter> converters;
public TypeConverterNodeDeserializer(IEnumerable<IYamlTypeConverter> converters)
{
this.converters = converters ?? throw new ArgumentNullException(nameof(converters));
}
bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
var converter = converters.FirstOrDefault(c => c.Accepts(expectedType));
if (converter == null)
{
value = null;
return false;
}
value = converter.ReadYaml(parser, expectedType);
return true;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a4dc6d0569fe722448b3d925a66e2b45
timeCreated: 1427145265
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,50 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using YamlDotNet.Core;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class YamlConvertibleNodeDeserializer : INodeDeserializer
{
private readonly IObjectFactory objectFactory;
public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory;
}
public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
if (typeof(IYamlConvertible).IsAssignableFrom(expectedType))
{
var convertible = (IYamlConvertible)objectFactory.Create(expectedType);
convertible.Read(parser, expectedType, type => nestedObjectDeserializer(parser, type));
value = convertible;
return true;
}
value = null;
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 994740f2670b0744e892638b88feb9f0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using YamlDotNet.Core;
namespace YamlDotNet.Serialization.NodeDeserializers
{
public sealed class YamlSerializableNodeDeserializer : INodeDeserializer
{
private readonly IObjectFactory objectFactory;
public YamlSerializableNodeDeserializer(IObjectFactory objectFactory)
{
this.objectFactory = objectFactory;
}
public bool Deserialize(IParser parser, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value)
{
#pragma warning disable 0618 // IYamlSerializable is obsolete
if (typeof(IYamlSerializable).IsAssignableFrom(expectedType))
{
var serializable = (IYamlSerializable)objectFactory.Create(expectedType);
serializable.ReadYaml(parser);
value = serializable;
return true;
}
#pragma warning restore
value = null;
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 997309be5330da04d9bc939aad61f6e2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: