Skip to content

Commit

Permalink
Add DefaultDictionaryAdapter
Browse files Browse the repository at this point in the history
  • Loading branch information
FabianTerhorst committed Jun 20, 2019
1 parent 07c0c23 commit 9ca9ba7
Showing 1 changed file with 59 additions and 1 deletion.
60 changes: 59 additions & 1 deletion api/AltV.Net/Elements/Args/DefaultMValueAdapters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ namespace AltV.Net.Elements.Args
{
public static class DefaultMValueAdapters
{
//TODO: create DefaultDictionaryAdapter
public class DefaultArrayAdapter<T> : IMValueAdapter<List<T>>
{
private readonly IMValueAdapter<T> elementAdapter;
Expand Down Expand Up @@ -57,9 +56,68 @@ public void ToMValue(object obj, IMValueWriter writer)
}
}

public class DefaultDictionaryAdapter<T> : IMValueAdapter<IDictionary<string, T>>
{
private readonly IMValueAdapter<T> elementAdapter;

public DefaultDictionaryAdapter(IMValueAdapter<T> elementAdapter)
{
this.elementAdapter = elementAdapter;
}

public IDictionary<string, T> FromMValue(IMValueReader reader)
{
var dictionary = new Dictionary<string, T>();
reader.BeginObject();
while (reader.HasNext())
{
var key = reader.NextName();
dictionary[key] = elementAdapter.FromMValue(reader);
}

reader.EndObject();
return dictionary;
}

public void ToMValue(IDictionary<string, T> dictionary, IMValueWriter writer)
{
writer.BeginObject();
foreach (var (key, value) in dictionary)
{
writer.Name(key);
elementAdapter.ToMValue(value, writer);
}

writer.EndObject();
}

object IMValueBaseAdapter.FromMValue(IMValueReader reader)
{
return FromMValue(reader);
}

public void ToMValue(object obj, IMValueWriter writer)
{
if (obj is IDictionary<string, T> list)
{
ToMValue(list, writer);
}
else
{
writer.BeginObject();
writer.EndObject();
}
}
}

public static IMValueAdapter<List<T>> GetArrayAdapter<T>(IMValueAdapter<T> elementAdapter)
{
return new DefaultArrayAdapter<T>(elementAdapter);
}

public static IMValueAdapter<IDictionary<string, T>> GetDictionaryAdapter<T>(IMValueAdapter<T> elementAdapter)
{
return new DefaultDictionaryAdapter<T>(elementAdapter);
}
}
}

0 comments on commit 9ca9ba7

Please sign in to comment.