-
Notifications
You must be signed in to change notification settings - Fork 774
Expand file tree
/
Copy pathListDecoder.cs
More file actions
50 lines (40 loc) · 1.61 KB
/
ListDecoder.cs
File metadata and controls
50 lines (40 loc) · 1.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
namespace Python.Runtime.Codecs
{
public class ListDecoder : IPyObjectDecoder
{
private static bool IsList(Type targetType)
{
if (!targetType.IsGenericType)
return false;
return targetType.GetGenericTypeDefinition() == typeof(IList<>);
}
private static bool IsList(PyType objectType)
{
//TODO accept any python object that implements the sequence and list protocols
//must implement sequence protocol to fully implement list protocol
//if (!SequenceDecoder.IsSequence(objectType)) return false;
//returns wheter the type is a list.
return PythonReferenceComparer.Instance.Equals(objectType, Runtime.PyListType);
}
public bool CanDecode(PyType objectType, Type targetType)
{
return IsList(objectType) && IsList(targetType);
}
public bool TryDecode<T>(PyObject pyObj, out T value)
{
if (pyObj == null) throw new ArgumentNullException(nameof(pyObj));
var elementType = typeof(T).GetGenericArguments()[0];
Type collectionType = typeof(CollectionWrappers.ListWrapper<>).MakeGenericType(elementType);
var instance = Activator.CreateInstance(collectionType, new[] { pyObj });
value = (T)instance;
return true;
}
public static ListDecoder Instance { get; } = new ListDecoder();
public static void Register()
{
PyObjectConversions.RegisterDecoder(Instance);
}
}
}