Skip to content

Commit 6cac66f

Browse files
committed
abandon rank and use three codecs
1 parent 01a2076 commit 6cac66f

File tree

8 files changed

+654
-539
lines changed

8 files changed

+654
-539
lines changed

src/embed_tests/Codecs.cs

Lines changed: 283 additions & 197 deletions
Large diffs are not rendered by default.

src/runtime/Codecs/IterableDecoder.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
namespace Python.Runtime.Codecs
5+
{
6+
class IterableDecoder : IPyObjectDecoder
7+
{
8+
internal static bool IsIterable(Type targetType)
9+
{
10+
//if it is a plain IEnumerable, we can decode it using sequence protocol.
11+
if (targetType == typeof(System.Collections.IEnumerable))
12+
return true;
13+
14+
if (!targetType.IsGenericType)
15+
return false;
16+
17+
return targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
18+
}
19+
20+
internal static bool IsIterable(PyObject objectType)
21+
{
22+
//TODO - do I need to decref iterObject?
23+
IntPtr iterObject = Runtime.PyObject_GetIter(objectType.Handle);
24+
return iterObject != IntPtr.Zero;
25+
}
26+
27+
public bool CanDecode(PyObject objectType, Type targetType)
28+
{
29+
return IsIterable(objectType) && IsIterable(targetType);
30+
}
31+
32+
public bool TryDecode<T>(PyObject pyObj, out T value)
33+
{
34+
//first see if T is a plan IEnumerable
35+
if (typeof(T) == typeof(System.Collections.IEnumerable))
36+
{
37+
object enumerable = new CollectionWrappers.IterableWrapper<object>(pyObj);
38+
value = (T)enumerable;
39+
return true;
40+
}
41+
42+
var elementType = typeof(T).GetGenericArguments()[0];
43+
var collectionType = typeof(CollectionWrappers.IterableWrapper<>).MakeGenericType(elementType);
44+
45+
var instance = Activator.CreateInstance(collectionType, new[] { pyObj });
46+
value = (T)instance;
47+
return true;
48+
}
49+
50+
public static IterableDecoder Instance { get; } = new IterableDecoder();
51+
52+
public static void Register()
53+
{
54+
PyObjectConversions.RegisterDecoder(Instance);
55+
}
56+
}
57+
}

0 commit comments

Comments
 (0)