Repository navigation
Expand file tree
/
Copy pathPythonBuffer.cs
More file actions
407 lines (336 loc) · 12.6 KB
/
Copy pathPythonBuffer.cs
File metadata and controls
407 lines (336 loc) · 12.6 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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if FEATURE_CORE_DLR
using System.Linq.Expressions;
#endif
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Runtime.CompilerServices;
using Microsoft.Scripting.Ast;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
namespace IronPython.Runtime {
[PythonType("buffer"), DontMapGetMemberNamesToDir]
public sealed class PythonBuffer : ICodeFormattable, IDynamicMetaObjectProvider, IList<byte> {
internal object _object;
private int _offset;
private int _size;
private readonly CodeContext/*!*/ _context;
public PythonBuffer(CodeContext/*!*/ context, object @object)
: this(context, @object, 0) {
}
public PythonBuffer(CodeContext/*!*/ context, object @object, int offset)
: this(context, @object, offset, -1) {
}
public PythonBuffer(CodeContext/*!*/ context, object @object, int offset, int size) {
if (!InitBufferObject(@object, offset, size)) {
throw PythonOps.TypeError("expected buffer object");
}
_context = context;
}
private bool InitBufferObject(object o, int offset, int size) {
if (offset < 0) {
throw PythonOps.ValueError("offset must be zero or positive");
} else if (size < -1) {
// -1 is the way to ask for the default size so we allow -1 as a size
throw PythonOps.ValueError("size must be zero or positive");
}
// we currently support only buffers, strings and arrays
// of primitives, strings, bytes, and bytearray objects.
int length;
if (o is PythonBuffer) {
PythonBuffer py = (PythonBuffer)o;
o = py._object; // grab the internal object
length = py._size;
} else if (o is string) {
string strobj = (string)o;
length = strobj.Length;
} else if (o is Bytes) {
length = ((Bytes)o).Count;
} else if (o is ByteArray) {
length = ((ByteArray)o).Count;
} else if (o is Array || o is IPythonArray) {
Array arr = o as Array;
if (arr != null) {
Type t = arr.GetType().GetElementType();
if (!t.IsPrimitive && t != typeof(string)) {
return false;
}
length = arr.Length;
} else {
IPythonArray pa = (IPythonArray)o;
length = pa.Count;
}
} else if (o is IPythonBufferable) {
length = ((IPythonBufferable)o).Size;
_object = o;
} else {
return false;
}
// reset the size based on the given buffer's original size
if (size >= (length - offset) || size == -1) {
_size = length - offset;
} else {
_size = size;
}
_object = o;
_offset = offset;
return true;
}
public override string ToString() {
object res = GetSelectedRange();
if (res is Bytes) {
return PythonOps.MakeString((Bytes)res);
} else if (res is ByteArray) {
return PythonOps.MakeString((ByteArray)res);
} else if (res is IPythonBufferable) {
return PythonOps.MakeString((IList<byte>)GetSelectedRange());
} else if (res is byte[]) {
return ((byte[])GetSelectedRange()).MakeString();
}
return res.ToString();
}
public int __cmp__([NotNull]PythonBuffer other) {
if (Object.ReferenceEquals(this, other)) return 0;
return PythonOps.Compare(ToString(), other.ToString());
}
[PythonHidden]
public override bool Equals(object obj) {
PythonBuffer b = obj as PythonBuffer;
if (b == null) {
return false;
}
return __cmp__(b) == 0;
}
public override int GetHashCode() {
return _object.GetHashCode() ^ _offset ^ (_size << 16 | (_size >> 16));
}
private Slice GetSlice() {
object end = null;
if (_size >= 0) {
end = _offset + _size;
}
return new Slice(_offset, end);
}
public object __getslice__(object start, object stop) {
return this[new Slice(start, stop)];
}
private static Exception ReadOnlyError() {
return PythonOps.TypeError("buffer is read-only");
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public object __setslice__(object start, object stop, object value) {
throw ReadOnlyError();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __delitem__(int index) {
throw ReadOnlyError();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __delslice__(object start, object stop) {
throw ReadOnlyError();
}
public object this[object s] {
[SpecialName]
get {
return PythonOps.GetIndex(_context, GetSelectedRange(), s);
}
[SpecialName]
set {
throw ReadOnlyError();
}
}
private object GetSelectedRange() {
IPythonArray arr = _object as IPythonArray;
if (arr != null) {
return arr.tostring();
}
ByteArray bytearr = _object as ByteArray;
if (bytearr != null) {
return new Bytes((IList<byte>)bytearr[GetSlice()]);
}
IPythonBufferable pyBuf = _object as IPythonBufferable;
if (pyBuf != null) {
return new Bytes(pyBuf.GetBytes(_offset, _size));
}
return PythonOps.GetIndex(_context, _object, GetSlice());
}
public static object operator +(PythonBuffer a, PythonBuffer b) {
PythonContext context = PythonContext.GetContext(a._context);
return context.Operation(
PythonOperationKind.Add,
PythonOps.GetIndex(a._context, a._object, a.GetSlice()),
PythonOps.GetIndex(a._context, b._object, b.GetSlice())
);
}
public static object operator +(PythonBuffer a, string b) {
return a.ToString() + b;
}
public static object operator *(PythonBuffer b, int n) {
PythonContext context = PythonContext.GetContext(b._context);
return context.Operation(
PythonOperationKind.Multiply,
PythonOps.GetIndex(b._context, b._object, b.GetSlice()),
n
);
}
public static object operator *(int n, PythonBuffer b) {
PythonContext context = PythonContext.GetContext(b._context);
return context.Operation(
PythonOperationKind.Multiply,
PythonOps.GetIndex(b._context, b._object, b.GetSlice()),
n
);
}
public int __len__() {
return Math.Max(_size, 0);
}
internal int Size {
get {
return _size;
}
}
#region ICodeFormattable Members
public string/*!*/ __repr__(CodeContext/*!*/ context) {
return string.Format("<read-only buffer for 0x{0:X16}, size {1}, offset {2} at 0x{3:X16}>",
PythonOps.Id(_object), _size, _offset, PythonOps.Id(this));
}
#endregion
/// <summary>
/// A DynamicMetaObject which is just used to support custom conversions to COM.
/// </summary>
class BufferMeta : DynamicMetaObject, IComConvertible {
public BufferMeta(Expression expr, BindingRestrictions restrictions, object value)
: base(expr, restrictions, value) {
}
#region IComConvertible Members
DynamicMetaObject IComConvertible.GetComMetaObject() {
return new DynamicMetaObject(
Expression.Call(
typeof(PythonOps).GetMethod("ConvertBufferToByteArray"),
Utils.Convert(
Expression,
typeof(PythonBuffer)
)
),
BindingRestrictions.Empty
);
}
#endregion
}
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new BufferMeta(parameter, BindingRestrictions.Empty, this);
}
#endregion
#region IList[System.Byte] implementation
byte[] _objectByteCache = null;
internal byte[] byteCache {
get {
return _objectByteCache ?? (_objectByteCache = PythonOps.ConvertBufferToByteArray(this));
}
}
[PythonHidden]
int IList<byte>.IndexOf(byte item) {
for (int i = 0; i < byteCache.Length; ++i) {
if (byteCache[i] == item)
return i;
}
return -1;
}
[PythonHidden]
void IList<byte>.Insert(int index, byte item) {
throw ReadOnlyError();
}
[PythonHidden]
void IList<byte>.RemoveAt(int index) {
throw ReadOnlyError();
}
byte IList<byte>.this[int index] {
[PythonHidden]
get {
return byteCache[index];
}
[PythonHidden]
set {
throw ReadOnlyError();
}
}
#endregion
#region IEnumerable implementation
[PythonHidden]
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
return byteCache.GetEnumerator();
}
#endregion
#region IEnumerable[System.Byte] implementation
[PythonHidden]
IEnumerator<byte> IEnumerable<byte>.GetEnumerator() {
return ((IEnumerable<byte>)byteCache).GetEnumerator();
}
#endregion
#region ICollection[System.Byte] implementation
[PythonHidden]
void ICollection<byte>.Add(byte item) {
throw ReadOnlyError();
}
[PythonHidden]
void ICollection<byte>.Clear() {
throw ReadOnlyError();
}
[PythonHidden]
bool ICollection<byte>.Contains(byte item) {
return ((IList<byte>)this).IndexOf(item) != -1;
}
[PythonHidden]
void ICollection<byte>.CopyTo(byte[] array, int arrayIndex) {
byteCache.CopyTo(array, arrayIndex);
}
[PythonHidden]
bool ICollection<byte>.Remove(byte item) {
throw ReadOnlyError();
}
int ICollection<byte>.Count {
[PythonHidden]
get {
return byteCache.Length;
}
}
bool ICollection<byte>.IsReadOnly {
[PythonHidden]
get {
return true;
}
}
#endregion
}
/// <summary>
/// A marker interface so we can recognize and access sequence members on our array objects.
/// </summary>
internal interface IPythonArray : IList<object> {
string tostring();
}
public interface IPythonBufferable {
IntPtr UnsafeAddress {
get;
}
int Size {
get;
}
byte[] GetBytes(int offset, int length);
}
}