/
UnicodeEncoding.cs
1836 lines (1549 loc) · 85.2 KB
/
UnicodeEncoding.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
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 MIT license.
//
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
// This define can be used to turn off the fast loops. Useful for finding whether
// the problem is fastloop-specific.
#define FASTLOOP
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System.Text
{
public class UnicodeEncoding : Encoding
{
// Used by Encoding.BigEndianUnicode/Unicode for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UnicodeEncoding s_bigEndianDefault = new UnicodeEncoding(bigEndian: true, byteOrderMark: true);
internal static readonly UnicodeEncoding s_littleEndianDefault = new UnicodeEncoding(bigEndian: false, byteOrderMark: true);
private readonly bool isThrowException;
private readonly bool bigEndian;
private readonly bool byteOrderMark;
// Unicode version 2.0 character size in bytes
public const int CharSize = 2;
public UnicodeEncoding()
: this(false, true)
{
}
public UnicodeEncoding(bool bigEndian, bool byteOrderMark)
: base(bigEndian ? 1201 : 1200) // Set the data item.
{
this.bigEndian = bigEndian;
this.byteOrderMark = byteOrderMark;
}
public UnicodeEncoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes)
: this(bigEndian, byteOrderMark)
{
this.isThrowException = throwOnInvalidBytes;
// Encoding constructor already did this, but it'll be wrong if we're throwing exceptions
if (this.isThrowException)
SetDefaultFallbacks();
}
internal sealed override void SetDefaultFallbacks()
{
// For UTF-X encodings, we use a replacement fallback with an empty string
if (this.isThrowException)
{
this.encoderFallback = EncoderFallback.ExceptionFallback;
this.decoderFallback = DecoderFallback.ExceptionFallback;
}
else
{
this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
}
}
// The following methods are copied from EncodingNLS.cs.
// Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here.
// These should be kept in sync for the following classes:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
//
// Returns the number of bytes required to encode a range of characters in
// a character array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(char[] chars, int index, int count)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input, return 0, avoid fixed empty array problem
if (count == 0)
return 0;
// Just call the pointer version
fixed (char* pChars = chars)
return GetByteCount(pChars + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetByteCount(string s)
{
if (s is null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
}
fixed (char* pChars = s)
return GetByteCount(pChars, s.Length, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentOutOfRangeException.ThrowIfNegative(count);
// Call it with empty encoder
return GetByteCount(chars, count, null);
}
// Parent method is safe.
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
public override unsafe int GetBytes(string s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(s);
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(charIndex);
ArgumentOutOfRangeException.ThrowIfNegative(charCount);
if (s.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. An exception occurs if the byte array is not large
// enough to hold the complete encoding of the characters. The
// GetByteCount method can be used to determine the exact number of
// bytes that will be produced for a given range of characters.
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(charIndex);
ArgumentOutOfRangeException.ThrowIfNegative(charCount);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
// If nothing to encode return 0, avoid fixed problem
if (charCount == 0)
return 0;
// Just call pointer version
int byteCount = bytes.Length - byteIndex;
fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes))
// Remember that byteCount is # to decode, not size of array.
return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
ArgumentNullException.ThrowIfNull(chars);
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(charCount);
ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
// If no input just return 0, fixed doesn't like 0 length arrays
if (count == 0)
return 0;
// Just call pointer version
fixed (byte* pBytes = bytes)
return GetCharCount(pBytes + index, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(count);
return GetCharCount(bytes, count, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
ArgumentOutOfRangeException.ThrowIfNegative(byteIndex);
ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
// If no input, return 0 & avoid fixed problem
if (byteCount == 0)
return 0;
// Just call pointer version
int charCount = chars.Length - charIndex;
fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars))
// Remember that charCount is # to decode, not size of array
return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
[CLSCompliant(false)]
public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentNullException.ThrowIfNull(chars);
ArgumentOutOfRangeException.ThrowIfNegative(charCount);
ArgumentOutOfRangeException.ThrowIfNegative(byteCount);
return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
//
// All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
// So if you fix this, fix the others. Currently those include:
// EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// parent method is safe
public override unsafe string GetString(byte[] bytes, int index, int count)
{
ArgumentNullException.ThrowIfNull(bytes);
ArgumentOutOfRangeException.ThrowIfNegative(index);
ArgumentOutOfRangeException.ThrowIfNegative(count);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer);
// Avoid problems with empty input buffer
if (count == 0) return string.Empty;
fixed (byte* pBytes = bytes)
return string.CreateStringFromEncoding(
pBytes + index, count, this);
}
//
// End of standard methods copied from EncodingNLS.cs
//
internal sealed override unsafe int GetByteCount(char* chars, int count, EncoderNLS? encoder)
{
Debug.Assert(chars is not null, "[UnicodeEncoding.GetByteCount]chars!=null");
Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
// Start by assuming each char gets 2 bytes
int byteCount = count << 1;
// Check for overflow in byteCount
// (If they were all invalid chars, this would actually be wrong,
// but that's a ridiculously large # so we're not concerned about that case)
if (byteCount < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow);
char* charStart = chars;
char* charEnd = chars + count;
char charLeftOver = (char)0;
bool wasHereBefore = false;
// For fallback we may need a fallback buffer
EncoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
if (encoder is not null)
{
charLeftOver = encoder._charLeftOver;
// Assume extra bytes to encode charLeftOver if it existed
if (charLeftOver > 0)
byteCount += 2;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback?.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
}
char ch;
TryAgain:
while (((ch = (fallbackBuffer is null) ? (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, maybe we can do it fast
#if FASTLOOP
// If endianness is backwards then each pair of bytes would be backwards.
if ((bigEndian ^ BitConverter.IsLittleEndian) &&
#if TARGET_64BIT
(unchecked((long)chars) & 7) == 0 &&
#else
(unchecked((int)chars) & 3) == 0 &&
#endif
charLeftOver == 0)
{
// Need -1 to check 2 at a time. If we have an even #, longChars will go
// from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars
// will go from longEnd - 1 long to longEnd. (Might not get to use this)
ulong* longEnd = (ulong*)(charEnd - 3);
// Need new char* so we can check 4 at a time
ulong* longChars = (ulong*)chars;
while (longChars < longEnd)
{
// See if we potentially have surrogates (0x8000 bit set)
// (We're either big endian on a big endian machine or little endian on
// a little endian machine so that'll work)
if ((0x8000800080008000 & *longChars) != 0)
{
// See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
// 5 bits looks like 11011, then its a high or low surrogate.
// We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
// Note that we expect BMP characters to be more common than surrogates
// & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
ulong uTemp = (0xf800f800f800f800 & *longChars) ^ 0xd800d800d800d800;
// Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
// but no clue if they're high or low.
// If each of the 4 characters are non-zero, then none are surrogates.
if ((uTemp & 0xFFFF000000000000) == 0 ||
(uTemp & 0x0000FFFF00000000) == 0 ||
(uTemp & 0x00000000FFFF0000) == 0 ||
(uTemp & 0x000000000000FFFF) == 0)
{
// It has at least 1 surrogate, but we don't know if they're high or low surrogates,
// or if there's 1 or 4 surrogates
// If they happen to be high/low/high/low, we may as well continue. Check the next
// bit to see if its set (low) or not (high) in the right pattern
if ((0xfc00fc00fc00fc00 & *longChars) !=
(BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00))
{
// Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
// was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
// Drop out to the slow loop to resolve the surrogates
break;
}
// else they are all surrogates in High/Low/High/Low order, so we can use them.
}
// else none are surrogates, so we can use them.
}
// else all < 0x8000 so we can use them
// We already counted these four chars, go to next long.
longChars++;
}
chars = (char*)longChars;
if (chars >= charEnd)
break;
}
#endif // FASTLOOP
// No fallback, just get next char
ch = *chars;
chars++;
}
else
{
// We weren't preallocating fallback space.
byteCount += 2;
}
// Check for high or low surrogates
if (ch >= 0xd800 && ch <= 0xdfff)
{
// Was it a high surrogate?
if (ch <= 0xdbff)
{
// Its a high surrogate, if we already had a high surrogate do its fallback
if (charLeftOver > 0)
{
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
chars--;
// If previous high surrogate deallocate 2 bytes
byteCount -= 2;
// Fallback the previous surrogate
// Need to initialize fallback buffer?
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be enregistered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
// Now no high surrogate left over
charLeftOver = (char)0;
continue;
}
// Remember this high surrogate
charLeftOver = ch;
continue;
}
// Its a low surrogate
if (charLeftOver == 0)
{
// Expected a previous high surrogate.
// Don't count this one (we'll count its fallback if necessary)
byteCount -= 2;
// fallback this one
// Need to initialize fallback buffer?
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
continue;
}
// Valid surrogate pair, add our charLeftOver
charLeftOver = (char)0;
continue;
}
else if (charLeftOver > 0)
{
// Expected a low surrogate, but this char is normal
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
chars--;
// fallback previous chars
// Need to initialize fallback buffer?
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
// Ignore charLeftOver or throw
byteCount -= 2;
charLeftOver = (char)0;
continue;
}
// Ok we had something to add (already counted)
}
// Don't allocate space for left over char
if (charLeftOver > 0)
{
byteCount -= 2;
// If we have to flush, stick it in fallback and try again
if (encoder is null || encoder.MustFlush)
{
if (wasHereBefore)
{
// Throw it, using our complete character
throw new ArgumentException(
SR.Format(SR.Argument_RecursiveFallback, charLeftOver), nameof(chars));
}
else
{
// Need to initialize fallback buffer?
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
charLeftOver = (char)0;
wasHereBefore = true;
goto TryAgain;
}
}
}
// Shouldn't have anything in fallback buffer for GetByteCount
// (don't have to check _throwOnOverflow for count)
Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0,
"[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end");
// Don't remember fallbackBuffer.encoder for counting
return byteCount;
}
internal sealed override unsafe int GetBytes(
char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS? encoder)
{
Debug.Assert(chars is not null, "[UnicodeEncoding.GetBytes]chars!=null");
Debug.Assert(byteCount >= 0, "[UnicodeEncoding.GetBytes]byteCount >=0");
Debug.Assert(charCount >= 0, "[UnicodeEncoding.GetBytes]charCount >=0");
Debug.Assert(bytes is not null, "[UnicodeEncoding.GetBytes]bytes!=null");
char charLeftOver = (char)0;
char ch;
bool wasHereBefore = false;
byte* byteEnd = bytes + byteCount;
char* charEnd = chars + charCount;
byte* byteStart = bytes;
char* charStart = chars;
// For fallback we may need a fallback buffer
EncoderFallbackBuffer? fallbackBuffer = null;
char* charsForFallback;
// Get our encoder, but don't clear it yet.
if (encoder is not null)
{
charLeftOver = encoder._charLeftOver;
// We mustn't have left over fallback data when counting
if (encoder.InternalHasFallbackBuffer)
{
// We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
fallbackBuffer = encoder.FallbackBuffer;
if (fallbackBuffer.Remaining > 0 && encoder._throwOnOverflow)
throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback?.GetType()));
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
}
}
TryAgain:
while (((ch = (fallbackBuffer is null) ?
(char)0 : fallbackBuffer.InternalGetNextChar()) != 0) ||
chars < charEnd)
{
// First unwind any fallback
if (ch == 0)
{
// No fallback, maybe we can do it fast
#if FASTLOOP
// If endianness is backwards then each pair of bytes would be backwards.
if ((bigEndian ^ BitConverter.IsLittleEndian) &&
#if TARGET_64BIT
(unchecked((long)chars) & 7) == 0 &&
#else
(unchecked((int)chars) & 3) == 0 &&
#endif
charLeftOver == 0)
{
// Need -1 to check 2 at a time. If we have an even #, longChars will go
// from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars
// will go from longEnd - 1 long to longEnd. (Might not get to use this)
// We can only go iCount units (limited by shorter of char or byte buffers.
ulong* longEnd = (ulong*)(chars - 3 +
(((byteEnd - bytes) >> 1 < charEnd - chars) ?
(byteEnd - bytes) >> 1 : charEnd - chars));
// Need new char* so we can check 4 at a time
ulong* longChars = (ulong*)chars;
ulong* longBytes = (ulong*)bytes;
while (longChars < longEnd)
{
// See if we potentially have surrogates (0x8000 bit set)
// (We're either big endian on a big endian machine or little endian on
// a little endian machine so that'll work)
if ((0x8000800080008000 & *longChars) != 0)
{
// See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
// 5 bits looks like 11011, then its a high or low surrogate.
// We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
// Note that we expect BMP characters to be more common than surrogates
// & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
ulong uTemp = (0xf800f800f800f800 & *longChars) ^ 0xd800d800d800d800;
// Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
// but no clue if they're high or low.
// If each of the 4 characters are non-zero, then none are surrogates.
if ((uTemp & 0xFFFF000000000000) == 0 ||
(uTemp & 0x0000FFFF00000000) == 0 ||
(uTemp & 0x00000000FFFF0000) == 0 ||
(uTemp & 0x000000000000FFFF) == 0)
{
// It has at least 1 surrogate, but we don't know if they're high or low surrogates,
// or if there's 1 or 4 surrogates
// If they happen to be high/low/high/low, we may as well continue. Check the next
// bit to see if its set (low) or not (high) in the right pattern
if ((0xfc00fc00fc00fc00 & *longChars) !=
(BitConverter.IsLittleEndian ? (ulong)0xdc00d800dc00d800 : (ulong)0xd800dc00d800dc00))
{
// Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
// was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
// Drop out to the slow loop to resolve the surrogates
break;
}
// else they are all surrogates in High/Low/High/Low order, so we can use them.
}
// else none are surrogates, so we can use them.
}
// else all < 0x8000 so we can use them
// We can use these 4 chars.
Unsafe.WriteUnaligned(longBytes, *longChars);
longChars++;
longBytes++;
}
chars = (char*)longChars;
bytes = (byte*)longBytes;
if (chars >= charEnd)
break;
}
#endif // FASTLOOP
// No fallback, just get next char
ch = *chars;
chars++;
}
// Check for high or low surrogates
if (ch >= 0xd800 && ch <= 0xdfff)
{
// Was it a high surrogate?
if (ch <= 0xdbff)
{
// Its a high surrogate, see if we already had a high surrogate
if (charLeftOver > 0)
{
// Unwind the current character, this should be safe because we
// don't have leftover data in the fallback, so chars must have
// advanced already.
Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate");
chars--;
// Fallback the previous surrogate
// Might need to create our fallback buffer
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
charLeftOver = (char)0;
continue;
}
// Remember this high surrogate
charLeftOver = ch;
continue;
}
// Its a low surrogate
if (charLeftOver == 0)
{
// We'll fall back this one
// Might need to create our fallback buffer
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(ch, ref charsForFallback);
chars = charsForFallback;
continue;
}
// Valid surrogate pair, add our charLeftOver
if (bytes + 3 >= byteEnd)
{
// Not enough room to add this surrogate pair
if (fallbackBuffer is not null && fallbackBuffer.bFallingBack)
{
// These must have both been from the fallbacks.
// Both of these MUST have been from a fallback because if the 1st wasn't
// from a fallback, then a high surrogate followed by an illegal char
// would've caused the high surrogate to fall back. If a high surrogate
// fell back, then it was consumed and both chars came from the fallback.
fallbackBuffer.MovePrevious(); // Didn't use either fallback surrogate
fallbackBuffer.MovePrevious();
}
else
{
// If we don't have enough room, then either we should've advanced a while
// or we should have bytes==byteStart and throw below
Debug.Assert(chars > charStart + 1 || bytes == byteStart,
"[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
chars -= 2; // Didn't use either surrogate
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
charLeftOver = (char)0; // we'll retry it later
break; // Didn't throw, but stop 'til next time.
}
if (bigEndian)
{
*(bytes++) = (byte)(charLeftOver >> 8);
*(bytes++) = (byte)charLeftOver;
}
else
{
*(bytes++) = (byte)charLeftOver;
*(bytes++) = (byte)(charLeftOver >> 8);
}
charLeftOver = (char)0;
}
else if (charLeftOver > 0)
{
// Expected a low surrogate, but this char is normal
// Rewind the current character, fallback previous character.
// this should be safe because we don't have leftover data in the
// fallback, so chars must have advanced already.
Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
chars--;
// fallback previous chars
// Might need to create our fallback buffer
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
// Ignore charLeftOver or throw
charLeftOver = (char)0;
continue;
}
// Ok, we have a char to add
if (bytes + 1 >= byteEnd)
{
// Couldn't add this char
if (fallbackBuffer is not null && fallbackBuffer.bFallingBack)
fallbackBuffer.MovePrevious(); // Not using this fallback char
else
{
// Lonely charLeftOver (from previous call) would've been caught up above,
// so this must be a case where we've already read an input char.
Debug.Assert(chars > charStart,
"[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback");
chars--; // Not using this char
}
ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
break; // didn't throw, just stop
}
if (bigEndian)
{
*(bytes++) = (byte)(ch >> 8);
*(bytes++) = (byte)ch;
}
else
{
*(bytes++) = (byte)ch;
*(bytes++) = (byte)(ch >> 8);
}
}
// Don't allocate space for left over char
if (charLeftOver > 0)
{
// If we aren't flushing we need to fall this back
if (encoder is null || encoder.MustFlush)
{
if (wasHereBefore)
{
// Throw it, using our complete character
throw new ArgumentException(
SR.Format(SR.Argument_RecursiveFallback, charLeftOver), nameof(chars));
}
else
{
// If we have to flush, stick it in fallback and try again
// Might need to create our fallback buffer
if (fallbackBuffer is null)
{
fallbackBuffer = encoder is null ?
this.encoderFallback.CreateFallbackBuffer() :
encoder.FallbackBuffer;
// Set our internal fallback interesting things.
fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
}
// If we're not flushing, that'll remember the left over character.
charsForFallback = chars; // Avoid passing chars by reference to allow it to be en-registered
fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
chars = charsForFallback;
charLeftOver = (char)0;
wasHereBefore = true;
goto TryAgain;
}
}
}
// Not flushing, remember it in the encoder
if (encoder is not null)
{
encoder._charLeftOver = charLeftOver;
encoder._charsUsed = (int)(chars - charStart);
}
// Remember charLeftOver if we must, or clear it if we're flushing
// (charLeftOver should be 0 if we're flushing)
Debug.Assert((encoder is not null && !encoder.MustFlush) || charLeftOver == (char)0,
"[UnicodeEncoding.GetBytes] Expected no left over characters if flushing");
Debug.Assert(fallbackBuffer is null || fallbackBuffer.Remaining == 0 ||
encoder is null || !encoder._throwOnOverflow,
"[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting");
return (int)(bytes - byteStart);
}
internal sealed override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS? baseDecoder)
{
Debug.Assert(bytes is not null, "[UnicodeEncoding.GetCharCount]bytes!=null");
Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
Decoder? decoder = (Decoder?)baseDecoder;
byte* byteEnd = bytes + count;
byte* byteStart = bytes;
// Need last vars
int lastByte = -1;
char lastChar = (char)0;
// Start by assuming same # of chars as bytes
int charCount = count >> 1;
// For fallback we may need a fallback buffer
DecoderFallbackBuffer? fallbackBuffer = null;
if (decoder is not null)
{
lastByte = decoder.lastByte;
lastChar = decoder.lastChar;