-
Notifications
You must be signed in to change notification settings - Fork 774
Expand file tree
/
Copy pathMpLengthSlot.cs
More file actions
68 lines (61 loc) · 2.32 KB
/
MpLengthSlot.cs
File metadata and controls
68 lines (61 loc) · 2.32 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace Python.Runtime.Slots
{
internal static class MpLengthSlot
{
public static bool CanAssign(Type clrType)
{
if (typeof(ICollection).IsAssignableFrom(clrType))
{
return true;
}
if (clrType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)))
{
return true;
}
if (clrType.IsInterface && clrType.IsGenericType && clrType.GetGenericTypeDefinition() == typeof(ICollection<>))
{
return true;
}
return false;
}
/// <summary>
/// Implements __len__ for classes that implement ICollection
/// (this includes any IList implementer or Array subclass)
/// </summary>
internal static nint impl(BorrowedReference ob)
{
if (ManagedType.GetManagedObject(ob) is not CLRObject co)
{
Exceptions.RaiseTypeError("invalid object");
return -1;
}
// first look for ICollection implementation directly
if (co.inst is ICollection c)
{
return c.Count;
}
Type clrType = co.inst.GetType();
// now look for things that implement ICollection<T> directly (non-explicitly)
PropertyInfo p = clrType.GetProperty("Count");
if (p != null && clrType.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>)))
{
return (int)p.GetValue(co.inst, null);
}
// finally look for things that implement the interface explicitly
var iface = clrType.GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(ICollection<>));
if (iface != null)
{
p = iface.GetProperty(nameof(ICollection<int>.Count));
return (int)p.GetValue(co.inst, null);
}
Exceptions.SetError(Exceptions.TypeError, $"object of type '{clrType.Name}' has no len()");
return -1;
}
}
}