-
Notifications
You must be signed in to change notification settings - Fork 973
/
ByteBufferUtil.cs
1215 lines (1098 loc) · 47.5 KB
/
ByteBufferUtil.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace DotNetty.Buffers
{
using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Text;
using DotNetty.Common.Internal;
using DotNetty.Common.Internal.Logging;
using DotNetty.Common.Utilities;
public static class ByteBufferUtil
{
const char WriteUtfUnknown = '?';
static readonly int MaxBytesPerCharUtf8 = Encoding.UTF8.GetMaxByteCount(1);
static readonly IInternalLogger Logger = InternalLoggerFactory.GetInstance(typeof(ByteBufferUtil));
public static readonly IByteBufferAllocator DefaultAllocator;
static ByteBufferUtil()
{
string allocType = SystemPropertyUtil.Get("io.netty.allocator.type", "pooled");
allocType = allocType.Trim();
IByteBufferAllocator alloc;
if ("unpooled".Equals(allocType, StringComparison.OrdinalIgnoreCase))
{
alloc = UnpooledByteBufferAllocator.Default;
Logger.Debug("-Dio.netty.allocator.type: {}", allocType);
}
else if ("pooled".Equals(allocType, StringComparison.OrdinalIgnoreCase))
{
alloc = PooledByteBufferAllocator.Default;
Logger.Debug("-Dio.netty.allocator.type: {}", allocType);
}
else
{
alloc = PooledByteBufferAllocator.Default;
Logger.Debug("-Dio.netty.allocator.type: pooled (unknown: {})", allocType);
}
DefaultAllocator = alloc;
}
/// <summary>
/// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
/// of the specified buffer's sub-region.
/// </summary>
public static string HexDump(IByteBuffer buffer) => HexDump(buffer, buffer.ReaderIndex, buffer.ReadableBytes);
/// <summary>
/// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
/// of the specified buffer's sub-region.
/// </summary>
public static string HexDump(IByteBuffer buffer, int fromIndex, int length) => HexUtil.DoHexDump(buffer, fromIndex, length);
/// <summary>
/// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
/// of the specified buffer's sub-region.
/// </summary>
public static string HexDump(byte[] array) => HexDump(array, 0, array.Length);
/// <summary>
/// Returns a <a href="http://en.wikipedia.org/wiki/Hex_dump">hex dump</a>
/// of the specified buffer's sub-region.
/// </summary>
public static string HexDump(byte[] array, int fromIndex, int length) => HexUtil.DoHexDump(array, fromIndex, length);
public static bool EnsureWritableSuccess(int ensureWritableResult) => ensureWritableResult == 0 || ensureWritableResult == 2;
/// <summary>
/// Calculates the hash code of the specified buffer. This method is
/// useful when implementing a new buffer type.
/// </summary>
public static int HashCode(IByteBuffer buffer)
{
int aLen = buffer.ReadableBytes;
int intCount = (int)((uint)aLen >> 2);
int byteCount = aLen & 3;
int hashCode = 1;
int arrayIndex = buffer.ReaderIndex;
for (int i = intCount; i > 0; i--)
{
hashCode = 31 * hashCode + buffer.GetInt(arrayIndex);
arrayIndex += 4;
}
for (int i = byteCount; i > 0; i--)
{
hashCode = 31 * hashCode + buffer.GetByte(arrayIndex++);
}
if (hashCode == 0)
{
hashCode = 1;
}
return hashCode;
}
/// <summary>
/// Returns the reader index of needle in haystack, or -1 if needle is not in haystack.
/// </summary>
public static int IndexOf(IByteBuffer needle, IByteBuffer haystack)
{
// TODO: maybe use Boyer Moore for efficiency.
int attempts = haystack.ReadableBytes - needle.ReadableBytes + 1;
for (int i = 0; i < attempts; i++)
{
if (Equals(needle, needle.ReaderIndex, haystack, haystack.ReaderIndex + i, needle.ReadableBytes))
{
return haystack.ReaderIndex + i;
}
}
return -1;
}
/// <summary>
/// Returns {@code true} if and only if the two specified buffers are
/// identical to each other for {@code length} bytes starting at {@code aStartIndex}
/// index for the {@code a} buffer and {@code bStartIndex} index for the {@code b} buffer.
/// A more compact way to express this is:
/// <p />
/// {@code a[aStartIndex : aStartIndex + length] == b[bStartIndex : bStartIndex + length]}
/// </summary>
public static bool Equals(IByteBuffer a, int aStartIndex, IByteBuffer b, int bStartIndex, int length)
{
if (aStartIndex < 0 || bStartIndex < 0 || length < 0)
{
throw new ArgumentException("All indexes and lengths must be non-negative");
}
if (a.WriterIndex - length < aStartIndex || b.WriterIndex - length < bStartIndex)
{
return false;
}
int longCount = unchecked((int)((uint)length >> 3));
int byteCount = length & 7;
for (int i = longCount; i > 0; i--)
{
if (a.GetLong(aStartIndex) != b.GetLong(bStartIndex))
{
return false;
}
aStartIndex += 8;
bStartIndex += 8;
}
for (int i = byteCount; i > 0; i--)
{
if (a.GetByte(aStartIndex) != b.GetByte(bStartIndex))
{
return false;
}
aStartIndex++;
bStartIndex++;
}
return true;
}
/// <summary>
/// Returns {@code true} if and only if the two specified buffers are
/// identical to each other as described in {@link ByteBuf#equals(Object)}.
/// This method is useful when implementing a new buffer type.
/// </summary>
public static bool Equals(IByteBuffer bufferA, IByteBuffer bufferB)
{
int aLen = bufferA.ReadableBytes;
if (aLen != bufferB.ReadableBytes)
{
return false;
}
return Equals(bufferA, bufferA.ReaderIndex, bufferB, bufferB.ReaderIndex, aLen);
}
/// <summary>
/// Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}.
/// This method is useful when implementing a new buffer type.
/// </summary>
public static int Compare(IByteBuffer bufferA, IByteBuffer bufferB)
{
int aLen = bufferA.ReadableBytes;
int bLen = bufferB.ReadableBytes;
int minLength = Math.Min(aLen, bLen);
int uintCount = minLength.RightUShift(2);
int byteCount = minLength & 3;
int aIndex = bufferA.ReaderIndex;
int bIndex = bufferB.ReaderIndex;
if (uintCount > 0)
{
int uintCountIncrement = uintCount << 2;
int res = CompareUint(bufferA, bufferB, aIndex, bIndex, uintCountIncrement);
if (res != 0)
{
return res;
}
aIndex += uintCountIncrement;
bIndex += uintCountIncrement;
}
for (int aEnd = aIndex + byteCount; aIndex < aEnd; ++aIndex, ++bIndex)
{
int comp = bufferA.GetByte(aIndex) - bufferB.GetByte(bIndex);
if (comp != 0)
{
return comp;
}
}
return aLen - bLen;
}
static int CompareUint(IByteBuffer bufferA, IByteBuffer bufferB, int aIndex, int bIndex, int uintCountIncrement)
{
for (int aEnd = aIndex + uintCountIncrement; aIndex < aEnd; aIndex += 4, bIndex += 4)
{
long va = bufferA.GetUnsignedInt(aIndex);
long vb = bufferB.GetUnsignedInt(bIndex);
if (va > vb)
{
return 1;
}
if (va < vb)
{
return -1;
}
}
return 0;
}
/// <summary>
/// The default implementation of <see cref="IByteBuffer.IndexOf(int, int, byte)"/>.
/// This method is useful when implementing a new buffer type.
/// </summary>
public static int IndexOf(IByteBuffer buffer, int fromIndex, int toIndex, byte value)
{
if (fromIndex <= toIndex)
{
return FirstIndexOf(buffer, fromIndex, toIndex, value);
}
else
{
return LastIndexOf(buffer, fromIndex, toIndex, value);
}
}
/// <summary>
/// Read the given amount of bytes into a new {@link ByteBuf} that is allocated from the {@link ByteBufAllocator}.
/// </summary>
public static IByteBuffer ReadBytes(IByteBufferAllocator alloc, IByteBuffer buffer, int length)
{
bool release = true;
IByteBuffer dst = alloc.Buffer(length);
try
{
buffer.ReadBytes(dst);
release = false;
return dst;
}
finally
{
if (release)
{
dst.Release();
}
}
}
static int FirstIndexOf(IByteBuffer buffer, int fromIndex, int toIndex, byte value)
{
fromIndex = Math.Max(fromIndex, 0);
if (fromIndex >= toIndex || buffer.Capacity == 0)
{
return -1;
}
return buffer.ForEachByte(fromIndex, toIndex - fromIndex, new IndexOfProcessor(value));
}
static int LastIndexOf(IByteBuffer buffer, int fromIndex, int toIndex, byte value)
{
fromIndex = Math.Min(fromIndex, buffer.Capacity);
if (fromIndex < 0 || buffer.Capacity == 0)
{
return -1;
}
return buffer.ForEachByteDesc(toIndex, fromIndex - toIndex, new IndexOfProcessor(value));
}
public static IByteBuffer WriteUtf8(IByteBufferAllocator alloc, ICharSequence seq)
{
// UTF-8 uses max. 3 bytes per char, so calculate the worst case.
IByteBuffer buf = alloc.Buffer(Utf8MaxBytes(seq));
WriteUtf8(buf, seq);
return buf;
}
public static int WriteUtf8(IByteBuffer buf, ICharSequence seq) => ReserveAndWriteUtf8(buf, seq, Utf8MaxBytes(seq));
public static int ReserveAndWriteUtf8(IByteBuffer buf, ICharSequence seq, int reserveBytes)
{
for (;;)
{
if (buf is AbstractByteBuffer byteBuf)
{
byteBuf.EnsureWritable0(reserveBytes);
int written = WriteUtf8(byteBuf, byteBuf.WriterIndex, seq, seq.Count);
byteBuf.SetWriterIndex(byteBuf.WriterIndex + written);
return written;
}
else if (buf is WrappedByteBuffer)
{
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.Unwrap();
}
else
{
byte[] bytes = Encoding.UTF8.GetBytes(seq.ToString());
buf.WriteBytes(bytes);
return bytes.Length;
}
}
}
// Fast-Path implementation
internal static int WriteUtf8(AbstractByteBuffer buffer, int writerIndex, ICharSequence value, int len)
{
int oldWriterIndex = writerIndex;
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++)
{
char c = value[i];
if (c < 0x80)
{
buffer._SetByte(writerIndex++, (byte)c);
}
else if (c < 0x800)
{
buffer._SetByte(writerIndex++, (byte)(0xc0 | (c >> 6)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (c & 0x3f)));
}
else if (char.IsSurrogate(c))
{
if (!char.IsHighSurrogate(c))
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
continue;
}
char c2;
try
{
// Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid
// duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will
// re-throw a more informative exception describing the problem.
c2 = value[++i];
}
catch (IndexOutOfRangeException)
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
break;
}
if (!char.IsLowSurrogate(c2))
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
buffer._SetByte(writerIndex++, char.IsHighSurrogate(c2) ? WriteUtfUnknown : c2);
continue;
}
int codePoint = CharUtil.ToCodePoint(c, c2);
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630.
buffer._SetByte(writerIndex++, (byte)(0xf0 | (codePoint >> 18)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((codePoint >> 12) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((codePoint >> 6) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (codePoint & 0x3f)));
}
else
{
buffer._SetByte(writerIndex++, (byte)(0xe0 | (c >> 12)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((c >> 6) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (c & 0x3f)));
}
}
return writerIndex - oldWriterIndex;
}
public static IByteBuffer WriteUtf8(IByteBufferAllocator alloc, string value)
{
// UTF-8 uses max. 3 bytes per char, so calculate the worst case.
IByteBuffer buf = alloc.Buffer(Utf8MaxBytes(value));
WriteUtf8(buf, value);
return buf;
}
public static int WriteUtf8(IByteBuffer buf, string seq) => ReserveAndWriteUtf8(buf, seq, Utf8MaxBytes(seq));
///<summary>
/// Encode a string in http://en.wikipedia.org/wiki/UTF-8 and write it into reserveBytes of
/// a byte buffer. The reserveBytes must be computed (ie eagerly using {@link #utf8MaxBytes(string)}
/// or exactly with #utf8Bytes(string)}) to ensure this method not to not: for performance reasons
/// the index checks will be performed using just reserveBytes.
/// </summary>
/// <returns> This method returns the actual number of bytes written.</returns>
public static int ReserveAndWriteUtf8(IByteBuffer buf, string value, int reserveBytes)
{
for (;;)
{
if (buf is AbstractByteBuffer byteBuf)
{
byteBuf.EnsureWritable0(reserveBytes);
int written = WriteUtf8(byteBuf, byteBuf.WriterIndex, value, value.Length);
byteBuf.SetWriterIndex(byteBuf.WriterIndex + written);
return written;
}
else if (buf is WrappedByteBuffer)
{
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.Unwrap();
}
else
{
byte[] bytes = Encoding.UTF8.GetBytes(value);
buf.WriteBytes(bytes);
return bytes.Length;
}
}
}
// Fast-Path implementation
internal static int WriteUtf8(AbstractByteBuffer buffer, int writerIndex, string value, int len)
{
int oldWriterIndex = writerIndex;
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++)
{
char c = value[i];
if (c < 0x80)
{
buffer._SetByte(writerIndex++, (byte)c);
}
else if (c < 0x800)
{
buffer._SetByte(writerIndex++, (byte)(0xc0 | (c >> 6)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (c & 0x3f)));
}
else if (char.IsSurrogate(c))
{
if (!char.IsHighSurrogate(c))
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
continue;
}
char c2;
try
{
// Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid
// duplicate bounds checking with charAt. If an IndexOutOfBoundsException is thrown we will
// re-throw a more informative exception describing the problem.
c2 = value[++i];
}
catch (IndexOutOfRangeException)
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
break;
}
if (!char.IsLowSurrogate(c2))
{
buffer._SetByte(writerIndex++, WriteUtfUnknown);
buffer._SetByte(writerIndex++, char.IsHighSurrogate(c2) ? WriteUtfUnknown : c2);
continue;
}
int codePoint = CharUtil.ToCodePoint(c, c2);
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630.
buffer._SetByte(writerIndex++, (byte)(0xf0 | (codePoint >> 18)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((codePoint >> 12) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((codePoint >> 6) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (codePoint & 0x3f)));
}
else
{
buffer._SetByte(writerIndex++, (byte)(0xe0 | (c >> 12)));
buffer._SetByte(writerIndex++, (byte)(0x80 | ((c >> 6) & 0x3f)));
buffer._SetByte(writerIndex++, (byte)(0x80 | (c & 0x3f)));
}
}
return writerIndex - oldWriterIndex;
}
internal static int Utf8MaxBytes(ICharSequence seq) => Utf8MaxBytes(seq.Count);
public static int Utf8MaxBytes(string seq) => Utf8MaxBytes(seq.Length);
internal static int Utf8MaxBytes(int seqLength) => seqLength * MaxBytesPerCharUtf8;
internal static int Utf8Bytes(string seq)
{
int seqLength = seq.Length;
int i = 0;
// ASCII fast path
while (i < seqLength && seq[i] < 0x80)
{
++i;
}
// !ASCII is packed in a separate method to let the ASCII case be smaller
return i < seqLength ? i + Utf8Bytes(seq, i, seqLength) : i;
}
static int Utf8Bytes(string seq, int start, int length)
{
int encodedLength = 0;
for (int i = start; i < length; i++)
{
char c = seq[i];
// making it 100% branchless isn't rewarding due to the many bit operations necessary!
if (c < 0x800)
{
// branchless version of: (c <= 127 ? 0:1) + 1
encodedLength += ((0x7f - c).RightUShift(31)) + 1;
}
else if (char.IsSurrogate(c))
{
if (!char.IsHighSurrogate(c))
{
encodedLength++;
// WRITE_UTF_UNKNOWN
continue;
}
char c2;
try
{
// Surrogate Pair consumes 2 characters. Optimistically try to get the next character to avoid
// duplicate bounds checking with charAt.
c2 = seq[++i];
}
catch (IndexOutOfRangeException)
{
encodedLength++;
// WRITE_UTF_UNKNOWN
break;
}
if (!char.IsLowSurrogate(c2))
{
// WRITE_UTF_UNKNOWN + (Character.isHighSurrogate(c2) ? WRITE_UTF_UNKNOWN : c2)
encodedLength += 2;
continue;
}
// See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630.
encodedLength += 4;
}
else
{
encodedLength += 3;
}
}
return encodedLength;
}
public static IByteBuffer WriteAscii(IByteBufferAllocator alloc, ICharSequence seq)
{
// ASCII uses 1 byte per char
IByteBuffer buf = alloc.Buffer(seq.Count);
WriteAscii(buf, seq);
return buf;
}
public static int WriteAscii(IByteBuffer buf, ICharSequence seq)
{
// ASCII uses 1 byte per char
int len = seq.Count;
if (seq is AsciiString asciiString)
{
buf.WriteBytes(asciiString.Array, asciiString.Offset, len);
}
else
{
for (;;)
{
if (buf is AbstractByteBuffer byteBuf)
{
byteBuf.EnsureWritable0(len);
int written = WriteAscii(byteBuf, byteBuf.WriterIndex, seq, len);
byteBuf.SetWriterIndex(byteBuf.WriterIndex + written);
return written;
}
else if (buf is WrappedByteBuffer)
{
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.Unwrap();
}
else
{
byte[] bytes = Encoding.ASCII.GetBytes(seq.ToString());
buf.WriteBytes(bytes);
return bytes.Length;
}
}
}
return len;
}
// Fast-Path implementation
internal static int WriteAscii(AbstractByteBuffer buffer, int writerIndex, ICharSequence seq, int len)
{
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++)
{
buffer._SetByte(writerIndex++, AsciiString.CharToByte(seq[i]));
}
return len;
}
public static IByteBuffer WriteAscii(IByteBufferAllocator alloc, string value)
{
// ASCII uses 1 byte per char
IByteBuffer buf = alloc.Buffer(value.Length);
WriteAscii(buf, value);
return buf;
}
public static int WriteAscii(IByteBuffer buf, string value)
{
// ASCII uses 1 byte per char
int len = value.Length;
for (;;)
{
if (buf is AbstractByteBuffer byteBuf)
{
byteBuf.EnsureWritable0(len);
int written = WriteAscii(byteBuf, byteBuf.WriterIndex, value, len);
byteBuf.SetWriterIndex(byteBuf.WriterIndex + written);
return written;
}
else if (buf is WrappedByteBuffer)
{
// Unwrap as the wrapped buffer may be an AbstractByteBuf and so we can use fast-path.
buf = buf.Unwrap();
}
else
{
byte[] bytes = Encoding.ASCII.GetBytes(value);
buf.WriteBytes(bytes);
return bytes.Length;
}
}
}
internal static int WriteAscii(AbstractByteBuffer buffer, int writerIndex, string value, int len)
{
// We can use the _set methods as these not need to do any index checks and reference checks.
// This is possible as we called ensureWritable(...) before.
for (int i = 0; i < len; i++)
{
buffer._SetByte(writerIndex++, (byte)value[i]);
}
return len;
}
/// <summary>
/// Encode the given <see cref="string" /> using the given <see cref="Encoding" /> into a new
/// <see cref="IByteBuffer" /> which
/// is allocated via the <see cref="IByteBufferAllocator" />.
/// </summary>
/// <param name="alloc">The <see cref="IByteBufferAllocator" /> to allocate {@link IByteBuffer}.</param>
/// <param name="src">src The <see cref="string" /> to encode.</param>
/// <param name="encoding">charset The specified <see cref="Encoding" /></param>
public static IByteBuffer EncodeString(IByteBufferAllocator alloc, string src, Encoding encoding) => EncodeString0(alloc, false, src, encoding, 0);
/// <summary>
/// Encode the given <see cref="string" /> using the given <see cref="Encoding" /> into a new
/// <see cref="IByteBuffer" /> which
/// is allocated via the <see cref="IByteBufferAllocator" />.
/// </summary>
/// <param name="alloc">The <see cref="IByteBufferAllocator" /> to allocate {@link IByteBuffer}.</param>
/// <param name="src">src The <see cref="string" /> to encode.</param>
/// <param name="encoding">charset The specified <see cref="Encoding" /></param>
/// <param name="extraCapacity">the extra capacity to alloc except the space for decoding.</param>
public static IByteBuffer EncodeString(IByteBufferAllocator alloc, string src, Encoding encoding, int extraCapacity) => EncodeString0(alloc, false, src, encoding, extraCapacity);
internal static IByteBuffer EncodeString0(IByteBufferAllocator alloc, bool enforceHeap, string src, Encoding encoding, int extraCapacity)
{
int length = encoding.GetMaxByteCount(src.Length) + extraCapacity;
bool release = true;
IByteBuffer dst = enforceHeap ? alloc.HeapBuffer(length) : alloc.Buffer(length);
Contract.Assert(dst.HasArray, "Operation expects allocator to operate array-based buffers.");
try
{
int written = encoding.GetBytes(src, 0, src.Length, dst.Array, dst.ArrayOffset + dst.WriterIndex);
dst.SetWriterIndex(dst.WriterIndex + written);
release = false;
return dst;
}
finally
{
if (release)
{
dst.Release();
}
}
}
public static string DecodeString(IByteBuffer src, int readerIndex, int len, Encoding encoding)
{
if (len == 0)
{
return string.Empty;
}
if (src.IoBufferCount == 1)
{
ArraySegment<byte> ioBuf = src.GetIoBuffer(readerIndex, len);
return encoding.GetString(ioBuf.Array, ioBuf.Offset, ioBuf.Count);
}
else
{
int maxLength = encoding.GetMaxCharCount(len);
IByteBuffer buffer = src.Allocator.HeapBuffer(maxLength);
try
{
buffer.WriteBytes(src, readerIndex, len);
ArraySegment<byte> ioBuf = buffer.GetIoBuffer();
return encoding.GetString(ioBuf.Array, ioBuf.Offset, ioBuf.Count);
}
finally
{
// Release the temporary buffer again.
buffer.Release();
}
}
}
public static void Copy(AsciiString src, IByteBuffer dst) => Copy(src, 0, dst, src.Count);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Copy(AsciiString src, int srcIdx, IByteBuffer dst, int dstIdx, int length)
{
if (MathUtil.IsOutOfBounds(srcIdx, length, src.Count))
{
ThrowHelper.ThrowIndexOutOfRangeException_Src(srcIdx, length, src.Count);
}
if (dst == null)
{
ThrowHelper.ThrowArgumentNullException_Dst();
}
// ReSharper disable once PossibleNullReferenceException
dst.SetBytes(dstIdx, src.Array, srcIdx + src.Offset, length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Copy(AsciiString src, int srcIdx, IByteBuffer dst, int length)
{
if (MathUtil.IsOutOfBounds(srcIdx, length, src.Count))
{
ThrowHelper.ThrowIndexOutOfRangeException_Src(srcIdx, length, src.Count);
}
if (dst == null)
{
ThrowHelper.ThrowArgumentNullException_Dst();
}
// ReSharper disable once PossibleNullReferenceException
dst.WriteBytes(src.Array, srcIdx + src.Offset, length);
}
/// <summary>
/// Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans.
/// </summary>
public static string PrettyHexDump(IByteBuffer buffer) => PrettyHexDump(buffer, buffer.ReaderIndex, buffer.ReadableBytes);
/// <summary>
/// Returns a multi-line hexadecimal dump of the specified {@link ByteBuf} that is easy to read by humans,
/// starting at the given {@code offset} using the given {@code length}.
/// </summary>
public static string PrettyHexDump(IByteBuffer buffer, int offset, int length) => HexUtil.DoPrettyHexDump(buffer, offset, length);
/// <summary>
/// Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
/// {@link StringBuilder} that is easy to read by humans.
/// </summary>
public static void AppendPrettyHexDump(StringBuilder dump, IByteBuffer buf) => AppendPrettyHexDump(dump, buf, buf.ReaderIndex, buf.ReadableBytes);
/// <summary>
/// Appends the prettified multi-line hexadecimal dump of the specified {@link ByteBuf} to the specified
/// {@link StringBuilder} that is easy to read by humans, starting at the given {@code offset} using
/// the given {@code length}.
/// </summary>
public static void AppendPrettyHexDump(StringBuilder dump, IByteBuffer buf, int offset, int length) => HexUtil.DoAppendPrettyHexDump(dump, buf, offset, length);
static class HexUtil
{
static readonly char[] HexdumpTable = new char[256 * 4];
static readonly string Newline = StringUtil.Newline;
static readonly string[] Byte2Hex = new string[256];
static readonly string[] HexPadding = new string[16];
static readonly string[] BytePadding = new string[16];
static readonly char[] Byte2Char = new char[256];
static readonly string[] HexDumpRowPrefixes = new string[(int)((uint)65536 >> 4)];
static HexUtil()
{
char[] digits = "0123456789abcdef".ToCharArray();
for (int i = 0; i < 256; i++)
{
HexdumpTable[i << 1] = digits[(int)((uint)i >> 4 & 0x0F)];
HexdumpTable[(i << 1) + 1] = digits[i & 0x0F];
}
// Generate the lookup table for byte-to-hex-dump conversion
for (int i = 0; i < Byte2Hex.Length; i++)
{
Byte2Hex[i] = ' ' + StringUtil.ByteToHexStringPadded(i);
}
// Generate the lookup table for hex dump paddings
for (int i = 0; i < HexPadding.Length; i++)
{
int padding = HexPadding.Length - i;
var buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j++)
{
buf.Append(" ");
}
HexPadding[i] = buf.ToString();
}
// Generate the lookup table for byte dump paddings
for (int i = 0; i < BytePadding.Length; i++)
{
int padding = BytePadding.Length - i;
var buf = new StringBuilder(padding);
for (int j = 0; j < padding; j++)
{
buf.Append(' ');
}
BytePadding[i] = buf.ToString();
}
// Generate the lookup table for byte-to-char conversion
for (int i = 0; i < Byte2Char.Length; i++)
{
if (i <= 0x1f || i >= 0x7f)
{
Byte2Char[i] = '.';
}
else
{
Byte2Char[i] = (char)i;
}
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
for (int i = 0; i < HexDumpRowPrefixes.Length; i++)
{
var buf = new StringBuilder(12);
buf.Append(Environment.NewLine);
buf.Append((i << 4 & 0xFFFFFFFFL | 0x100000000L).ToString("X2"));
buf.Insert(buf.Length - 9, '|');
buf.Append('|');
HexDumpRowPrefixes[i] = buf.ToString();
}
}
public static string DoHexDump(IByteBuffer buffer, int fromIndex, int length)
{
Contract.Requires(length >= 0);
if (length == 0)
{
return "";
}
int endIndex = fromIndex + length;
var buf = new char[length << 1];
int srcIdx = fromIndex;
int dstIdx = 0;
for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
{
Array.Copy(
HexdumpTable, buffer.GetByte(srcIdx) << 1,
buf, dstIdx, 2);
}
return new string(buf);
}
public static string DoHexDump(byte[] array, int fromIndex, int length)
{
Contract.Requires(length >= 0);
if (length == 0)
{
return "";
}
int endIndex = fromIndex + length;
var buf = new char[length << 1];
int srcIdx = fromIndex;
int dstIdx = 0;
for (; srcIdx < endIndex; srcIdx++, dstIdx += 2)
{
Array.Copy(HexdumpTable, (array[srcIdx] & 0xFF) << 1, buf, dstIdx, 2);
}
return new string(buf);
}
public static string DoPrettyHexDump(IByteBuffer buffer, int offset, int length)
{
if (length == 0)
{
return string.Empty;
}
else
{
int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
var buf = new StringBuilder(rows * 80);
AppendPrettyHexDump(buf, buffer, offset, length);
return buf.ToString();
}
}
public static void DoAppendPrettyHexDump(StringBuilder dump, IByteBuffer buf, int offset, int length)
{
if (MathUtil.IsOutOfBounds(offset, length, buf.Capacity))
{
throw new IndexOutOfRangeException(
$"expected: 0 <= offset({offset}) <= offset + length({length}) <= buf.capacity({buf.Capacity}{')'}");
}
if (length == 0)
{
return;
}
dump.Append(
" +-------------------------------------------------+" +
Newline + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
Newline + "+--------+-------------------------------------------------+----------------+");
int startIndex = offset;
int fullRows = (int)((uint)length >> 4);
int remainder = length & 0xF;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row++)
{
int rowStartIndex = (row << 4) + startIndex;
// Per-row prefix.
AppendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++)
{
dump.Append(Byte2Hex[buf.GetByte(j)]);
}
dump.Append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j++)
{
dump.Append(Byte2Char[buf.GetByte(j)]);
}
dump.Append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0)
{
int rowStartIndex = (fullRows << 4) + startIndex;
AppendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++)
{
dump.Append(Byte2Hex[buf.GetByte(j)]);
}
dump.Append(HexPadding[remainder]);
dump.Append(" |");
// Ascii dump
for (int j = rowStartIndex; j < rowEndIndex; j++)