Repository navigation
Expand file tree
/
Copy path_codecs.cs
More file actions
1037 lines (856 loc) · 38.3 KB
/
Copy path_codecs.cs
File metadata and controls
1037 lines (856 loc) · 38.3 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
/* ****************************************************************************
*
* 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.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Scripting.Runtime;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("_codecs", typeof(IronPython.Modules.PythonCodecs))]
namespace IronPython.Modules {
public static class PythonCodecs {
public const string __doc__ = "Provides access to various codecs (ASCII, UTF7, UTF8, etc...)";
internal const int EncoderIndex = 0;
internal const int DecoderIndex = 1;
internal const int StreamReaderIndex = 2;
internal const int StreamWriterIndex = 3;
#region ASCII Encoding
public static object ascii_decode(object input) {
return ascii_decode(input, "strict");
}
public static object ascii_decode(object input, string errors) {
return DoDecode(PythonAsciiEncoding.Instance, input, errors, true);
}
public static object ascii_encode(object input) {
return ascii_encode(input, "strict");
}
public static object ascii_encode(object input, string errors) {
return DoEncode(PythonAsciiEncoding.Instance, input, errors);
}
#endregion
/// <summary>
/// Creates an optimized encoding mapping that can be consumed by an optimized version of charmap_encode.
/// </summary>
public static EncodingMap charmap_build(string decoding_table) {
if (decoding_table.Length != 256) {
throw PythonOps.TypeError("charmap_build expected 256 character string");
}
EncodingMap map = new EncodingMap();
for (int i = 0; i < decoding_table.Length; i++) {
map.Mapping[(int)decoding_table[i]] = (char)i;
}
return map;
}
/// <summary>
/// Encodes the input string with the specified optimized encoding map.
/// </summary>
public static PythonTuple charmap_encode(CodeContext context, [BytesConversion]string input, string errors, [NotNull]EncodingMap map) {
return CharmapDecodeWorker(context, input, errors, new EncodingMapEncoding(map, errors), false);
}
public static PythonTuple charmap_encode(CodeContext context, [BytesConversion]string input, string errors = "strict", IDictionary<object, object> map = null) {
Encoding e = map != null ? new CharmapEncoding(map, errors) : null;
return CharmapDecodeWorker(context, input, errors, e, false);
}
/// <summary>
/// Decodes the input string using the provided string mapping.
/// </summary>
public static PythonTuple charmap_decode(CodeContext context, [BytesConversion]string input, string errors, [NotNull]string map) {
EncodingMap m = new EncodingMap();
for (int i = 0; i < map.Length; i++) {
m.Mapping[(int)map[i]] = (char)i;
}
return CharmapDecodeWorker(context, input, errors, new EncodingMapEncoding(m, errors), true);
}
public static PythonTuple charmap_decode(CodeContext context, [BytesConversion]string input, string errors="strict", IDictionary<object, object> map=null) {
Encoding e = map != null ? new CharmapEncoding(map, errors) : null;
return CharmapDecodeWorker(context, input, errors, e, true);
}
private static PythonTuple CharmapDecodeWorker(CodeContext context, string input, string errors, Encoding e, bool isDecode) {
if (input.Length == 0) {
return PythonTuple.MakeTuple(String.Empty, 0);
}
string encoding = "charmap";
// default to latin-1 if an encoding is not specified
if (e == null) {
e = Encoding.GetEncoding("iso-8859-1");
encoding = "latin-1";
}
string res = isDecode ? StringOps.DoDecode(context, input, errors, encoding, e) : StringOps.DoEncode(context, input, errors, encoding, e).ToString();
return PythonTuple.MakeTuple(res, res.Length);
}
public static object decode(CodeContext/*!*/ context, object obj, string encoding=null, string errors="strict") {
if(encoding == null) {
encoding = context.LanguageContext.DefaultEncoding.EncodingName;
}
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, errors), 0);
}
public static object encode(CodeContext/*!*/ context, object obj, string encoding=null, string errors="strict") {
if (encoding == null) {
encoding = context.LanguageContext.DefaultEncoding.EncodingName;
}
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, errors), 0);
}
public static object escape_decode(string text, string errors="strict") {
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\') {
if (i == text.Length - 1) throw PythonOps.ValueError("\\ at end of string");
switch (text[++i]) {
case 'a': res.Append((char)0x07); break;
case 'b': res.Append((char)0x08); break;
case 't': res.Append('\t'); break;
case 'n': res.Append('\n'); break;
case 'r': res.Append('\r'); break;
case '\\': res.Append('\\'); break;
case 'f': res.Append((char)0x0c); break;
case 'v': res.Append((char)0x0b); break;
case '\n': break;
case 'x':
int dig1, dig2;
if (i >= text.Length - 2 || !CharToInt(text[i], out dig1) || !CharToInt(text[i + 1], out dig2)) {
switch (errors) {
case "strict":
if (i >= text.Length - 2) {
throw PythonOps.ValueError("invalid character value");
} else {
throw PythonOps.ValueError("invalid hexadecimal digit");
}
case "replace":
res.Append("?");
i--;
while (i < (text.Length - 1)) {
res.Append(text[i++]);
}
continue;
default:
throw PythonOps.ValueError("decoding error; unknown error handling code: " + errors);
}
}
res.Append(dig1 * 16 + dig2);
i += 2;
break;
default:
res.Append("\\" + text[i]);
break;
}
} else {
res.Append(text[i]);
}
}
return PythonTuple.MakeTuple(res.ToString(), text.Length);
}
private static bool CharToInt(char ch, out int val) {
if (Char.IsDigit(ch)) {
val = ch - '0';
return true;
}
ch = Char.ToUpper(ch);
if (ch >= 'A' && ch <= 'F') {
val = ch - 'A' + 10;
return true;
}
val = 0;
return false;
}
public static PythonTuple/*!*/ escape_encode(string text, string errors="strict") {
StringBuilder res = new StringBuilder();
for (int i = 0; i < text.Length; i++) {
switch (text[i]) {
case '\n': res.Append("\\n"); break;
case '\r': res.Append("\\r"); break;
case '\t': res.Append("\\t"); break;
case '\\': res.Append("\\\\"); break;
case '\'': res.Append("\\'"); break;
default:
if (text[i] < 0x20 || text[i] >= 0x7f) {
res.AppendFormat("\\x{0:x2}", (int)text[i]);
} else {
res.Append(text[i]);
}
break;
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
#region Latin-1 Functions
public static object latin_1_decode(object input) {
return latin_1_decode(input, "strict");
}
public static object latin_1_decode(object input, string errors) {
return DoDecode(Encoding.GetEncoding("iso-8859-1"), input, errors);
}
public static object latin_1_encode(object input) {
return latin_1_encode(input, "strict");
}
public static object latin_1_encode(object input, string errors) {
return DoEncode(Encoding.GetEncoding("iso-8859-1"), input, errors);
}
#endregion
public static PythonTuple lookup(CodeContext/*!*/ context, string encoding) {
return PythonOps.LookupEncoding(context, encoding);
}
[LightThrowing]
public static object lookup_error(CodeContext/*!*/ context, string name) {
return PythonOps.LookupEncodingError(context, name);
}
#if FEATURE_ENCODING && FEATURE_WINDOWS
#region MBCS Functions
public static PythonTuple mbcs_decode(CodeContext/*!*/ context, string input, string errors="strict", bool ignored=false) {
return PythonTuple.MakeTuple(
StringOps.decode(context, input, Encoding.Default, errors),
Builtin.len(input)
);
}
public static PythonTuple mbcs_encode(CodeContext/*!*/ context, string input, string errors="strict") {
return PythonTuple.MakeTuple(
StringOps.encode(context, input, Encoding.Default, errors),
Builtin.len(input)
);
}
#endregion
#endif
public static PythonTuple raw_unicode_escape_decode(CodeContext/*!*/ context, object input, string errors="strict") {
return PythonTuple.MakeTuple(
StringOps.decode(context, Converter.ConvertToString(input), "raw-unicode-escape", errors),
Builtin.len(input)
);
}
public static PythonTuple raw_unicode_escape_encode(CodeContext/*!*/ context, object input, string errors="strict") {
return PythonTuple.MakeTuple(
StringOps.encode(context, Converter.ConvertToString(input), "raw-unicode-escape", errors),
Builtin.len(input)
);
}
public static PythonTuple readbuffer_encode([BytesConversion]string input, string errors=null) {
return PythonTuple.MakeTuple(input, input.Length);
}
public static void register(CodeContext/*!*/ context, object search_function) {
PythonOps.RegisterEncoding(context, search_function);
}
public static void register_error(CodeContext/*!*/ context, string name, object handler) {
PythonOps.RegisterEncodingError(context, name, handler);
}
#region Unicode Escape Encoding
public static PythonTuple unicode_escape_decode(string input) {
throw PythonOps.NotImplementedError("unicode_escape_decode");
}
public static PythonTuple unicode_escape_encode(string input) {
throw PythonOps.NotImplementedError("unicode_escape_encode");
}
public static PythonTuple unicode_internal_decode(object input, [Optional]string errors) {
return utf_16_decode(input, errors, false);
}
public static PythonTuple unicode_internal_encode(object input, [Optional]string errors) {
// length consumed is returned in bytes and for a UTF-16 string that is 2 bytes per char
PythonTuple res = DoEncode(Encoding.Unicode, input, errors, false);
return PythonTuple.MakeTuple(
res[0],
((int)res[1]) * 2
);
}
#endregion
#region Utf-16 Big Endian Functions
public static PythonTuple utf_16_be_decode(object input) {
return utf_16_be_decode(input, "strict", false);
}
public static PythonTuple utf_16_be_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.BigEndianUnicode, input, errors);
}
public static PythonTuple utf_16_be_encode(object input) {
return utf_16_be_encode(input, "strict");
}
public static PythonTuple utf_16_be_encode(object input, string errors) {
return DoEncode(Encoding.BigEndianUnicode, input, errors);
}
#endregion
#region Utf-16 Functions
public static PythonTuple utf_16_decode(object input) {
return utf_16_decode(input, "strict", false);
}
public static PythonTuple utf_16_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.Unicode, input, errors);
}
public static PythonTuple utf_16_encode(object input) {
return utf_16_encode(input, "strict");
}
public static PythonTuple utf_16_encode(object input, string errors) {
return DoEncode(Encoding.Unicode, input, errors, true);
}
#endregion
public static PythonTuple utf_16_ex_decode(object input, [Optional]string errors) {
return utf_16_ex_decode(input, errors, null, null);
}
public static PythonTuple utf_16_ex_decode(object input, string errors, object unknown1, object unknown2) {
byte[] lePre = Encoding.Unicode.GetPreamble();
byte[] bePre = Encoding.BigEndianUnicode.GetPreamble();
string instr = Converter.ConvertToString(input);
bool match = true;
if (instr.Length > lePre.Length) {
for (int i = 0; i < lePre.Length; i++) {
if ((byte)instr[i] != lePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, lePre.Length, -1);
}
match = true;
}
if (instr.Length > bePre.Length) {
for (int i = 0; i < bePre.Length; i++) {
if ((byte)instr[i] != bePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, bePre.Length, 1);
}
}
PythonTuple res = utf_16_decode(input, errors, false) as PythonTuple;
return PythonTuple.MakeTuple(res[0], res[1], 0);
}
#region Utf-16 Le Functions
public static PythonTuple utf_16_le_decode(object input) {
return utf_16_le_decode(input, "strict", false);
}
public static PythonTuple utf_16_le_decode(object input, string errors, [Optional]bool ignored) {
return utf_16_decode(input, errors, false);
}
public static PythonTuple utf_16_le_encode(object input) {
return utf_16_le_encode(input, "strict");
}
public static PythonTuple utf_16_le_encode(object input, string errors) {
return DoEncode(Encoding.Unicode, input, errors);
}
#endregion
#region Utf-7 Functions
#if FEATURE_ENCODING
public static PythonTuple utf_7_decode(object input) {
return utf_7_decode(input, "strict", false);
}
public static PythonTuple utf_7_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.UTF7, input, errors);
}
public static PythonTuple utf_7_encode(object input) {
return utf_7_encode(input, "strict");
}
public static PythonTuple utf_7_encode(object input, string errors) {
return DoEncode(Encoding.UTF7, input, errors);
}
#endif
#endregion
#region Utf-8 Functions
public static PythonTuple utf_8_decode(object input) {
return utf_8_decode(input, "strict", false);
}
public static PythonTuple utf_8_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(Encoding.UTF8, input, errors);
}
public static PythonTuple utf_8_encode(object input) {
return utf_8_encode(input, "strict");
}
public static PythonTuple utf_8_encode(object input, string errors) {
return DoEncode(Encoding.UTF8, input, errors);
}
#endregion
#if FEATURE_ENCODING
#region Utf-32 Functions
public static PythonTuple utf_32_decode(object input) {
return utf_32_decode(input, "strict");
}
public static PythonTuple utf_32_decode(object input, string errors) {
return DoDecode(Encoding.UTF32, input, errors);
}
public static PythonTuple utf_32_encode(object input) {
return utf_32_encode(input, "strict");
}
public static PythonTuple utf_32_encode(object input, string errors) {
return DoEncode(Encoding.UTF32, input, errors, true);
}
#endregion
public static PythonTuple utf_32_ex_decode(object input, [Optional]string errors) {
return utf_32_ex_decode(input, errors, null, null);
}
public static PythonTuple utf_32_ex_decode(object input, string errors, object unknown1, object unknown2) {
byte[] lePre = Encoding.UTF32.GetPreamble();
string instr = Converter.ConvertToString(input);
bool match = true;
if (instr.Length > lePre.Length) {
for (int i = 0; i < lePre.Length; i++) {
if ((byte)instr[i] != lePre[i]) {
match = false;
break;
}
}
if (match) {
return PythonTuple.MakeTuple(String.Empty, lePre.Length, -1);
}
}
PythonTuple res = utf_32_decode(input, errors) as PythonTuple;
return PythonTuple.MakeTuple(res[0], res[1], 0);
}
#region Utf-32 Le Functions
public static PythonTuple utf_32_le_decode(object input) {
return utf_32_le_decode(input, "strict", false);
}
public static PythonTuple utf_32_le_decode(object input, string errors, [Optional]bool ignored) {
return utf_32_decode(input, errors);
}
public static PythonTuple utf_32_le_encode(object input) {
return utf_32_le_encode(input, "strict");
}
public static PythonTuple utf_32_le_encode(object input, string errors) {
return DoEncode(Encoding.UTF32, input, errors);
}
#endregion
#region Utf-32 Be Functions
private static Encoding utf32BeEncoding = null;
private static Encoding UTF32BE {
get {
if (utf32BeEncoding == null) utf32BeEncoding = new UTF32Encoding(true, true);
return utf32BeEncoding;
}
}
public static PythonTuple utf_32_be_decode(object input) {
return utf_32_be_decode(input, "strict", false);
}
public static PythonTuple utf_32_be_decode(object input, string errors, [Optional]bool ignored) {
return DoDecode(UTF32BE, input, errors);
}
public static PythonTuple utf_32_be_encode(object input) {
return utf_32_be_encode(input, "strict");
}
public static PythonTuple utf_32_be_encode(object input, string errors) {
return DoEncode(UTF32BE, input, errors);
}
#endregion
#endif
#region Private implementation
private static PythonTuple DoDecode(Encoding encoding, object input, string errors) {
return DoDecode(encoding, input, errors, false);
}
private static PythonTuple DoDecode(Encoding encoding, object input, string errors, bool fAlwaysThrow) {
// input should be character buffer of some form...
string res;
if (!Converter.TryConvertToString(input, out res)) {
Bytes tempBytes = input as Bytes;
if (tempBytes == null) {
throw PythonOps.TypeErrorForBadInstance("argument 1 must be string, got {0}", input);
} else {
res = tempBytes.ToString();
}
}
int preOffset = CheckPreamble(encoding, res);
byte[] bytes = new byte[res.Length - preOffset];
for (int i = 0; i < bytes.Length; i++) {
bytes[i] = (byte)res[i + preOffset];
}
#if FEATURE_ENCODING // DecoderFallback
encoding = (Encoding)encoding.Clone();
ExceptionFallBack fallback = null;
if (fAlwaysThrow) {
encoding.DecoderFallback = DecoderFallback.ExceptionFallback;
} else {
fallback = (encoding is UTF8Encoding && DotNet) ?
// This is a workaround for a bug, see ExceptionFallbackBufferUtf8DotNet
// for more details.
new ExceptionFallBackUtf8DotNet(bytes):
new ExceptionFallBack(bytes);
encoding.DecoderFallback = fallback;
}
#endif
string decoded = encoding.GetString(bytes, 0, bytes.Length);
int badByteCount = 0;
#if FEATURE_ENCODING // DecoderFallback
if (!fAlwaysThrow) {
byte[] badBytes = fallback.buffer.badBytes;
if (badBytes != null) {
badByteCount = badBytes.Length;
}
}
#endif
PythonTuple tuple = PythonTuple.MakeTuple(decoded, bytes.Length - badByteCount);
return tuple;
}
internal static readonly bool DotNet;
static PythonCodecs() {
DotNet = Type.GetType("Mono.Runtime") == null;
}
private static int CheckPreamble(Encoding enc, string buffer) {
byte[] preamble = enc.GetPreamble();
if (preamble.Length != 0 && buffer.Length >= preamble.Length) {
bool hasPreamble = true;
for (int i = 0; i < preamble.Length; i++) {
if (preamble[i] != (byte)buffer[i]) {
hasPreamble = false;
break;
}
}
if (hasPreamble) {
return preamble.Length;
}
}
return 0;
}
private static PythonTuple DoEncode(Encoding encoding, object input, string errors) {
return DoEncode(encoding, input, errors, false);
}
private static PythonTuple DoEncode(Encoding encoding, object input, string errors, bool includePreamble) {
// input should be some Unicode object
string res;
if (Converter.TryConvertToString(input, out res)) {
StringBuilder sb = new StringBuilder();
encoding = (Encoding)encoding.Clone();
#if FEATURE_ENCODING // EncoderFallback
encoding.EncoderFallback = EncoderFallback.ExceptionFallback;
#endif
if (includePreamble) {
byte[] preamble = encoding.GetPreamble();
for (int i = 0; i < preamble.Length; i++) {
sb.Append((char)preamble[i]);
}
}
byte[] bytes = encoding.GetBytes(res);
for (int i = 0; i < bytes.Length; i++) {
sb.Append((char)bytes[i]);
}
return PythonTuple.MakeTuple(sb.ToString(), res.Length);
}
throw PythonOps.TypeErrorForBadInstance("cannot decode {0}", input);
}
#endregion
}
/// <summary>
/// Optimized encoding mapping that can be consumed by charmap_encode.
/// </summary>
[PythonHidden]
public class EncodingMap {
internal Dictionary<int, char> Mapping = new Dictionary<int, char>();
}
#if FEATURE_ENCODING // Encoding
class EncodingMapEncoding : Encoding {
private EncodingMap _map;
private string _errors;
public EncodingMapEncoding(EncodingMap map, string errors) {
_map = map;
_errors = errors;
}
public override int GetByteCount(char[] chars, int index, int count) {
int byteCount = 0;
int charEnd = index + count;
while (index < charEnd) {
char val;
char c = chars[index];
if (!_map.Mapping.TryGetValue(c, out val)) {
EncoderFallbackBuffer efb = EncoderFallback.CreateFallbackBuffer();
if (efb.Fallback(c, index)) {
byteCount += efb.Remaining;
}
} else {
byteCount++;
}
index++;
}
return byteCount;
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) {
int charEnd = charIndex + charCount;
int outputBytes = 0;
while (charIndex < charEnd) {
char c = chars[charIndex];
char val;
if (!_map.Mapping.TryGetValue((int)c, out val)) {
EncoderFallbackBuffer efb = EncoderFallback.CreateFallbackBuffer();
if (efb.Fallback(c, charIndex)) {
while (efb.Remaining != 0) {
bytes[byteIndex++] = (byte)_map.Mapping[(int)efb.GetNextChar()];
outputBytes++;
}
}
} else {
bytes[byteIndex++] = (byte)val;
outputBytes++;
}
charIndex++;
}
return outputBytes;
}
public override int GetCharCount(byte[] bytes, int index, int count) {
int byteEnd = index + count;
int outputChars = 0;
while (index < byteEnd) {
byte b = bytes[index];
char val;
if (!_map.Mapping.TryGetValue(b, out val)) {
DecoderFallbackBuffer dfb = DecoderFallback.CreateFallbackBuffer();
if (dfb.Fallback(new[] { b }, 0)) {
outputChars += dfb.Remaining;
}
} else {
outputChars++;
}
index++;
}
return outputChars;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) {
int byteEnd = byteIndex + byteCount;
int outputChars = 0;
while (byteIndex < byteEnd) {
byte b = bytes[byteIndex];
char val;
if (!_map.Mapping.TryGetValue(b, out val)) {
DecoderFallbackBuffer dfb = DecoderFallback.CreateFallbackBuffer();
if (dfb.Fallback(new[] { b }, 0)) {
while (dfb.Remaining != 0) {
chars[charIndex++] = (char)((int)_map.Mapping[(int)dfb.GetNextChar()]);
outputChars++;
}
}
} else {
chars[charIndex++] = val;
outputChars++;
}
byteIndex++;
}
return outputChars;
}
public override int GetMaxByteCount(int charCount) {
// TODO: revisit
return charCount * 4;
}
public override int GetMaxCharCount(int byteCount) {
// TODO: revisit
return byteCount;
}
}
class CharmapEncoding : Encoding {
private IDictionary<object, object> _map;
private string _errors;
public CharmapEncoding(IDictionary<object, object> map, string errors) {
_map = map;
_errors = errors;
FixupMap();
}
private void FixupMap() {
// this is required if someone passes in a mapping like { 'a' : None }
foreach(var k in _map) {
if(k.Key is string) {
var s = (string)k.Key;
if(s.Length == 1)
_map[(int)s[0]] = k.Value;
}
}
}
public override int GetByteCount(char[] chars, int index, int count) {
int byteCount = 0;
int charEnd = index + count;
while (index < charEnd) {
char c = chars[index];
object val;
object charObj = (int)c;
if (!_map.TryGetValue(charObj, out val) || (val == null && _errors == "strict")) {
EncoderFallbackBuffer efb = EncoderFallback.CreateFallbackBuffer();
if (efb.Fallback(c, index)) {
byteCount += efb.Remaining;
}
} else if(val == null) {
throw PythonOps.UnicodeEncodeError("charmap", c, index, "'charmap' codec can't encode character u'\\x{0:x}' in position {1}: character maps to <undefined>", (int)c, index);
} else if (val is string) {
byteCount += ((string)val).Length;
} else if(val is int) {
byteCount++;
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
index++;
}
return byteCount;
}
public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) {
int charEnd = charIndex + charCount;
int outputBytes = 0;
while(charIndex < charEnd) {
char c = chars[charIndex];
object val;
object obj = (int)c;
if (!_map.TryGetValue(obj, out val) || (val == null && _errors == "strict")) {
EncoderFallbackBuffer efb = EncoderFallback.CreateFallbackBuffer();
if (efb.Fallback(c, charIndex)) {
while (efb.Remaining != 0) {
obj = (int)efb.GetNextChar();
bytes[byteIndex++] = (byte)((int)_map[obj]);
outputBytes++;
}
}
} else if(val == null) {
throw PythonOps.UnicodeEncodeError("charmap", c, charIndex, "'charmap' codec can't encode character u'\\x{0:x}' in position {1}: character maps to <undefined>", (int)c, charIndex);
} else if (val is string) {
string v = val as string;
for (int i = 0; i < v.Length; i++) {
bytes[byteIndex++] = (byte)v[i];
outputBytes++;
}
} else if(val is int) {
bytes[byteIndex++] = (byte)(int)val;
outputBytes++;
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
charIndex++;
}
return outputBytes;
}
public override int GetCharCount(byte[] bytes, int index, int count) {
int byteEnd = index + count;
int outputChars = 0;
while (index < byteEnd) {
byte b = bytes[index];
object val;
object byteObj = ScriptingRuntimeHelpers.Int32ToObject((int)b);
if (!_map.TryGetValue(byteObj, out val) || val == null) {
DecoderFallbackBuffer dfb = DecoderFallback.CreateFallbackBuffer();
if (dfb.Fallback(new[] { b }, 0)) {
outputChars += dfb.Remaining;
}
} else if (val is string) {
outputChars += ((string)val).Length;
} else if(val is int) {
outputChars++;
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
index++;
}
return outputChars;
}
public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) {
int byteEnd = byteIndex + byteCount;
int outputChars = 0;
while (byteIndex < byteEnd) {
byte b = bytes[byteIndex];
object val;
object obj = ScriptingRuntimeHelpers.Int32ToObject((int)b);
if (!_map.TryGetValue(obj, out val) || val == null) {
DecoderFallbackBuffer dfb = DecoderFallback.CreateFallbackBuffer();
if (dfb.Fallback(new[] { b }, 0)) {
while (dfb.Remaining != 0) {
chars[charIndex++] = dfb.GetNextChar();
outputChars++;
}
}
} else if (val is string) {
string v = val as string;
for (int i = 0; i < v.Length; i++) {
chars[charIndex++] = v[i];
outputChars++;
}
} else if (val is int) {
chars[charIndex++] = (char)(int)val;
outputChars++;
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
byteIndex++;
}
return outputChars;
}
public override int GetMaxByteCount(int charCount) {
// TODO: revisit
return charCount * 4;
}
public override int GetMaxCharCount(int byteCount) {
// TODO: revisit
return byteCount;
}
}
class ExceptionFallBack : DecoderFallback {
internal ExceptionFallbackBuffer buffer;
// This ctor can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
protected ExceptionFallBack() {
}
public ExceptionFallBack(byte[] bytes) {
buffer = new ExceptionFallbackBuffer(bytes);
}
public override DecoderFallbackBuffer CreateFallbackBuffer() {
return buffer;
}
public override int MaxCharCount {
get { return 100; }
}
}
class ExceptionFallbackBuffer : DecoderFallbackBuffer {
internal byte[] badBytes;
protected byte[] inputBytes;
public ExceptionFallbackBuffer(byte[] bytes) {
inputBytes = bytes;
}
public override bool Fallback(byte[] bytesUnknown, int index) {
if (index > 0 && index + bytesUnknown.Length != inputBytes.Length) {
throw PythonOps.UnicodeDecodeError(
String.Format("failed to decode bytes at index: {0}", index), bytesUnknown, index);
}
// just some bad bytes at the end
badBytes = bytesUnknown;
return false;
}
public override char GetNextChar() {
return ' ';
}
public override bool MovePrevious() {
return false;
}
public override int Remaining {
get { return 0; }
}
}