/
_codecs.cs
848 lines (678 loc) · 31.2 KB
/
_codecs.cs
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
/* ****************************************************************************
*
* 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
* dlr@microsoft.com. 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>
/// Optimied encoding mapping that can be consumed by charmap_encode.
/// </summary>
[PythonHidden]
public class EncodingMap {
internal Dictionary<int, char> Mapping = new Dictionary<int, char>();
}
/// <summary>
/// Decodes the input string using the provided string mapping.
/// </summary>
public static PythonTuple charmap_decode([BytesConversion]string input, string errors, [NotNull]string map) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < input.Length; i++) {
var charIndex = (int)input[i];
if (map.Length <= charIndex) {
if (errors == "strict") {
throw PythonOps.UnicodeDecodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else {
res.Append(map[input[i]]);
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
/// <summary>
/// Encodes the input string with the specified optimized encoding map.
/// </summary>
public static PythonTuple charmap_encode([BytesConversion]string input, string errors, [NotNull]EncodingMap map) {
StringBuilder res = new StringBuilder();
var dict = map.Mapping;
for (int i = 0; i < input.Length; i++) {
char val;
if (!dict.TryGetValue(input[i], out val)) {
if (errors == "strict") {
throw PythonOps.UnicodeEncodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else {
res.Append(val);
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
public static object charbuffer_encode(string input) {
throw PythonOps.NotImplementedError("charbuffer_encode");
}
public static object charmap_decode([BytesConversion]string input, [Optional]string errors, [Optional]IDictionary<object, object> map) {
return CharmapDecodeWorker(input, errors, map, true);
}
private static object CharmapDecodeWorker(string input, string errors, IDictionary<object, object> map, bool isDecode) {
if (input.Length == 0) {
return PythonTuple.MakeTuple(String.Empty, 0);
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < input.Length; i++) {
object val;
if (map == null) {
res.Append(input[i]);
continue;
}
object charObj = ScriptingRuntimeHelpers.Int32ToObject((int)input[i]);
if (!map.TryGetValue(charObj, out val)) {
if (errors == "strict" && isDecode) {
throw PythonOps.UnicodeDecodeError("failed to find key in mapping");
} else if (!isDecode) {
throw PythonOps.UnicodeEncodeError("failed to find key in mapping");
}
res.Append("\ufffd");
} else if (val == null) {
if (errors == "strict" && isDecode) {
throw PythonOps.UnicodeDecodeError("'charmap' codec can't decode characters at index {0} because charmap maps to None", i);
} else if (!isDecode) {
throw PythonOps.UnicodeEncodeError("charmap", input[i], i,
"'charmap' codec can't encode characters at index {0} because charmap maps to None", i);
}
res.Append("\ufffd");
} else if (val is string) {
res.Append((string)val);
} else if (val is int) {
res.Append((char)(int)val);
} else {
throw PythonOps.TypeError("charmap must be an int, str, or None");
}
}
return PythonTuple.MakeTuple(res.ToString(), res.Length);
}
public static object charmap_encode([BytesConversion]string input, string errors="strict", IDictionary<object, object> map=null) {
return CharmapDecodeWorker(input, errors, map, false);
}
public static object decode(CodeContext/*!*/ context, object obj) {
PythonTuple t = lookup(context, PythonContext.GetContext(context).GetDefaultEncodingName());
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, null), 0);
}
public static object decode(CodeContext/*!*/ context, object obj, string encoding) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[DecoderIndex], obj, null), 0);
}
public static object decode(CodeContext/*!*/ context, object obj, string encoding, string errors) {
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) {
PythonTuple t = lookup(context, PythonContext.GetContext(context).GetDefaultEncodingName());
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, null), 0);
}
public static object encode(CodeContext/*!*/ context, object obj, string encoding) {
PythonTuple t = lookup(context, encoding);
return PythonOps.GetIndex(context, PythonCalls.Call(context, t[EncoderIndex], obj, null), 0);
}
public static object encode(CodeContext/*!*/ context, object obj, string encoding, string errors) {
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(), ScriptingRuntimeHelpers.Int32ToObject(res.Length));
}
#region Latin-1 Functions
#if !SILVERLIGHT
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);
}
#endif
#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
#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 object readbuffer_encode(string input) {
throw PythonOps.NotImplementedError("readbuffer_encode");
}
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
}
#if FEATURE_ENCODING // Encoding
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; }
}
}
// This class can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
class ExceptionFallBackUtf8DotNet : ExceptionFallBack {
public ExceptionFallBackUtf8DotNet(byte[] bytes) {
buffer = new ExceptionFallbackBufferUtf8DotNet(bytes);
}
}
// This class can be removed as soon as workaround for utf8 encoding in .net is
// no longer necessary.
class ExceptionFallbackBufferUtf8DotNet : ExceptionFallbackBuffer {
private bool ignoreNext = false;
public ExceptionFallbackBufferUtf8DotNet(byte[] bytes) : base(bytes) {
}
public override bool Fallback(byte[] bytesUnknown, int index) {
// In case of dot net and utf-8 value of index does not conform to documentation provided by
// Microsoft http://msdn.microsoft.com/en-us/library/bdftay9c%28v=vs.100%29.aspx
// The value of index is mysteriously decreased by the size of bytesUnknown
// Tested on Windows 7 64, .NET 4.0.30319.18408, all recommended patches as of 06.02.2014
if (ignoreNext) {
// dot net sometimes calls second time after this method returns false
// if this is the case, do nothing
return false;
}
// adjust index
index = index + bytesUnknown.Length;
ignoreNext = true;
return base.Fallback(bytesUnknown, index);
}
}
#endif
}