Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions YamlDotNet.Test/Serialization/GenericTestReadOnlyDictionary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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.Collections;
using System.Collections.Generic;

namespace YamlDotNet.Test.Serialization
{
/// <summary>
/// Test Dictionary that implements <see cref="IReadOnlyDictionary{TKey, TValue}" />, but not
/// <see cref="IDictionary{TKey, TValue}"/> nor <see cref="IDictionary"/>.
/// </summary>
public class GenericTestReadOnlyDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>
{
private readonly Dictionary<TKey, TValue> dictionary;

public GenericTestReadOnlyDictionary()
{
dictionary = new Dictionary<TKey, TValue>();
}

public void Add(TKey key, TValue value)
{
dictionary.Add(key, value);
}

public TValue this[TKey key]
{
get { return dictionary[key]; }
}

public IEnumerable<TKey> Keys
{
get { return dictionary.Keys; }
}

public IEnumerable<TValue> Values
{
get { return dictionary.Values; }
}

public int Count
{
get { return dictionary.Count; }
}

public bool ContainsKey(TKey key)
{
return dictionary.ContainsKey(key);
}

public bool TryGetValue(TKey key, out TValue value)
{
return dictionary.TryGetValue(key, out value);
}

public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return dictionary.GetEnumerator();
}

IEnumerator IEnumerable.GetEnumerator()
{
return dictionary.GetEnumerator();
}
}
}
23 changes: 23 additions & 0 deletions YamlDotNet.Test/Serialization/SerializationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1577,6 +1577,29 @@ public void SerializeGenericDictionaryPropertyAndDoNotApplyNamingConvention()
writer.ToString().Should().Contain("new_key_here: new_value");
}

[Fact]
public void SerializeGenericReadOnlyDictionary()
{
// A type that implements only IReadOnlyDictionary<,> must serialize as a
// mapping, the same as a regular dictionary, rather than as a sequence of
// key/value pairs. See https://github.com/aaubry/YamlDotNet/issues/606.
var readOnlyDictionary = new GenericTestReadOnlyDictionary<string, string>();
readOnlyDictionary.Add("key1", "value1");
readOnlyDictionary.Add("key2", "value2");

var serializer = new SerializerBuilder().Build();

var actual = serializer.Serialize(readOnlyDictionary);
var expected = serializer.Serialize(
new Dictionary<string, string>
{
["key1"] = "value1",
["key2"] = "value2",
});

actual.Should().Be(expected);
}

[Theory, MemberData(nameof(SpecialFloats))]
public void SpecialFloatsAreHandledCorrectly(FloatTestCase testCase)
{
Expand Down
168 changes: 168 additions & 0 deletions YamlDotNet/Helpers/GenericReadOnlyDictionaryToNonGenericAdapter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// 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;

namespace YamlDotNet.Helpers
{
/// <summary>
/// Adapts an <see cref="System.Collections.Generic.IReadOnlyDictionary{TKey, TValue}" /> to <see cref="IDictionary" />
/// so that types which implement only the read-only interface are still traversed as mappings.
/// Only enumeration is supported, which is all that object graph traversal requires.
/// </summary>
internal sealed class GenericReadOnlyDictionaryToNonGenericAdapter<TKey, TValue> : IDictionary
where TKey : notnull
{
private readonly IReadOnlyDictionary<TKey, TValue> genericDictionary;

public GenericReadOnlyDictionaryToNonGenericAdapter(IReadOnlyDictionary<TKey, TValue> genericDictionary)
{
this.genericDictionary = genericDictionary ?? throw new ArgumentNullException(nameof(genericDictionary));
}

public void Add(object key, object? value)
{
throw new NotSupportedException();
}

public void Clear()
{
throw new NotSupportedException();
}

public bool Contains(object key)
{
throw new NotSupportedException();
}

public IDictionaryEnumerator GetEnumerator()
{
return new DictionaryEnumerator(genericDictionary.GetEnumerator());
}

public bool IsFixedSize
{
get { throw new NotSupportedException(); }
}

public bool IsReadOnly
{
get { throw new NotSupportedException(); }
}

public ICollection Keys
{
get { throw new NotSupportedException(); }
}

public void Remove(object key)
{
throw new NotSupportedException();
}

public ICollection Values
{
get { throw new NotSupportedException(); }
}

public object? this[object key]
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}

public void CopyTo(Array array, int index)
{
throw new NotSupportedException();
}

public int Count
{
get { throw new NotSupportedException(); }
}

public bool IsSynchronized
{
get { throw new NotSupportedException(); }
}

public object SyncRoot
{
get { throw new NotSupportedException(); }
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}

private class DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IEnumerator<KeyValuePair<TKey, TValue>> enumerator;

public DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> enumerator)
{
this.enumerator = enumerator;
}

public DictionaryEntry Entry
{
get
{
return new DictionaryEntry(Key, Value);
}
}

public object Key
{
get { return enumerator.Current.Key!; }
}

public object? Value
{
get { return enumerator.Current.Value; }
}

public object Current
{
get { return Entry; }
}

public bool MoveNext()
{
return enumerator.MoveNext();
}

public void Reset()
{
enumerator.Reset();
}
}
}
}
10 changes: 10 additions & 0 deletions YamlDotNet/Serialization/ObjectFactories/ObjectFactoryBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,16 @@ public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary?
dictionary = adaptedDictionary as IDictionary;
return true;
}

var genericReadOnlyDictionaryType = descriptor.Type.GetImplementationOfOpenGenericInterface(typeof(IReadOnlyDictionary<,>));
if (genericReadOnlyDictionaryType != null)
{
genericArguments = genericReadOnlyDictionaryType.GetGenericArguments();
var adaptedDictionary = Activator.CreateInstance(typeof(GenericReadOnlyDictionaryToNonGenericAdapter<,>).MakeGenericType(genericArguments), descriptor.Value)!;
dictionary = adaptedDictionary as IDictionary;
return true;
}

genericArguments = null;
dictionary = null;
return false;
Expand Down