forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_io.cs
More file actions
3183 lines (2643 loc) · 113 KB
/
_io.cs
File metadata and controls
3183 lines (2643 loc) · 113 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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 System.Dynamic;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("_io", typeof(IronPython.Modules.PythonIOModule))]
namespace IronPython.Modules {
public static partial class PythonIOModule {
public const int DEFAULT_BUFFER_SIZE = 8192;
private static readonly object _blockingIOErrorKey = new object();
private static readonly object _unsupportedOperationKey = new object();
private const int O_RDONLY = 0x0000;
private const int O_WRONLY = 0x0001;
private const int O_RDWR = 0x0002;
private const int O_APPEND = 0x0008;
private const int O_CREAT = 0x0100;
private const int O_TRUNC = 0x0200;
private const int O_EXCL = 0x0400;
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException(
_unsupportedOperationKey,
new PythonType[] { PythonExceptions.ValueError, PythonExceptions.OSError },
typeof(PythonExceptions.BaseException),
dict,
"UnsupportedOperation",
"io"
);
}
[PythonType, DontMapGetMemberNamesToDir]
public class _IOBase : IDisposable, IEnumerator<object>, IEnumerable<object>, IWeakReferenceable, IDynamicMetaObjectProvider, IPythonExpandable {
private bool _closed;
internal CodeContext/*!*/ context;
public _IOBase(CodeContext/*!*/ context) {
this.context = context;
}
#region Public API
public void __del__(CodeContext/*!*/ context) {
close(context);
}
public _IOBase __enter__() {
_checkClosed();
return this;
}
public void __exit__(CodeContext/*!*/ context, params object[] excinfo) {
close(context);
}
public void _checkClosed() {
_checkClosed(null);
}
public void _checkClosed(string msg) {
if (closed) {
throw PythonOps.ValueError(msg ?? "I/O operation on closed file.");
}
}
public void _checkReadable() {
_checkReadable(null);
}
public void _checkReadable(string msg) {
if (!readable(context)) {
throw PythonOps.ValueError(msg ?? "File or stream is not readable.");
}
}
public void _checkSeekable() {
_checkSeekable(null);
}
public void _checkSeekable(string msg) {
if (!seekable(context)) {
throw PythonOps.ValueError(msg ?? "File or stream is not seekable.");
}
}
public void _checkWritable() {
_checkWritable(null);
}
public void _checkWritable(string msg) {
if (!writable(context)) {
throw PythonOps.ValueError(msg ?? "File or stream is not writable.");
}
}
public virtual void close(CodeContext/*!*/ context) {
try {
if (!_closed) {
flush(context);
}
} finally {
_closed = true;
}
}
public virtual bool closed {
get { return _closed; }
}
public virtual int fileno(CodeContext/*!*/ context) {
throw UnsupportedOperation(context, "fileno");
}
public virtual void flush(CodeContext/*!*/ context) {
_checkClosed();
}
public virtual bool isatty(CodeContext/*!*/ context) {
_checkClosed();
return false;
}
[PythonHidden]
public virtual Bytes peek(CodeContext/*!*/ context, int length=0) {
_checkClosed();
throw AttributeError("peek");
}
[PythonHidden]
public virtual object read(CodeContext/*!*/ context, object length=null) {
throw AttributeError("read");
}
[PythonHidden]
public virtual Bytes read1(CodeContext/*!*/ context, int length=0) {
throw AttributeError("read1");
}
public virtual bool readable(CodeContext/*!*/ context) {
return false;
}
public virtual object readline(CodeContext/*!*/ context, int limit) {
_checkClosed();
List<Bytes> res = new List<Bytes>();
int count = 0;
while (limit < 0 || res.Count < limit) {
object cur = read(context, 1);
if (cur == null) {
break;
}
Bytes curBytes = GetBytes(cur, "read()");
if (curBytes.Count == 0) {
break;
}
res.Add(curBytes);
count += curBytes.Count;
if (((IList<byte>)curBytes)[curBytes.Count - 1] == (byte)'\n') {
break;
}
}
return Bytes.Concat(res, count);
}
public object readline(CodeContext/*!*/ context, object limit=null) {
return readline(context, GetInt(limit, -1));
}
public virtual PythonList readlines() {
return readlines(null);
}
public virtual PythonList readlines(object hint=null) {
int size = GetInt(hint, -1);
PythonList res = new PythonList();
if (size <= 0) {
foreach (object line in this) {
res.AddNoLock(line);
}
return res;
}
int count = 0;
foreach (object line in this) {
if (line is Bytes bytes) {
res.AddNoLock(line);
count += bytes.Count;
if (count >= size) {
break;
}
continue;
}
if (line is string str) {
res.AddNoLock(line);
count += str.Length;
if (count >= size) {
break;
}
continue;
}
throw PythonOps.TypeError("next() should return string or bytes");
}
return res;
}
public virtual BigInteger seek(CodeContext/*!*/ context, BigInteger pos, [Optional]object whence) {
throw UnsupportedOperation(context, "seek");
}
public virtual bool seekable(CodeContext/*!*/ context) {
return false;
}
public virtual BigInteger tell(CodeContext/*!*/ context) {
return seek(context, 0, 1);
}
public virtual BigInteger truncate(CodeContext/*!*/ context, object pos=null) {
throw UnsupportedOperation(context, "truncate");
}
public virtual bool writable(CodeContext/*!*/ context) {
return false;
}
[PythonHidden]
public virtual BigInteger write(CodeContext/*!*/ context, object buf) {
throw AttributeError("write");
}
public virtual void writelines(CodeContext/*!*/ context, object lines) {
_checkClosed();
IEnumerator en = PythonOps.GetEnumerator(context, lines);
while (en.MoveNext()) {
write(context, en.Current);
}
}
#endregion
~_IOBase() {
try {
close(context);
} catch { }
}
#region IEnumerator<object> Members
private object _current;
object IEnumerator<object>.Current {
get { return _current; }
}
#endregion
#region IEnumerator Members
object IEnumerator.Current {
get { return _current; }
}
bool IEnumerator.MoveNext() {
_current = readline(context, -1);
if (_current == null) {
return false;
}
if (_current is Bytes bytes) {
return bytes.Count > 0;
}
if (_current is string str) {
return str.Length > 0;
}
return PythonOps.IsTrue(_current);
}
void IEnumerator.Reset() {
_current = null;
seek(context, 0, 0);
}
#endregion
#region IEnumerable<object> Members
[PythonHidden]
public IEnumerator<object> GetEnumerator() {
_checkClosed();
return this;
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
_checkClosed();
return this;
}
#endregion
#region IDisposable Members
void IDisposable.Dispose() { }
#endregion
#region IWeakReferenceable Members
private WeakRefTracker _weakref;
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _weakref;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
_weakref = value;
return true;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
((IWeakReferenceable)this).SetWeakRef(value);
}
#endregion
#region IPythonExpandable Members
private IDictionary<string, object> _customAttributes;
IDictionary<string, object> IPythonExpandable.EnsureCustomAttributes() {
return _customAttributes = new Dictionary<string, object>();
}
IDictionary<string, object> IPythonExpandable.CustomAttributes {
get { return _customAttributes; }
}
CodeContext/*!*/ IPythonExpandable.Context {
get { return context; }
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new MetaExpandable<_IOBase>(parameter, this);
}
#endregion
#region Private implementation details
internal Exception UnsupportedOperation(CodeContext/*!*/ context, string attr) {
throw PythonExceptions.CreateThrowable(
(PythonType)context.LanguageContext.GetModuleState(_unsupportedOperationKey),
string.Format("{0}.{1} not supported", PythonTypeOps.GetName(this), attr)
);
}
internal Exception AttributeError(string attrName) {
throw PythonOps.AttributeError("'{0}' object has no attribute '{1}'", PythonTypeOps.GetName(this), attrName);
}
internal Exception InvalidPosition(BigInteger pos) {
return PythonOps.IOError("Raw stream returned invalid position {0}", pos);
}
#endregion
}
[PythonType]
public class _RawIOBase : _IOBase, IDynamicMetaObjectProvider {
public _RawIOBase(CodeContext/*!*/ context) : base(context) { }
#region Public API
public override object read(CodeContext/*!*/ context, object size=null) {
int sizeInt = GetInt(size, -1);
if (sizeInt < 0) {
return readall(context);
}
ByteArray arr = new ByteArray(new byte[sizeInt]);
sizeInt = (int)readinto(context, arr);
List<byte> res = arr.UnsafeByteList;
if (sizeInt < res.Count) {
res.RemoveRange(sizeInt, res.Count - sizeInt);
}
return new Bytes(res);
}
public Bytes readall(CodeContext/*!*/ context) {
List<Bytes> res = new List<Bytes>();
int count = 0;
for (; ; ) {
object cur = read(context, DEFAULT_BUFFER_SIZE);
if (cur == null) {
break;
}
Bytes curBytes = GetBytes(cur, "read()");
if (curBytes.Count == 0) {
break;
}
count += curBytes.Count;
res.Add(curBytes);
}
return Bytes.Concat(res, count);
}
public virtual BigInteger readinto(CodeContext/*!*/ context, object buf) {
throw UnsupportedOperation(context, "readinto");
}
public override BigInteger write(CodeContext/*!*/ context, object buf) {
throw UnsupportedOperation(context, "write");
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new MetaExpandable<_RawIOBase>(parameter, this);
}
#endregion
}
[PythonType]
public class _BufferedIOBase : _IOBase, IDynamicMetaObjectProvider {
public _BufferedIOBase(CodeContext/*!*/ context) : base(context) { }
#region Public API
public virtual object detach(CodeContext/*!*/ context) {
throw UnsupportedOperation(context, "detach");
}
public override object read(CodeContext/*!*/ context, object length=null) {
throw UnsupportedOperation(context, "read");
}
public virtual BigInteger readinto(CodeContext/*!*/ context, object buf) {
int length = -1;
if (PythonOps.HasAttr(context, buf, "__len__")) {
length = PythonOps.Length(buf);
}
object dataObj = read(context, length);
if (dataObj == null) {
return BigInteger.Zero;
}
Bytes data = GetBytes(dataObj, "read()");
if (buf is IList<byte> bytes) {
for (int i = 0; i < data.Count; i++) {
bytes[i] = ((IList<byte>)data)[i];
}
GC.KeepAlive(this);
return data.Count;
}
object setter;
if (PythonOps.TryGetBoundAttr(buf, "__setitem__", out setter)) {
for (int i = 0; i < data.Count; i++) {
PythonOps.CallWithContext(context, setter, i, data[i]);
}
GC.KeepAlive(this);
return data.Count;
}
throw PythonOps.TypeError("must be read-write buffer, not " + PythonTypeOps.GetName(buf));
}
public override BigInteger write(CodeContext/*!*/ context, object buf) {
throw UnsupportedOperation(context, "write");
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new MetaExpandable<_BufferedIOBase>(parameter, this);
}
#endregion
}
[PythonType]
public class _TextIOBase : _IOBase, IDynamicMetaObjectProvider {
public _TextIOBase(CodeContext/*!*/ context) : base(context) { }
#region Public API
public virtual object detach(CodeContext/*!*/ context) {
throw UnsupportedOperation(context, "detach");
}
public virtual string encoding {
get { return null; }
}
public virtual string errors {
get { return null; }
}
public virtual object newlines {
get { return null; }
}
public override object read(CodeContext/*!*/ context, [DefaultParameterValue(-1)]object length) {
throw UnsupportedOperation(context, "read");
}
public override object readline(CodeContext/*!*/ context, int limit=-1) {
throw UnsupportedOperation(context, "readline");
}
public override BigInteger truncate(CodeContext/*!*/ context, object pos=null) {
throw UnsupportedOperation(context, "truncate");
}
public override BigInteger write(CodeContext/*!*/ context, object str) {
throw UnsupportedOperation(context, "write");
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new MetaExpandable<_TextIOBase>(parameter, this);
}
#endregion
}
[PythonType]
public class BufferedReader : _BufferedIOBase, IDynamicMetaObjectProvider {
private _IOBase _rawIO;
private object _raw;
private int _bufSize;
private Bytes _readBuf;
private int _readBufPos;
internal static BufferedReader Create(CodeContext/*!*/ context, object raw, int buffer_size=DEFAULT_BUFFER_SIZE) {
var res = new BufferedReader(context, raw, buffer_size);
res.__init__(context, raw, buffer_size);
return res;
}
public BufferedReader(
CodeContext/*!*/ context,
object raw,
int buffer_size=DEFAULT_BUFFER_SIZE
) : base(context) {
}
public void __init__(
CodeContext/*!*/ context,
object raw,
int buffer_size=DEFAULT_BUFFER_SIZE
) {
this.raw = raw;
if (_rawIO != null) {
if (!_rawIO.readable(context)) {
throw PythonOps.IOError("\"raw\" argument must be readable.");
}
} else {
if (PythonOps.Not(PythonOps.Invoke(context, _raw, "readable"))) {
throw PythonOps.IOError("\"raw\" argument must be readable.");
}
}
if (buffer_size <= 0) {
throw PythonOps.ValueError("invalid buffer size (must be positive)");
}
_bufSize = buffer_size;
_readBuf = Bytes.Empty;
}
#region Public API
public object raw {
get {
return _raw;
}
set {
_rawIO = value as _IOBase;
_raw = value;
}
}
#region _BufferedIOMixin
public override BigInteger truncate(CodeContext/*!*/ context, object pos=null) {
if (_rawIO != null) {
return _rawIO.truncate(context, pos);
}
return GetBigInt(
PythonOps.Invoke(context, _raw, "truncate", pos),
"truncate() should return integer"
);
}
public override void close(CodeContext/*!*/ context) {
if (!closed) {
try {
flush(context);
} finally {
if (_rawIO != null) {
_rawIO.close(context);
} else {
PythonOps.Invoke(context, _raw, "close");
}
}
}
}
public override object detach(CodeContext/*!*/ context) {
if (_raw == null) {
throw PythonOps.ValueError("raw stream already detached");
}
flush(context);
object res = _raw;
raw = null;
return res;
}
public override bool seekable(CodeContext/*!*/ context) {
if (_rawIO != null) {
return _rawIO.seekable(context);
}
return PythonOps.IsTrue(PythonOps.Invoke(context, _raw, "seekable"));
}
public override bool readable(CodeContext/*!*/ context) {
if (_rawIO != null) {
return _rawIO.readable(context);
}
return PythonOps.IsTrue(PythonOps.Invoke(context, _raw, "readable"));
}
public override bool writable(CodeContext/*!*/ context) {
if (_rawIO != null) {
return _rawIO.writable(context);
}
return PythonOps.IsTrue(PythonOps.Invoke(context, _raw, "writable"));
}
public override bool closed {
get {
if (_rawIO != null) {
return _rawIO.closed;
}
return PythonOps.IsTrue(PythonOps.GetBoundAttr(context, _raw, "closed"));
}
}
public object name {
get {
return PythonOps.GetBoundAttr(context, _raw, "name");
}
}
public object mode {
get {
return PythonOps.GetBoundAttr(context, _raw, "mode");
}
}
public override int fileno(CodeContext/*!*/ context) {
if (_rawIO != null) {
return _rawIO.fileno(context);
}
return GetInt(
PythonOps.Invoke(context, _raw, "fileno"),
"fileno() should return integer"
);
}
public override bool isatty(CodeContext/*!*/ context) {
if (_rawIO != null) {
return _rawIO.isatty(context);
}
return PythonOps.IsTrue(PythonOps.Invoke(context, _raw, "isatty"));
}
#endregion
public override object read(CodeContext/*!*/ context, object length=null) {
int len = GetInt(length, -1);
if (len < -1) {
throw PythonOps.ValueError("invalid number of bytes to read");
}
lock (this) {
return ReadNoLock(context, len);
}
}
private Bytes ReadNoLock(CodeContext/*!*/ context, int length, bool read1 = false) {
if (length == 0) {
return Bytes.Empty;
}
if (length < 0) {
List<Bytes> chunks = new List<Bytes>();
int count = 0;
if (_readBuf.Count > 0) {
chunks.Add(ResetReadBuf());
count += chunks[0].Count;
}
for (; ; ) {
object chunkObj;
if (_rawIO != null) {
chunkObj = _rawIO.read(context, -1);
} else {
chunkObj = PythonOps.Invoke(context, _raw, "read", -1);
}
Bytes chunk = GetBytes(chunkObj, "read()");
if (chunk == null || chunk.Count == 0) {
if (count == 0) {
return chunk;
}
break;
}
chunks.Add(chunk);
count += chunk.Count;
if (read1) break;
}
GC.KeepAlive(this);
return Bytes.Concat(chunks, count);
}
if (length <= _readBuf.Count - _readBufPos) {
// requested data is already buffered
byte[] res = new byte[length];
Array.Copy(_readBuf.UnsafeByteArray, _readBufPos, res, 0, length);
_readBufPos += length;
if (_readBufPos == _readBuf.Count) {
ResetReadBuf();
}
GC.KeepAlive(this);
return Bytes.Make(res);
} else {
// a read is required to provide requested amount of data
List<Bytes> chunks = new List<Bytes>();
int remaining = length;
if (_readBuf.Count > 0) {
chunks.Add(ResetReadBuf());
remaining -= chunks[0].Count;
}
while (remaining > 0) {
object chunkObj;
if (_rawIO != null) {
chunkObj = _rawIO.read(context, _bufSize);
} else {
chunkObj = PythonOps.Invoke(context, _raw, "read", _bufSize);
}
Bytes chunk = chunkObj != null ? GetBytes(chunkObj, "read()") : Bytes.Empty;
_readBuf = chunk;
if (_readBuf.Count == 0) {
break;
}
if (remaining >= _readBuf.Count - _readBufPos) {
remaining -= _readBuf.Count - _readBufPos;
chunks.Add(ResetReadBuf());
} else {
byte[] bytes = new byte[remaining];
Array.Copy(_readBuf.UnsafeByteArray, 0, bytes, 0, remaining);
chunks.Add(Bytes.Make(bytes));
_readBufPos = remaining;
remaining = 0;
break;
}
if (read1) break;
}
GC.KeepAlive(this);
return Bytes.Concat(chunks, length - remaining);
}
}
public override Bytes peek(CodeContext/*!*/ context, int length=0) {
_checkClosed();
if (length <= 0 || length > _bufSize) {
length = _bufSize;
}
lock (this) {
return PeekNoLock(context, length);
}
}
private Bytes PeekNoLock(CodeContext/*!*/ context, int length) {
int bufLen = _readBuf.Count - _readBufPos;
byte[] bytes = new byte[length];
if (length <= bufLen) {
Array.Copy(_readBuf.UnsafeByteArray, _readBufPos, bytes, 0, length);
return Bytes.Make(bytes);
}
object nextObj;
if (_rawIO != null) {
nextObj = _rawIO.read(context, length - _readBuf.Count + _readBufPos);
} else {
nextObj = PythonOps.Invoke(context, _raw, "read", length - _readBuf.Count + _readBufPos);
}
Bytes next = nextObj != null ? GetBytes(nextObj, "read()") : Bytes.Empty;
_readBuf = ResetReadBuf() + next;
return _readBuf;
}
public override Bytes read1(CodeContext/*!*/ context, int length=0) {
if (length == 0) {
return Bytes.Empty;
} else if (length < 0) {
throw PythonOps.ValueError("number of bytes to read must be positive");
}
lock (this) {
int bufLen = _readBuf.Count - _readBufPos;
return ReadNoLock(context, bufLen > 0 ? Math.Min(length, bufLen) : length, read1: true);
}
}
public override BigInteger tell(CodeContext/*!*/ context) {
BigInteger res = _rawIO != null ?
_rawIO.tell(context) :
GetBigInt(
PythonOps.Invoke(context, _raw, "tell"),
"tell() should return integer"
);
if (res < 0) {
throw InvalidPosition(res);
}
return res - _readBuf.Count + _readBufPos;
}
public BigInteger seek(double offset, [Optional]object whence) {
_checkClosed();
throw PythonOps.TypeError("an integer is required");
}
public override BigInteger seek(CodeContext/*!*/ context, BigInteger pos, [Optional]object whence) {
int whenceInt = GetInt(whence);
if (whenceInt < 0 || whenceInt > 2) {
throw PythonOps.ValueError("invalid whence ({0}, should be 0, 1, or 2)", whenceInt);
}
lock (this) {
if (whenceInt == 1) {
pos -= _readBuf.Count - _readBufPos;
}
object posObj;
if (_rawIO != null) {
posObj = _rawIO.seek(context, pos, whenceInt);
} else {
posObj = PythonOps.Invoke(context, _raw, "seek", whenceInt);
}
pos = GetBigInt(posObj, "seek() should return integer");
ResetReadBuf();
if (pos < 0) {
throw InvalidPosition(pos);
}
GC.KeepAlive(this);
return pos;
}
}
#endregion
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) {
return new MetaExpandable<BufferedReader>(parameter, this);
}
#endregion
#region Private implementation details
private Bytes ResetReadBuf() {
Bytes res;
if (_readBufPos == 0) {
res = _readBuf;
} else {
byte[] bytes = new byte[_readBuf.Count - _readBufPos];
Array.Copy(_readBuf.UnsafeByteArray, _readBufPos, bytes, 0, bytes.Length);
res = Bytes.Make(bytes);
_readBufPos = 0;
}
_readBuf = Bytes.Empty;
return res;
}
#endregion
}
[PythonType]
public class BufferedWriter : _BufferedIOBase, IDynamicMetaObjectProvider {
private _IOBase _rawIO;
private object _raw;
private int _bufSize;
private List<byte> _writeBuf;
internal static BufferedWriter Create(CodeContext/*!*/ context,
object raw,
int buffer_size=DEFAULT_BUFFER_SIZE,
object max_buffer_size=null) {
var res = new BufferedWriter(context, raw, buffer_size, max_buffer_size);
res.__init__(context, raw, buffer_size, max_buffer_size);
return res;
}
public BufferedWriter(
CodeContext/*!*/ context,
object raw,
int buffer_size=DEFAULT_BUFFER_SIZE,
object max_buffer_size=null
)
: base(context) {
}
public void __init__(
CodeContext/*!*/ context,
object raw,
int buffer_size=DEFAULT_BUFFER_SIZE,
object max_buffer_size=null
) {
if (max_buffer_size != null) {
PythonOps.Warn(context, PythonExceptions.DeprecationWarning, "max_buffer_size is deprecated");
}