Skip to content

Commit

Permalink
Merge pull request #204 from atifaziz/rm/PyKeyValuePairEnumerable
Browse files Browse the repository at this point in the history
Reuse `PyEnumerable`, removing need for `PyKeyValuePairEnumerable`
  • Loading branch information
tonybaloney authored Sep 17, 2024
2 parents b6d08c2 + c03cd1b commit 6379c99
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 54 deletions.
2 changes: 1 addition & 1 deletion src/CSnakes.Runtime/Python/PyDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
using (GIL.Acquire())
{
using var items = PyObject.Create(CPythonAPI.PyMapping_Items(_dictionaryObject));
return new PyKeyValuePairEnumerable<TKey, TValue>(items).GetEnumerator();
return new PyEnumerable<KeyValuePair<TKey, TValue>, PyObjectImporter<TKey, TValue>>(items).GetEnumerator();
}
}

Expand Down
10 changes: 8 additions & 2 deletions src/CSnakes.Runtime/Python/PyEnumerable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@

namespace CSnakes.Runtime.Python;

internal class PyEnumerable<TValue> : IEnumerable<TValue>, IEnumerator<TValue>, IDisposable
internal class PyEnumerable<TValue, TImporter> : IEnumerable<TValue>, IEnumerator<TValue>, IDisposable
where TImporter : IPyObjectImporter<TValue>
{
private readonly PyObject _pyIterator;
private TValue current = default!;
Expand Down Expand Up @@ -40,7 +41,7 @@ public bool MoveNext()
}

using PyObject pyObject = PyObject.Create(result);
current = pyObject.As<TValue>();
current = TImporter.Import(pyObject);
return true;
}
}
Expand All @@ -49,3 +50,8 @@ public bool MoveNext()

IEnumerator IEnumerable.GetEnumerator() => this;
}

internal class PyEnumerable<TValue> : PyEnumerable<TValue, PyObjectImporter<TValue>>
{
internal PyEnumerable(PyObject pyObject) : base(pyObject) { }
}
51 changes: 0 additions & 51 deletions src/CSnakes.Runtime/Python/PyKeyValuePairEnumerable.cs

This file was deleted.

22 changes: 22 additions & 0 deletions src/CSnakes.Runtime/Python/PyObjectImporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
using CSnakes.Runtime.Python;

internal interface IPyObjectImporter<out T>
{
static abstract T Import(PyObject pyObj);
}

internal sealed class PyObjectImporter<T> :
IPyObjectImporter<T>
{
private PyObjectImporter() { }

public static T Import(PyObject pyObj) => pyObj.As<T>();
}

internal sealed class PyObjectImporter<TKey, TValue> :
IPyObjectImporter<KeyValuePair<TKey, TValue>>
{
private PyObjectImporter() { }

public static KeyValuePair<TKey, TValue> Import(PyObject pyObj) => pyObj.As<TKey, TValue>();
}

0 comments on commit 6379c99

Please sign in to comment.