Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
abandon rank and use three codecs
  • Loading branch information
koubaa committed Feb 16, 2021
commit 224df0ea94e8c081052159106051797e487bef32
579 changes: 334 additions & 245 deletions src/embed_tests/Codecs.cs

Large diffs are not rendered by default.

57 changes: 57 additions & 0 deletions src/runtime/Codecs/IterableDecoder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;

namespace Python.Runtime.Codecs
{
class IterableDecoder : IPyObjectDecoder
{
internal static bool IsIterable(Type targetType)
{
//if it is a plain IEnumerable, we can decode it using sequence protocol.
if (targetType == typeof(System.Collections.IEnumerable))
return true;

if (!targetType.IsGenericType)
return false;

return targetType.GetGenericTypeDefinition() == typeof(IEnumerable<>);
}

internal static bool IsIterable(PyObject objectType)
{
//TODO - do I need to decref iterObject?
IntPtr iterObject = Runtime.PyObject_GetIter(objectType.Handle);
return iterObject != IntPtr.Zero;
}

public bool CanDecode(PyObject objectType, Type targetType)
{
return IsIterable(objectType) && IsIterable(targetType);
}

public bool TryDecode<T>(PyObject pyObj, out T value)
{
//first see if T is a plan IEnumerable
if (typeof(T) == typeof(System.Collections.IEnumerable))
{
object enumerable = new CollectionWrappers.IterableWrapper<object>(pyObj);
value = (T)enumerable;
return true;
}

var elementType = typeof(T).GetGenericArguments()[0];
var collectionType = typeof(CollectionWrappers.IterableWrapper<>).MakeGenericType(elementType);

var instance = Activator.CreateInstance(collectionType, new[] { pyObj });
value = (T)instance;
return true;
}

public static IterableDecoder Instance { get; } = new IterableDecoder();

public static void Register()
{
PyObjectConversions.RegisterDecoder(Instance);
}
}
}
Loading