forked from IronLanguages/ironpython3
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_struct.cs
More file actions
1395 lines (1217 loc) · 62.9 KB
/
_struct.cs
File metadata and controls
1395 lines (1217 loc) · 62.9 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.Generic;
using System.IO;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
[assembly: PythonModule("_struct", typeof(IronPython.Modules.PythonStruct))]
namespace IronPython.Modules {
public static class PythonStruct {
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException("structerror", dict, "error", "struct");
}
#region Public API
public const string __doc__ = null;
[PythonType, Documentation("Represents a compiled struct pattern")]
public class Struct : IWeakReferenceable {
private Format[] _formats; // the various formatting options for the compiled struct
private bool _isStandardized; // true if the format is in standardized mode
private bool _isLittleEndian; // true if the format is in little endian mode
private int _encodingCount = -1; // the number of objects consumed/produced by the format
private int _encodingSize = -1; // the number of bytes read/produced by the format
private WeakRefTracker _tracker; // storage for weak proxy's
private void InitializeFrom(Struct s) {
format = s.format;
_formats = s._formats;
_isStandardized = s._isStandardized;
_isLittleEndian = s._isLittleEndian;
_encodingCount = s._encodingCount;
_encodingSize = s._encodingSize;
_tracker = s._tracker;
}
internal Struct(CodeContext/*!*/ context, [NotNull]string/*!*/ fmt) {
__init__(context, fmt);
}
#region Python construction
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct(params object[] args) {
}
[Documentation("creates a new uninitialized struct object - all arguments are ignored")]
public Struct([ParamDictionary]IDictionary<object, object> kwArgs, params object[] args) {
}
[Documentation("initializes or re-initializes the compiled struct object with a new format")]
public void __init__(CodeContext/*!*/ context, object fmt) {
format = FormatObjectToString(fmt);
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(format, out s);
}
InitializeFrom(gotIt ? s : CompileAndCache(context, format));
}
#endregion
#region Public API
[Documentation("gets the current format string for the compiled Struct")]
public string format { get; private set; }
[Documentation("returns a string consisting of the values serialized according to the format of the struct object")]
public Bytes/*!*/ pack(CodeContext/*!*/ context, params object[] values) {
if (values.Length != _encodingCount) {
throw Error(context, $"pack requires exactly {_encodingCount} arguments");
}
int curObj = 0;
var buffer = new byte[_encodingSize];
using var res = new MemoryStream(buffer);
foreach (Format curFormat in _formats) {
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
int alignLength = Align((int)res.Position, nativeSize);
int padLength = alignLength - (int)res.Position;
res.WriteByteCount((byte)'\0', padLength);
}
switch (curFormat.Type) {
case FormatType.PadByte:
res.WriteByteCount((byte)'\0', curFormat.Count);
break;
case FormatType.Bool:
res.WriteByte((byte)(GetBoolValue(context, curObj++, values) ? 1 : 0));
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte((byte)GetCharValue(context, curObj++, values));
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte((byte)GetSByteValue(context, curObj++, values));
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res.WriteByte(GetByteValue(context, curObj++, values));
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
WriteShort(res, _isLittleEndian, GetShortValue(context, curObj++, values));
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
WriteUShort(res, _isLittleEndian, GetUShortValue(context, curObj++, values));
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
WriteInt(res, _isLittleEndian, GetIntValue(context, curObj++, values));
}
break;
case FormatType.UnsignedInt:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, curObj++, values));
}
break;
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetULongValue(context, curObj++, values));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
WritePointer(res, _isLittleEndian, GetPointer(context, curObj++, values));
}
break;
case FormatType.SignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
WriteSignedNetPointer(res, _isLittleEndian, GetSignedNetPointer(context, curObj++, values));
}
break;
case FormatType.UnsignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
WriteUnsignedNetPointer(res, _isLittleEndian, GetUnsignedNetPointer(context, curObj++, values));
}
break;
case FormatType.SignedSizeT:
for (int j = 0; j < curFormat.Count; j++) {
WriteInt(res, _isLittleEndian, GetSignedSizeT(context, curObj++, values));
}
break;
case FormatType.SizeT:
for (int j = 0; j < curFormat.Count; j++) {
WriteUInt(res, _isLittleEndian, GetSizeT(context, curObj++, values));
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteLong(res, _isLittleEndian, GetLongLongValue(context, curObj++, values));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
WriteULong(res, _isLittleEndian, GetULongLongValue(context, curObj++, values));
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
WriteDouble(res, _isLittleEndian, GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
WriteFloat(res, _isLittleEndian, (float)GetDoubleValue(context, curObj++, values));
}
break;
case FormatType.CString:
WriteString(res, curFormat.Count, GetStringValue(context, curObj++, values));
break;
case FormatType.PascalString:
WritePascalString(res, curFormat.Count - 1, GetStringValue(context, curObj++, values));
break;
}
}
return Bytes.Make(buffer);
}
[Documentation("Stores the deserialized data into the provided array")]
public void pack_into(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args) {
byte[] existing = buffer.ToByteArray();
if (offset + size > existing.Length) {
throw Error(context, $"pack_into requires a buffer of at least {size} bytes");
}
var data = pack(context, args).UnsafeByteArray;
for (int i = 0; i < data.Length; i++) {
existing[i + offset] = data[i];
}
buffer.Clear();
buffer.FromStream(new MemoryStream(existing));
}
public void pack_into(CodeContext/*!*/ context, [NotNull]ByteArray/*!*/ buffer, int offset, params object[] args) {
IList<byte> existing = buffer.UnsafeByteList;
if (offset + size > existing.Count) {
throw Error(context, $"pack_into requires a buffer of at least {size} bytes");
}
var data = pack(context, args).UnsafeByteArray;
for (int i = 0; i < data.Length; i++) {
existing[i + offset] = data[i];
}
}
[Documentation("deserializes the string using the structs specified format")]
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte> @string) {
if (@string.Count != size) {
throw Error(context, $"unpack requires a bytes object of length {size}");
}
var data = @string;
int curIndex = 0;
var res = new object[_encodingCount];
var res_idx = 0;
foreach (Format curFormat in _formats) {
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
int nativeSize = curFormat.NativeSize;
if (nativeSize > 0) {
curIndex = Align(curIndex, nativeSize);
}
}
switch (curFormat.Type) {
case FormatType.PadByte:
curIndex += curFormat.Count;
break;
case FormatType.Bool:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateBoolValue(context, ref curIndex, data);
}
break;
case FormatType.Char:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = Bytes.FromByte(CreateCharValue(context, ref curIndex, data));
}
break;
case FormatType.SignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)(sbyte)CreateCharValue(context, ref curIndex, data);
}
break;
case FormatType.UnsignedChar:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateCharValue(context, ref curIndex, data);
}
break;
case FormatType.Short:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateShortValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.UnsignedShort:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = (int)CreateUShortValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.Int:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateUIntValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Pointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
} else {
res[res_idx++] = BigIntegerOps.__int__(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.SignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = new IntPtr(CreateIntValue(context, ref curIndex, _isLittleEndian, data));
} else {
res[res_idx++] = new IntPtr(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.UnsignedNetPointer:
for (int j = 0; j < curFormat.Count; j++) {
if (IntPtr.Size == 4) {
res[res_idx++] = new UIntPtr(CreateUIntValue(context, ref curIndex, _isLittleEndian, data));
} else {
res[res_idx++] = new UIntPtr(CreateULongValue(context, ref curIndex, _isLittleEndian, data));
}
}
break;
case FormatType.SignedSizeT:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.SizeT:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateUIntValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.LongLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateLongValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.UnsignedLongLong:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = BigIntegerOps.__int__(CreateULongValue(context, ref curIndex, _isLittleEndian, data));
}
break;
case FormatType.Float:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateFloatValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.Double:
for (int j = 0; j < curFormat.Count; j++) {
res[res_idx++] = CreateDoubleValue(context, ref curIndex, _isLittleEndian, data);
}
break;
case FormatType.CString:
res[res_idx++] = CreateString(context, ref curIndex, curFormat.Count, data);
break;
case FormatType.PascalString:
res[res_idx++] = CreatePascalString(context, ref curIndex, curFormat.Count - 1, data);
break;
}
}
System.Diagnostics.Debug.Assert(res_idx == res.Length);
return PythonTuple.MakeTuple(res);
}
public PythonTuple/*!*/ unpack(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer)
=> unpack(context, buffer.ToByteArray());
[Documentation("reads the current format from the specified array")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
int bytesAvail = buffer.Count - offset;
if (bytesAvail < size) {
throw Error(context, $"unpack_from requires a buffer of at least {size} bytes");
}
return unpack(context, buffer.Substring(offset, size));
}
[Documentation("reads the current format from the specified array")]
public PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return unpack_from(context, buffer.ToByteArray(), offset);
}
[Documentation("iteratively unpack the current format from the specified array.")]
public PythonUnpackIterator iter_unpack(CodeContext/*!*/ context, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return new PythonUnpackIterator(this, context, buffer, offset);
}
[Documentation("iteratively unpack the current format from the specified array.")]
public PythonUnpackIterator iter_unpack(CodeContext/*!*/ context, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return new PythonUnpackIterator(this, context, buffer, offset);
}
[Documentation("gets the number of bytes that the serialized string will occupy or are required to deserialize the data")]
public int size {
get {
return _encodingSize;
}
}
#endregion
#region IWeakReferenceable Members
WeakRefTracker IWeakReferenceable.GetWeakRef() {
return _tracker;
}
bool IWeakReferenceable.SetWeakRef(WeakRefTracker value) {
return Interlocked.CompareExchange(ref _tracker, value, null) == null;
}
void IWeakReferenceable.SetFinalizer(WeakRefTracker value) {
_tracker = value;
}
#endregion
#region Implementation Details
private static Struct CompileAndCache(CodeContext/*!*/ context, string/*!*/ fmt) {
List<Format> res = new List<Format>();
int count = 1;
bool fLittleEndian = BitConverter.IsLittleEndian;
bool fStandardized = false;
for (int i = 0; i < fmt.Length; i++) {
switch (fmt[i]) {
case 'x': // pad byte
res.Add(new Format(FormatType.PadByte, count));
count = 1;
break;
case '?': // bool
res.Add(new Format(FormatType.Bool, count));
count = 1;
break;
case 'c': // char
res.Add(new Format(FormatType.Char, count));
count = 1;
break;
case 'b': // signed char
res.Add(new Format(FormatType.SignedChar, count));
count = 1;
break;
case 'B': // unsigned char
res.Add(new Format(FormatType.UnsignedChar, count));
count = 1;
break;
case 'h': // short
res.Add(new Format(FormatType.Short, count));
count = 1;
break;
case 'H': // unsigned short
res.Add(new Format(FormatType.UnsignedShort, count));
count = 1;
break;
case 'i': // int
case 'l': // long
res.Add(new Format(FormatType.Int, count));
count = 1;
break;
case 'I': // unsigned int
res.Add(new Format(FormatType.UnsignedInt, count));
count = 1;
break;
case 'L': // unsigned long
res.Add(new Format(FormatType.UnsignedLong, count));
count = 1;
break;
case 'q': // long long
res.Add(new Format(FormatType.LongLong, count));
count = 1;
break;
case 'Q': // unsigned long long
res.Add(new Format(FormatType.UnsignedLongLong, count));
count = 1;
break;
case 'f': // float
res.Add(new Format(FormatType.Float, count));
count = 1;
break;
case 'd': // double
res.Add(new Format(FormatType.Double, count));
count = 1;
break;
case 's': // char[]
res.Add(new Format(FormatType.CString, count));
count = 1;
break;
case 'p': // pascal char[]
res.Add(new Format(FormatType.PascalString, count));
count = 1;
break;
case 'P': // void *
res.Add(new Format(FormatType.Pointer, count));
count = 1;
break;
case 'r': // IntPtr
if (fStandardized) {
// r and R don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SignedNetPointer, count));
count = 1;
break;
case 'R': // UIntPtr
if (fStandardized) {
// r and R don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.UnsignedNetPointer, count));
count = 1;
break;
case 'n': // ssize_t
if (fStandardized) {
// n and N don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SignedSizeT, count));
count = 1;
break;
case 'N': // size_t
if (fStandardized) {
// n and N don't exist in standard sizes
throw Error(context, "bad char in struct format");
}
res.Add(new Format(FormatType.SizeT, count));
count = 1;
break;
case ' ': // white space, ignore
case '\t':
break;
case '=': // native
if (i != 0) throw Error(context, "unexpected byte order");
fStandardized = true;
break;
case '@': // native
if (i != 0) throw Error(context, "unexpected byte order");
break;
case '<': // little endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = true;
fStandardized = true;
break;
case '>': // big endian
case '!': // big endian
if (i != 0) throw Error(context, "unexpected byte order");
fLittleEndian = false;
fStandardized = true;
break;
default:
if (char.IsDigit(fmt[i])) {
count = 0;
while (char.IsDigit(fmt[i])) {
count = count * 10 + (fmt[i] - '0');
i++;
}
if (char.IsWhiteSpace(fmt[i])) Error(context, "white space not allowed between count and format");
i--;
break;
}
throw Error(context, "bad char in struct format");
}
}
// store the new formats
var s = new Struct() {
format = fmt,
_formats = res.ToArray(),
_isStandardized = fStandardized,
_isLittleEndian = fLittleEndian,
};
s.InitCountAndSize();
lock (_cache) {
_cache.Add(fmt, s);
}
return s;
}
private void InitCountAndSize() {
var encodingCount = 0;
var encodingSize = 0;
foreach (Format format in _formats) {
if (format.Type != FormatType.PadByte) {
if (format.Type != FormatType.CString && format.Type != FormatType.PascalString) {
encodingCount += format.Count;
} else {
encodingCount++;
}
}
if (!_isStandardized) {
// In native mode, align to {size}-byte boundaries
encodingSize = Align(encodingSize, format.NativeSize);
}
encodingSize += GetNativeSize(format.Type) * format.Count;
}
_encodingCount = encodingCount;
_encodingSize = encodingSize;
}
#endregion
#region Internal helpers
internal static Struct Create(string/*!*/ format) {
Struct res = new Struct();
res.__init__(DefaultContext.Default, format); // default context is only used for errors, this better be an error free format.
return res;
}
#endregion
}
[PythonType("unpack_iterator"), Documentation("Represents an iterator returned by _struct.iter_unpack()")]
public class PythonUnpackIterator : System.Collections.IEnumerator, System.Collections.IEnumerable {
private object _iter_current;
private int _next_offset;
private readonly CodeContext _context;
private readonly IList<byte> _buffer;
private readonly int _start_offset;
private readonly Struct _owner;
private PythonUnpackIterator() { }
internal PythonUnpackIterator(Struct/*!*/ owner, CodeContext/*!*/ context, IList<byte>/*!*/ buffer, int offset) {
_context = context;
_buffer = buffer;
_start_offset = offset;
_owner = owner;
Reset();
ValidateBufferLength();
}
internal PythonUnpackIterator(Struct/*!*/ owner, CodeContext/*!*/ context, ArrayModule.array/*!*/ buffer, int offset) {
_context = context;
_buffer = buffer.ToByteArray();
_start_offset = offset;
_owner = owner;
Reset();
ValidateBufferLength();
}
private void ValidateBufferLength() {
if (_buffer.Count - _start_offset < _owner.size) {
throw Error(_context, $"iterative unpacking requires a buffer of a multiple of {_owner.size} bytes");
}
}
#region IEnumerable
[PythonHidden]
public System.Collections.IEnumerator GetEnumerator() {
return this;
}
#endregion
#region IEnumerator
[PythonHidden]
public object Current => _iter_current;
[PythonHidden]
public bool MoveNext() {
if (_buffer.Count - _next_offset < _owner.size) {
return false;
}
_iter_current = _owner.unpack_from(_context, _buffer, _next_offset);
_next_offset += _owner.size;
return true;
}
[PythonHidden]
public void Reset() {
_iter_current = null;
_next_offset = _start_offset;
}
#endregion
public object __iter__() {
return this;
}
public object __next__() {
if (!MoveNext()) {
throw PythonOps.StopIteration();
}
return Current;
}
public int __length_hint__() {
return (_buffer.Count - _next_offset) / _owner.size;
}
}
#endregion
#region Compiled Format
/// <summary>
/// Enum which specifies the format type for a compiled struct
/// </summary>
private enum FormatType {
PadByte,
Bool,
Char,
SignedChar,
UnsignedChar,
Short,
UnsignedShort,
Int,
UnsignedInt,
UnsignedLong,
Float,
LongLong,
UnsignedLongLong,
Double,
CString,
PascalString,
Pointer,
SignedNetPointer,
UnsignedNetPointer,
SignedSizeT,
SizeT,
}
private static int GetNativeSize(FormatType c) {
switch (c) {
case FormatType.Char:
case FormatType.SignedChar:
case FormatType.UnsignedChar:
case FormatType.PadByte:
case FormatType.Bool:
case FormatType.CString:
case FormatType.PascalString:
return 1;
case FormatType.Short:
case FormatType.UnsignedShort:
return 2;
case FormatType.Int:
case FormatType.UnsignedInt:
case FormatType.UnsignedLong:
case FormatType.Float:
case FormatType.SignedSizeT:
case FormatType.SizeT:
return 4;
case FormatType.LongLong:
case FormatType.UnsignedLongLong:
case FormatType.Double:
return 8;
case FormatType.Pointer:
case FormatType.SignedNetPointer:
case FormatType.UnsignedNetPointer:
return UIntPtr.Size;
default:
throw new InvalidOperationException(c.ToString());
}
}
/// <summary>
/// Struct used to store the format and the number of times it should be repeated.
/// </summary>
private readonly struct Format {
public readonly FormatType Type;
public readonly int Count;
public Format(FormatType type, int count) {
Type = type;
Count = count;
}
public int NativeSize => GetNativeSize(Type);
}
#endregion
#region Cache of compiled struct patterns
private const int MAX_CACHE_SIZE = 1024;
private static CacheDict<string, Struct> _cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
private static string FormatObjectToString(object fmt) {
if (Converter.TryConvertToString(fmt, out string res)) {
return res;
}
if (fmt is IList<byte> b) {
return PythonOps.MakeString(b);
}
throw PythonOps.TypeError("Struct() argument 1 must be a str or bytes object, not {0}", PythonOps.GetPythonTypeName(fmt));
}
private static Struct GetStructFromCache(CodeContext/*!*/ context, object fmt) {
var formatString = FormatObjectToString(fmt);
Struct s;
bool gotIt;
lock (_cache) {
gotIt = _cache.TryGetValue(formatString, out s);
}
if (!gotIt) {
s = new Struct(context, formatString);
}
return s;
}
[Documentation("Clear the internal cache.")]
public static void _clearcache() {
_cache = new CacheDict<string, Struct>(MAX_CACHE_SIZE);
}
[Documentation("int(x[, base]) -> integer\n\nConvert a string or number to an integer, if possible. A floating point\nargument will be truncated towards zero (this does not include a string\nrepresentation of a floating point number!) When converting a string, use\nthe optional base. It is an error to supply a base when converting a\nnon-string. If base is zero, the proper base is guessed based on the\nstring content. If the argument is outside the integer range a\nlong object will be returned instead.")]
public static int calcsize(CodeContext/*!*/ context, object fmt) {
return GetStructFromCache(context, fmt).size;
}
[Documentation("Return string containing values v1, v2, ... packed according to fmt.")]
public static Bytes/*!*/ pack(CodeContext/*!*/ context, object fmt/*!*/, params object[] values) {
return GetStructFromCache(context, fmt).pack(context, values);
}
[Documentation("Pack the values v1, v2, ... according to fmt.\nWrite the packed bytes into the writable buffer buf starting at offset.")]
public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset, params object[] args) {
GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args);
}
public static void pack_into(CodeContext/*!*/ context, object fmt, [NotNull]ByteArray/*!*/ buffer, int offset, params object[] args) {
GetStructFromCache(context, fmt).pack_into(context, buffer, offset, args);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer) {
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the string containing packed C structure data, according to fmt.\nRequires len(string) == calcsize(fmt).")]
public static PythonTuple/*!*/ unpack(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer) {
return GetStructFromCache(context, fmt).unpack(context, buffer);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonTuple/*!*/ unpack_from(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).unpack_from(context, buffer, offset);
}
[Documentation("Iteratively unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonUnpackIterator/*!*/ iter_unpack(CodeContext/*!*/ context, object fmt, [BytesLike][NotNull]IList<byte>/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).iter_unpack(context, buffer, offset);
}
[Documentation("Iteratively unpack the buffer, containing packed C structure data, according to\nfmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).")]
public static PythonUnpackIterator/*!*/ iter_unpack(CodeContext/*!*/ context, object fmt, [NotNull]ArrayModule.array/*!*/ buffer, int offset = 0) {
return GetStructFromCache(context, fmt).iter_unpack(context, buffer, offset);
}
#endregion
#region Write Helpers
private static void WriteByteCount(this MemoryStream stream, byte value, int repeatCount) {
while (repeatCount > 0) {
stream.WriteByte(value);
--repeatCount;
}
}
private static void WriteShort(this MemoryStream res, bool fLittleEndian, short val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
} else {
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteUShort(this MemoryStream res, bool fLittleEndian, ushort val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
} else {
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteInt(this MemoryStream res, bool fLittleEndian, int val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
} else {
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteUInt(this MemoryStream res, bool fLittleEndian, uint val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
} else {
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WritePointer(this MemoryStream res, bool fLittleEndian, ulong val) {
if (UIntPtr.Size == 4) {
res.WriteUInt(fLittleEndian, (uint)val);
} else {
res.WriteULong(fLittleEndian, val);
}
}
private static void WriteUnsignedNetPointer(this MemoryStream res, bool fLittleEndian, UIntPtr val) {
res.WritePointer(fLittleEndian, val.ToUInt64());
}
private static void WriteSignedNetPointer(this MemoryStream res, bool fLittleEndian, IntPtr val) {
res.WritePointer(fLittleEndian, unchecked((ulong)val.ToInt64()));
}
private static void WriteFloat(this MemoryStream res, bool fLittleEndian, float val) {
byte[] bytes = BitConverter.GetBytes(val);
if (BitConverter.IsLittleEndian == fLittleEndian) {
res.Write(bytes, 0, bytes.Length);
} else {
res.WriteByte(bytes[3]);
res.WriteByte(bytes[2]);
res.WriteByte(bytes[1]);
res.WriteByte(bytes[0]);
}
}
private static void WriteLong(this MemoryStream res, bool fLittleEndian, long val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 56) & 0xff));
} else {
res.WriteByte((byte)((val >> 56) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)(val & 0xff));
}
}
private static void WriteULong(this MemoryStream res, bool fLittleEndian, ulong val) {
if (fLittleEndian) {
res.WriteByte((byte)(val & 0xff));
res.WriteByte((byte)((val >> 8) & 0xff));
res.WriteByte((byte)((val >> 16) & 0xff));
res.WriteByte((byte)((val >> 24) & 0xff));
res.WriteByte((byte)((val >> 32) & 0xff));
res.WriteByte((byte)((val >> 40) & 0xff));
res.WriteByte((byte)((val >> 48) & 0xff));
res.WriteByte((byte)((val >> 56) & 0xff));
} else {