forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayOps.cs
More file actions
368 lines (293 loc) · 14.1 KB
/
ArrayOps.cs
File metadata and controls
368 lines (293 loc) · 14.1 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using System.Text;
using IronPython.Runtime.Types;
using SpecialNameAttribute = System.Runtime.CompilerServices.SpecialNameAttribute;
namespace IronPython.Runtime.Operations {
public static class ArrayOps {
#region Python APIs
[SpecialName]
public static Array Add(Array data1, Array data2) {
if (data1 == null) throw PythonOps.TypeError("expected array for 1st argument, got None");
if (data2 == null) throw PythonOps.TypeError("expected array for 2nd argument, got None");
if (data1.Rank > 1 || data2.Rank > 1) throw new NotImplementedException("can't add multidimensional arrays");
Type type1 = data1.GetType();
Type type2 = data2.GetType();
Type type = (type1 == type2) ? type1.GetElementType() : typeof(object);
Array ret = Array.CreateInstance(type, data1.Length + data2.Length);
Array.Copy(data1, 0, ret, 0, data1.Length);
Array.Copy(data2, 0, ret, data1.Length, data2.Length);
return ret;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, ICollection items) {
Type type = pythonType.UnderlyingSystemType.GetElementType();
Array res = Array.CreateInstance(type, items.Count);
int i = 0;
foreach (object item in items) {
res.SetValue(Converter.Convert(item, type), i++);
}
return res;
}
[StaticExtensionMethod]
public static object __new__(CodeContext context, PythonType pythonType, object items) {
Type type = pythonType.UnderlyingSystemType.GetElementType();
object lenFunc;
if (!PythonOps.TryGetBoundAttr(items, "__len__", out lenFunc))
throw PythonOps.TypeErrorForBadInstance("expected object with __len__ function, got {0}", items);
int len = context.LanguageContext.ConvertToInt32(PythonOps.CallWithContext(context, lenFunc));
Array res = Array.CreateInstance(type, len);
IEnumerator ie = PythonOps.GetEnumerator(items);
int i = 0;
while (ie.MoveNext()) {
res.SetValue(Converter.Convert(ie.Current, type), i++);
}
return res;
}
/// <summary>
/// Multiply two object[] arrays - slow version, we need to get the type, etc...
/// </summary>
[SpecialName]
public static Array Multiply(Array data, int count) {
if (data.Rank > 1) throw new NotImplementedException("can't multiply multidimensional arrays");
Type elemType = data.GetType().GetElementType();
if (count <= 0) return Array.CreateInstance(elemType, 0);
int newCount = data.Length * count;
Array ret = Array.CreateInstance(elemType, newCount);
Array.Copy(data, 0, ret, 0, data.Length);
// this should be extremely fast for large count as it uses the same algoithim as efficient integer powers
// ??? need to test to see how large count and n need to be for this to be fastest approach
int block = data.Length;
int pos = data.Length;
while (pos < newCount) {
Array.Copy(ret, 0, ret, pos, Math.Min(block, newCount - pos));
pos += block;
block *= 2;
}
return ret;
}
[SpecialName]
public static object GetItem(Array data, int index) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
return data.GetValue(PythonOps.FixIndex(index, data.Length) + data.GetLowerBound(0));
}
[SpecialName]
public static object GetItem(Array data, Slice slice) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
return GetSlice(data, data.Length, slice);
}
[SpecialName]
public static object GetItem(Array data, PythonTuple tuple) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
return GetItem(data, tuple.ToArray());
}
[SpecialName]
public static object GetItem(Array data, params object[] indices) {
if (indices == null || indices.Length < 1) throw PythonOps.TypeError("__getitem__ requires at least 1 parameter");
int iindex;
if (indices.Length == 1 && Converter.TryConvertToInt32(indices[0], out iindex)) {
return GetItem(data, iindex);
}
Type t = data.GetType();
Debug.Assert(t.HasElementType);
int[] iindices = TupleToIndices(data, indices);
if (data.Rank != indices.Length) throw PythonOps.ValueError("bad dimensions for array, got {0} expected {1}", indices.Length, data.Rank);
for (int i = 0; i < iindices.Length; i++) iindices[i] += data.GetLowerBound(i);
return data.GetValue(iindices);
}
[SpecialName]
public static void SetItem(Array data, int index, object value) {
if (data == null) throw PythonOps.TypeError("expected Array, got None");
data.SetValue(Converter.Convert(value, data.GetType().GetElementType()), PythonOps.FixIndex(index, data.Length) + data.GetLowerBound(0));
}
[SpecialName]
public static void SetItem(Array a, params object[] indexAndValue) {
if (indexAndValue == null || indexAndValue.Length < 2) throw PythonOps.TypeError("__setitem__ requires at least 2 parameters");
int iindex;
if (indexAndValue.Length == 2 && Converter.TryConvertToInt32(indexAndValue[0], out iindex)) {
SetItem(a, iindex, indexAndValue[1]);
return;
}
Type t = a.GetType();
Debug.Assert(t.HasElementType);
object[] args = ArrayUtils.RemoveLast(indexAndValue);
int[] indices = TupleToIndices(a, args);
if (a.Rank != args.Length) throw PythonOps.ValueError("bad dimensions for array, got {0} expected {1}", args.Length, a.Rank);
for (int i = 0; i < indices.Length; i++) indices[i] += a.GetLowerBound(i);
a.SetValue(indexAndValue[indexAndValue.Length - 1], indices);
}
[SpecialName]
public static void SetItem(Array a, Slice index, object value) {
if (a.Rank != 1) throw PythonOps.NotImplementedError("slice on multi-dimensional array");
Type elm = a.GetType().GetElementType();
index.DoSliceAssign(
delegate(int idx, object val) {
a.SetValue(Converter.Convert(val, elm), idx + a.GetLowerBound(0));
},
a.Length,
value);
}
public static string __repr__(CodeContext/*!*/ context, [NotNull]Array/*!*/ self) {
List<object> infinite = PythonOps.GetAndCheckInfinite(self);
if (infinite == null) {
return "...";
}
int index = infinite.Count;
infinite.Add(self);
try {
StringBuilder ret = new StringBuilder();
if (self.Rank == 1) {
// single dimensional Array's have a valid display
ret.Append("Array[");
Type elemType = self.GetType().GetElementType();
ret.Append(DynamicHelpers.GetPythonTypeFromType(elemType).Name);
ret.Append("]");
ret.Append("((");
for (int i = 0; i < self.Length; i++) {
if (i > 0) ret.Append(", ");
ret.Append(PythonOps.Repr(context, self.GetValue(i + self.GetLowerBound(0))));
}
ret.Append("))");
} else {
// multi dimensional arrays require multiple statements to construct so we just
// give enough info to identify the object and its type.
ret.Append("<");
ret.Append(self.Rank);
ret.Append(" dimensional Array[");
Type elemType = self.GetType().GetElementType();
ret.Append(DynamicHelpers.GetPythonTypeFromType(elemType).Name);
ret.Append("] at ");
ret.Append(PythonOps.HexId(self));
ret.Append(">");
}
return ret.ToString();
} finally {
System.Diagnostics.Debug.Assert(index == infinite.Count - 1);
infinite.RemoveAt(index);
}
}
#endregion
#region Internal APIs
/// <summary>
/// Multiply two object[] arrays - internal version used for objects backed by arrays
/// </summary>
internal static object[] Multiply(object[] data, int size, int count) {
int newCount;
try {
newCount = checked(size * count);
} catch (OverflowException) {
throw PythonOps.MemoryError();
}
object[] ret = ArrayOps.CopyArray(data, newCount);
if (count > 0) {
// this should be extremely fast for large count as it uses the same algoithim as efficient integer powers
// ??? need to test to see how large count and n need to be for this to be fastest approach
int block = size;
int pos = size;
while (pos < newCount) {
Array.Copy(ret, 0, ret, pos, Math.Min(block, newCount - pos));
pos += block;
block *= 2;
}
}
return ret;
}
/// <summary>
/// Add two arrays - internal versions for objects backed by arrays
/// </summary>
/// <param name="data1"></param>
/// <param name="size1"></param>
/// <param name="data2"></param>
/// <param name="size2"></param>
/// <returns></returns>
internal static object[] Add(object[] data1, int size1, object[] data2, int size2) {
object[] ret = ArrayOps.CopyArray(data1, size1 + size2);
Array.Copy(data2, 0, ret, size1, size2);
return ret;
}
internal static object[] GetSlice(object[] data, int start, int stop) {
if (stop <= start) return ArrayUtils.EmptyObjects;
object[] ret = new object[stop - start];
int index = 0;
for (int i = start; i < stop; i++) {
ret[index++] = data[i];
}
return ret;
}
internal static object[] GetSlice(object[] data, int start, int stop, int step) {
Debug.Assert(step != 0);
if (step == 1) {
return GetSlice(data, start, stop);
}
int size = GetSliceSize(start, stop, step);
if (size <= 0) return ArrayUtils.EmptyObjects;
object[] res = new object[size];
for (int i = 0, index = start; i < res.Length; i++, index += step) {
res[i] = data[index];
}
return res;
}
internal static object[] GetSlice(object[] data, Slice slice) {
int start, stop, step;
slice.indices(data.Length, out start, out stop, out step);
return GetSlice(data, start, stop, step);
}
internal static Array GetSlice(Array data, int size, Slice slice) {
if (data.Rank != 1) throw PythonOps.NotImplementedError("slice on multi-dimensional array");
int start, stop, step;
slice.indices(size, out start, out stop, out step);
if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
if (data.GetType().GetElementType() == typeof(object))
return ArrayUtils.EmptyObjects;
return Array.CreateInstance(data.GetType().GetElementType(), 0);
}
if (step == 1) {
int n = stop - start;
Array ret = Array.CreateInstance(data.GetType().GetElementType(), n);
Array.Copy(data, start + data.GetLowerBound(0), ret, 0, n);
return ret;
} else {
int n = GetSliceSize(start, stop, step);
Array ret = Array.CreateInstance(data.GetType().GetElementType(), n);
int ri = 0;
for (int i = 0, index = start; i < n; i++, index += step) {
ret.SetValue(data.GetValue(index + data.GetLowerBound(0)), ri++);
}
return ret;
}
}
private static int GetSliceSize(int start, int stop, int step) {
// could cause overflow (?)
return step > 0 ? (stop - start + step - 1) / step : (stop - start + step + 1) / step;
}
internal static object[] CopyArray(object[] data, int newSize) {
if (newSize == 0) return ArrayUtils.EmptyObjects;
object[] newData = new object[newSize];
if (data.Length < 20) {
for (int i = 0; i < data.Length && i < newSize; i++) {
newData[i] = data[i];
}
} else {
Array.Copy(data, newData, Math.Min(newSize, data.Length));
}
return newData;
}
#endregion
#region Private helpers
private static int[] TupleToIndices(Array a, IList<object> tuple) {
int[] indices = new int[tuple.Count];
for (int i = 0; i < indices.Length; i++) {
indices[i] = PythonOps.FixIndex(Converter.ConvertToInt32(tuple[i]), a.GetUpperBound(i) + 1);
}
return indices;
}
#endregion
}
}