Repository navigation
Expand file tree
/
Copy pathBuffer.kt
More file actions
1710 lines (1484 loc) · 49.3 KB
/
Copy pathBuffer.kt
File metadata and controls
1710 lines (1484 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("-Buffer") // A leading '-' hides this class from Java.
// TODO move to Buffer class: https://youtrack.jetbrains.com/issue/KT-20427
@file:Suppress("NOTHING_TO_INLINE")
package okio.internal
import kotlin.jvm.JvmName
import okio.ArrayIndexOutOfBoundsException
import okio.Buffer
import okio.Buffer.UnsafeCursor
import okio.ByteString
import okio.EOFException
import okio.Options
import okio.REPLACEMENT_CODE_POINT
import okio.Segment
import okio.SegmentPool
import okio.SegmentedByteString
import okio.Sink
import okio.Source
import okio.and
import okio.asUtf8ToByteArray
import okio.checkOffsetAndCount
import okio.minOf
import okio.toHexString
internal val HEX_DIGIT_BYTES = "0123456789abcdef".asUtf8ToByteArray()
// Threshold determined empirically via ReadByteStringBenchmark
/** Create SegmentedByteString when size is greater than this many bytes. */
internal const val SEGMENTING_THRESHOLD = 4096
/**
* Returns true if the range within this buffer starting at `segmentPos` in `segment` is equal to
* `bytes[bytesOffset..bytesLimit)`.
*/
internal fun rangeEquals(
segment: Segment,
segmentPos: Int,
bytes: ByteArray,
bytesOffset: Int,
bytesLimit: Int,
): Boolean {
var segment = segment
var segmentPos = segmentPos
var segmentLimit = segment.limit
var data = segment.data
var i = bytesOffset
while (i < bytesLimit) {
if (segmentPos == segmentLimit) {
segment = segment.next!!
data = segment.data
segmentPos = segment.pos
segmentLimit = segment.limit
}
if (data[segmentPos] != bytes[i]) {
return false
}
segmentPos++
i++
}
return true
}
internal fun Buffer.readUtf8Line(newline: Long): String {
return when {
newline > 0 && this[newline - 1] == '\r'.code.toByte() -> {
// Read everything until '\r\n', then skip the '\r\n'.
val result = readUtf8(newline - 1L)
skip(2L)
result
}
else -> {
// Read everything until '\n', then skip the '\n'.
val result = readUtf8(newline)
skip(1L)
result
}
}
}
/**
* Invoke `lambda` with the segment and offset at `fromIndex`. Searches from the front or the back
* depending on what's closer to `fromIndex`.
*/
internal inline fun <T> Buffer.seek(
fromIndex: Long,
lambda: (Segment?, Long) -> T,
): T {
var s: Segment = head ?: return lambda(null, -1L)
if (size - fromIndex < fromIndex) {
// We're scanning in the back half of this buffer. Find the segment starting at the back.
var offset = size
while (offset > fromIndex) {
s = s.prev!!
offset -= (s.limit - s.pos).toLong()
}
return lambda(s, offset)
} else {
// We're scanning in the front half of this buffer. Find the segment starting at the front.
var offset = 0L
while (true) {
val nextOffset = offset + (s.limit - s.pos)
if (nextOffset > fromIndex) break
s = s.next!!
offset = nextOffset
}
return lambda(s, offset)
}
}
/**
* Returns the index of a value in options that is a prefix of this buffer. Returns -1 if no value
* is found. This method does two simultaneous iterations: it iterates the trie and it iterates
* this buffer. It returns when it reaches a result in the trie, when it mismatches in the trie,
* and when the buffer is exhausted.
*
* @param selectTruncated true to return -2 if a possible result is present but truncated. For
* example, this will return -2 if the buffer contains [ab] and the options are [abc, abd].
* Note that this is made complicated by the fact that options are listed in preference order,
* and one option may be a prefix of another. For example, this returns -2 if the buffer
* contains [ab] and the options are [abc, a].
*/
internal fun Buffer.selectPrefix(options: Options, selectTruncated: Boolean = false): Int {
val head = head ?: return if (selectTruncated) -2 else -1
var s: Segment? = head
var data = head.data
var pos = head.pos
var limit = head.limit
val trie = options.trie
var triePos = 0
var prefixIndex = -1
navigateTrie@
while (true) {
val scanOrSelect = trie[triePos++]
val possiblePrefixIndex = trie[triePos++]
if (possiblePrefixIndex != -1) {
prefixIndex = possiblePrefixIndex
}
val nextStep: Int
if (s == null) {
break@navigateTrie
} else if (scanOrSelect < 0) {
// Scan: take multiple bytes from the buffer and the trie, looking for any mismatch.
val scanByteCount = -1 * scanOrSelect
val trieLimit = triePos + scanByteCount
while (true) {
val byte = data[pos++] and 0xff
if (byte != trie[triePos++]) return prefixIndex // Fail 'cause we found a mismatch.
val scanComplete = (triePos == trieLimit)
// Advance to the next buffer segment if this one is exhausted.
if (pos == limit) {
s = s!!.next!!
pos = s.pos
data = s.data
limit = s.limit
if (s === head) {
if (!scanComplete) break@navigateTrie // We were exhausted before the scan completed.
s = null // We were exhausted at the end of the scan.
}
}
if (scanComplete) {
nextStep = trie[triePos]
break
}
}
} else {
// Select: take one byte from the buffer and find a match in the trie.
val selectChoiceCount = scanOrSelect
val byte = data[pos++] and 0xff
val selectLimit = triePos + selectChoiceCount
while (true) {
if (triePos == selectLimit) return prefixIndex // Fail 'cause we didn't find a match.
if (byte == trie[triePos]) {
nextStep = trie[triePos + selectChoiceCount]
break
}
triePos++
}
// Advance to the next buffer segment if this one is exhausted.
if (pos == limit) {
s = s.next!!
pos = s.pos
data = s.data
limit = s.limit
if (s === head) {
s = null // No more segments! The next trie node will be our last.
}
}
}
if (nextStep >= 0) return nextStep // Found a matching option.
triePos = -nextStep // Found another node to continue the search.
}
// We break out of the loop above when we've exhausted the buffer without exhausting the trie.
if (selectTruncated) return -2 // The buffer is a prefix of at least one option.
return prefixIndex // Return any matches we encountered while searching for a deeper match.
}
// TODO Kotlin's expect classes can't have default implementations, so platform implementations
// have to call these functions. Remove all this nonsense when expect class allow actual code.
internal inline fun Buffer.commonCopyTo(
out: Buffer,
offset: Long,
byteCount: Long,
): Buffer {
var offset = offset
var byteCount = byteCount
checkOffsetAndCount(size, offset, byteCount)
if (byteCount == 0L) return this
out.size += byteCount
// Skip segments that we aren't copying from.
var s = head
while (offset >= s!!.limit - s.pos) {
offset -= (s.limit - s.pos).toLong()
s = s.next
}
// Copy one segment at a time.
while (byteCount > 0L) {
val copy = s!!.sharedCopy()
copy.pos += offset.toInt()
copy.limit = minOf(copy.pos + byteCount.toInt(), copy.limit)
if (out.head == null) {
copy.prev = copy
copy.next = copy.prev
out.head = copy.next
} else {
out.head!!.prev!!.push(copy)
}
byteCount -= (copy.limit - copy.pos).toLong()
offset = 0L
s = s.next
}
return this
}
internal inline fun Buffer.commonCompleteSegmentByteCount(): Long {
var result = size
if (result == 0L) return 0L
// Omit the tail if it's still writable.
val tail = head!!.prev!!
if (tail.limit < Segment.SIZE && tail.owner) {
result -= (tail.limit - tail.pos).toLong()
}
return result
}
internal inline fun Buffer.commonReadByte(): Byte {
if (size == 0L) throw EOFException()
val segment = head!!
var pos = segment.pos
val limit = segment.limit
val data = segment.data
val b = data[pos++]
size -= 1L
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
return b
}
internal inline fun Buffer.commonReadShort(): Short {
if (size < 2L) throw EOFException()
val segment = head!!
var pos = segment.pos
val limit = segment.limit
// If the short is split across multiple segments, delegate to readByte().
if (limit - pos < 2) {
val s = readByte() and 0xff shl 8 or (readByte() and 0xff)
return s.toShort()
}
val data = segment.data
val s = data[pos++] and 0xff shl 8 or (data[pos++] and 0xff)
size -= 2L
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
return s.toShort()
}
internal inline fun Buffer.commonReadInt(): Int {
if (size < 4L) throw EOFException()
val segment = head!!
var pos = segment.pos
val limit = segment.limit
// If the int is split across multiple segments, delegate to readByte().
if (limit - pos < 4L) {
return (
readByte() and 0xff shl 24
or (readByte() and 0xff shl 16)
or (readByte() and 0xff shl 8) // ktlint-disable no-multi-spaces
or (readByte() and 0xff)
)
}
val data = segment.data
val i = (
data[pos++] and 0xff shl 24
or (data[pos++] and 0xff shl 16)
or (data[pos++] and 0xff shl 8)
or (data[pos++] and 0xff)
)
size -= 4L
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
return i
}
internal inline fun Buffer.commonReadLong(): Long {
if (size < 8L) throw EOFException()
val segment = head!!
var pos = segment.pos
val limit = segment.limit
// If the long is split across multiple segments, delegate to readInt().
if (limit - pos < 8L) {
return (
readInt() and 0xffffffffL shl 32
or (readInt() and 0xffffffffL)
)
}
val data = segment.data
val v = (
data[pos++] and 0xffL shl 56
or (data[pos++] and 0xffL shl 48)
or (data[pos++] and 0xffL shl 40)
or (data[pos++] and 0xffL shl 32)
or (data[pos++] and 0xffL shl 24)
or (data[pos++] and 0xffL shl 16)
or (data[pos++] and 0xffL shl 8) // ktlint-disable no-multi-spaces
or (data[pos++] and 0xffL)
)
size -= 8L
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
return v
}
internal inline fun Buffer.commonGet(pos: Long): Byte {
checkOffsetAndCount(size, pos, 1L)
seek(pos) { s, offset ->
return s!!.data[(s.pos + pos - offset).toInt()]
}
}
internal inline fun Buffer.commonClear() = skip(size)
internal inline fun Buffer.commonSkip(byteCount: Long) {
var byteCount = byteCount
while (byteCount > 0) {
val head = this.head ?: throw EOFException()
val toSkip = minOf(byteCount, head.limit - head.pos).toInt()
size -= toSkip.toLong()
byteCount -= toSkip.toLong()
head.pos += toSkip
if (head.pos == head.limit) {
this.head = head.pop()
SegmentPool.recycle(head)
}
}
}
internal inline fun Buffer.commonWrite(
byteString: ByteString,
offset: Int = 0,
byteCount: Int = byteString.size,
): Buffer {
byteString.write(this, offset, byteCount)
return this
}
internal inline fun Buffer.commonWriteDecimalLong(v: Long): Buffer {
var v = v
if (v == 0L) {
// Both a shortcut and required since the following code can't handle zero.
return writeByte('0'.code)
}
var negative = false
if (v < 0L) {
v = -v
if (v < 0L) { // Only true for Long.MIN_VALUE.
return writeUtf8("-9223372036854775808")
}
negative = true
}
var width = countDigitsIn(v)
if (negative) {
++width
}
val tail = writableSegment(width)
val data = tail.data
var pos = tail.limit + width // We write backwards from right to left.
while (v != 0L) {
val digit = (v % 10).toInt()
data[--pos] = HEX_DIGIT_BYTES[digit]
v /= 10
}
if (negative) {
data[--pos] = '-'.code.toByte()
}
tail.limit += width
this.size += width.toLong()
return this
}
private fun countDigitsIn(v: Long): Int {
val guess = ((64 - v.countLeadingZeroBits()) * 10) ushr 5
return guess + (if (v > DigitCountToLargestValue[guess]) 1 else 0)
}
private val DigitCountToLargestValue = longArrayOf(
-1, // Every value has more than 0 digits.
9L, // For 1 digit (index 1), the largest value is 9.
99L,
999L,
9999L,
99999L,
999999L,
9999999L,
99999999L,
999999999L,
9999999999L,
99999999999L,
999999999999L,
9999999999999L,
99999999999999L,
999999999999999L,
9999999999999999L,
99999999999999999L,
999999999999999999L, // For 18 digits (index 18), the largest value is 999999999999999999.
Long.MAX_VALUE, // For 19 digits (index 19), the largest value is MAX_VALUE.
)
internal inline fun Buffer.commonWriteHexadecimalUnsignedLong(v: Long): Buffer {
var v = v
if (v == 0L) {
// Both a shortcut and required since the following code can't handle zero.
return writeByte('0'.code)
}
// Mask every bit below the most significant bit to a 1
// https://aggregate.org/MAGIC/#Most%20Significant%201%20Bit
var x = v
x = x or (x ushr 1)
x = x or (x ushr 2)
x = x or (x ushr 4)
x = x or (x ushr 8)
x = x or (x ushr 16)
x = x or (x ushr 32)
// Count the number of 1s
// https://aggregate.org/MAGIC/#Population%20Count%20(Ones%20Count)
x -= x ushr 1 and 0x5555555555555555
x = (x ushr 2 and 0x3333333333333333) + (x and 0x3333333333333333)
x = (x ushr 4) + x and 0x0f0f0f0f0f0f0f0f
x += x ushr 8
x += x ushr 16
x = (x and 0x3f) + ((x ushr 32) and 0x3f)
// Round up to the nearest full byte
val width = ((x + 3) / 4).toInt()
val tail = writableSegment(width)
val data = tail.data
var pos = tail.limit + width - 1
val start = tail.limit
while (pos >= start) {
data[pos] = HEX_DIGIT_BYTES[(v and 0xF).toInt()]
v = v ushr 4
pos--
}
tail.limit += width
size += width.toLong()
return this
}
internal inline fun Buffer.commonWritableSegment(minimumCapacity: Int): Segment {
require(minimumCapacity >= 1 && minimumCapacity <= Segment.SIZE) { "unexpected capacity" }
if (head == null) {
val result = SegmentPool.take() // Acquire a first segment.
head = result
result.prev = result
result.next = result
return result
}
var tail = head!!.prev
if (tail!!.limit + minimumCapacity > Segment.SIZE || !tail.owner) {
tail = tail.push(SegmentPool.take()) // Append a new empty segment to fill up.
}
return tail
}
internal inline fun Buffer.commonWrite(source: ByteArray) = write(source, 0, source.size)
internal inline fun Buffer.commonWrite(
source: ByteArray,
offset: Int,
byteCount: Int,
): Buffer {
var offset = offset
checkOffsetAndCount(source.size.toLong(), offset.toLong(), byteCount.toLong())
val limit = offset + byteCount
while (offset < limit) {
val tail = writableSegment(1)
val toCopy = minOf(limit - offset, Segment.SIZE - tail.limit)
source.copyInto(
destination = tail.data,
destinationOffset = tail.limit,
startIndex = offset,
endIndex = offset + toCopy,
)
offset += toCopy
tail.limit += toCopy
}
size += byteCount.toLong()
return this
}
internal inline fun Buffer.commonReadByteArray() = readByteArray(size)
internal inline fun Buffer.commonReadByteArray(byteCount: Long): ByteArray {
require(byteCount >= 0 && byteCount <= Int.MAX_VALUE) { "byteCount: $byteCount" }
if (size < byteCount) throw EOFException()
val result = ByteArray(byteCount.toInt())
readFully(result)
return result
}
internal inline fun Buffer.commonRead(sink: ByteArray) = read(sink, 0, sink.size)
internal inline fun Buffer.commonReadFully(sink: ByteArray) {
var offset = 0
while (offset < sink.size) {
val read = read(sink, offset, sink.size - offset)
if (read == -1) throw EOFException()
offset += read
}
}
internal inline fun Buffer.commonRead(sink: ByteArray, offset: Int, byteCount: Int): Int {
checkOffsetAndCount(sink.size.toLong(), offset.toLong(), byteCount.toLong())
val s = head ?: return -1
val toCopy = minOf(byteCount, s.limit - s.pos)
s.data.copyInto(
destination = sink,
destinationOffset = offset,
startIndex = s.pos,
endIndex = s.pos + toCopy,
)
s.pos += toCopy
size -= toCopy.toLong()
if (s.pos == s.limit) {
head = s.pop()
SegmentPool.recycle(s)
}
return toCopy
}
internal const val OVERFLOW_ZONE = Long.MIN_VALUE / 10L
internal const val OVERFLOW_DIGIT_START = Long.MIN_VALUE % 10L + 1
internal inline fun Buffer.commonReadDecimalLong(): Long {
if (size == 0L) throw EOFException()
// This value is always built negatively in order to accommodate Long.MIN_VALUE.
var value = 0L
var seen = 0
var negative = false
var done = false
var overflowDigit = OVERFLOW_DIGIT_START
do {
val segment = head!!
val data = segment.data
var pos = segment.pos
val limit = segment.limit
while (pos < limit) {
val b = data[pos]
if (b >= '0'.code.toByte() && b <= '9'.code.toByte()) {
val digit = '0'.code.toByte() - b
// Detect when the digit would cause an overflow.
if (value < OVERFLOW_ZONE || value == OVERFLOW_ZONE && digit < overflowDigit) {
val buffer = Buffer().writeDecimalLong(value).writeByte(b.toInt())
if (!negative) buffer.readByte() // Skip negative sign.
throw NumberFormatException("Number too large: ${buffer.readUtf8()}")
}
value *= 10L
value += digit.toLong()
} else if (b == '-'.code.toByte() && seen == 0) {
negative = true
overflowDigit -= 1
} else {
// Set a flag to stop iteration. We still need to run through segment updating below.
done = true
break
}
pos++
seen++
}
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
} while (!done && head != null)
size -= seen.toLong()
val minimumSeen = if (negative) 2 else 1
if (seen < minimumSeen) {
if (size == 0L) throw EOFException()
val expected = if (negative) "Expected a digit" else "Expected a digit or '-'"
throw NumberFormatException("$expected but was 0x${get(0).toHexString()}")
}
return if (negative) value else -value
}
internal inline fun Buffer.commonReadHexadecimalUnsignedLong(): Long {
if (size == 0L) throw EOFException()
var value = 0L
var seen = 0
var done = false
do {
val segment = head!!
val data = segment.data
var pos = segment.pos
val limit = segment.limit
while (pos < limit) {
val digit: Int
val b = data[pos]
if (b >= '0'.code.toByte() && b <= '9'.code.toByte()) {
digit = b - '0'.code.toByte()
} else if (b >= 'a'.code.toByte() && b <= 'f'.code.toByte()) {
digit = b - 'a'.code.toByte() + 10
} else if (b >= 'A'.code.toByte() && b <= 'F'.code.toByte()) {
digit = b - 'A'.code.toByte() + 10 // We never write uppercase, but we support reading it.
} else {
if (seen == 0) {
throw NumberFormatException(
"Expected leading [0-9a-fA-F] character but was 0x${b.toHexString()}",
)
}
// Set a flag to stop iteration. We still need to run through segment updating below.
done = true
break
}
// Detect when the shift will overflow.
if (value and -0x1000000000000000L != 0L) {
val buffer = Buffer().writeHexadecimalUnsignedLong(value).writeByte(b.toInt())
throw NumberFormatException("Number too large: " + buffer.readUtf8())
}
value = value shl 4
value = value or digit.toLong()
pos++
seen++
}
if (pos == limit) {
head = segment.pop()
SegmentPool.recycle(segment)
} else {
segment.pos = pos
}
} while (!done && head != null)
size -= seen.toLong()
return value
}
internal inline fun Buffer.commonReadByteString(): ByteString = readByteString(size)
internal inline fun Buffer.commonReadByteString(byteCount: Long): ByteString {
require(byteCount >= 0 && byteCount <= Int.MAX_VALUE) { "byteCount: $byteCount" }
if (size < byteCount) throw EOFException()
if (byteCount >= SEGMENTING_THRESHOLD) {
return snapshot(byteCount.toInt()).also { skip(byteCount) }
} else {
return ByteString(readByteArray(byteCount))
}
}
internal inline fun Buffer.commonSelect(options: Options): Int {
val index = selectPrefix(options)
if (index == -1) return -1
// If the prefix match actually matched a full byte string, consume it and return it.
val selectedSize = options.byteStrings[index].size
skip(selectedSize.toLong())
return index
}
internal inline fun Buffer.commonReadFully(sink: Buffer, byteCount: Long) {
if (size < byteCount) {
sink.write(this, size) // Exhaust ourselves.
throw EOFException()
}
sink.write(this, byteCount)
}
internal inline fun Buffer.commonReadAll(sink: Sink): Long {
val byteCount = size
if (byteCount > 0L) {
sink.write(this, byteCount)
}
return byteCount
}
internal inline fun Buffer.commonReadUtf8(byteCount: Long): String {
require(byteCount >= 0 && byteCount <= Int.MAX_VALUE) { "byteCount: $byteCount" }
if (size < byteCount) throw EOFException()
if (byteCount == 0L) return ""
val s = head!!
if (s.pos + byteCount > s.limit) {
// If the string spans multiple segments, delegate to readBytes().
return readByteArray(byteCount).commonToUtf8String()
}
val result = s.data.commonToUtf8String(s.pos, s.pos + byteCount.toInt())
s.pos += byteCount.toInt()
size -= byteCount
if (s.pos == s.limit) {
head = s.pop()
SegmentPool.recycle(s)
}
return result
}
internal inline fun Buffer.commonReadUtf8Line(): String? {
val newline = indexOf('\n'.code.toByte())
return when {
newline != -1L -> readUtf8Line(newline)
size != 0L -> readUtf8(size)
else -> null
}
}
internal inline fun Buffer.commonReadUtf8LineStrict(limit: Long): String {
require(limit >= 0L) { "limit < 0: $limit" }
val scanLength = if (limit == Long.MAX_VALUE) Long.MAX_VALUE else limit + 1L
val newline = indexOf('\n'.code.toByte(), 0L, scanLength)
if (newline != -1L) return readUtf8Line(newline)
if (scanLength < size &&
this[scanLength - 1] == '\r'.code.toByte() &&
this[scanLength] == '\n'.code.toByte()
) {
return readUtf8Line(scanLength) // The line was 'limit' UTF-8 bytes followed by \r\n.
}
val data = Buffer()
copyTo(data, 0, minOf(32, size))
throw EOFException(
"\\n not found: limit=${minOf(
size,
limit,
)} content=${data.readByteString().hex()}${'…'}",
)
}
internal inline fun Buffer.commonReadUtf8CodePoint(): Int {
if (size == 0L) throw EOFException()
val b0 = this[0]
var codePoint: Int
val byteCount: Int
val min: Int
when {
b0 and 0x80 == 0 -> {
// 0xxxxxxx.
codePoint = b0 and 0x7f
byteCount = 1 // 7 bits (ASCII).
min = 0x0
}
b0 and 0xe0 == 0xc0 -> {
// 0x110xxxxx
codePoint = b0 and 0x1f
byteCount = 2 // 11 bits (5 + 6).
min = 0x80
}
b0 and 0xf0 == 0xe0 -> {
// 0x1110xxxx
codePoint = b0 and 0x0f
byteCount = 3 // 16 bits (4 + 6 + 6).
min = 0x800
}
b0 and 0xf8 == 0xf0 -> {
// 0x11110xxx
codePoint = b0 and 0x07
byteCount = 4 // 21 bits (3 + 6 + 6 + 6).
min = 0x10000
}
else -> {
// We expected the first byte of a code point but got something else.
skip(1)
return REPLACEMENT_CODE_POINT
}
}
if (size < byteCount) {
throw EOFException("size < $byteCount: $size (to read code point prefixed 0x${b0.toHexString()})")
}
// Read the continuation bytes. If we encounter a non-continuation byte, the sequence consumed
// thus far is truncated and is decoded as the replacement character. That non-continuation byte
// is left in the stream for processing by the next call to readUtf8CodePoint().
for (i in 1 until byteCount) {
val b = this[i.toLong()]
if (b and 0xc0 == 0x80) {
// 0x10xxxxxx
codePoint = codePoint shl 6
codePoint = codePoint or (b and 0x3f)
} else {
skip(i.toLong())
return REPLACEMENT_CODE_POINT
}
}
skip(byteCount.toLong())
return when {
codePoint > 0x10ffff -> {
REPLACEMENT_CODE_POINT // Reject code points larger than the Unicode maximum.
}
codePoint.isSurrogate -> {
REPLACEMENT_CODE_POINT // Reject partial surrogates.
}
codePoint < min -> {
REPLACEMENT_CODE_POINT // Reject overlong code points.
}
else -> codePoint
}
}
internal inline fun Buffer.commonWriteUtf8(string: String, beginIndex: Int, endIndex: Int): Buffer {
require(beginIndex >= 0) { "beginIndex < 0: $beginIndex" }
require(endIndex >= beginIndex) { "endIndex < beginIndex: $endIndex < $beginIndex" }
require(endIndex <= string.length) { "endIndex > string.length: $endIndex > ${string.length}" }
// Transcode a UTF-16 Java String to UTF-8 bytes.
var i = beginIndex
while (i < endIndex) {
var c = string[i].code
when {
c < 0x80 -> {
val tail = writableSegment(1)
val data = tail.data
val segmentOffset = tail.limit - i
val runLimit = minOf(endIndex, Segment.SIZE - segmentOffset)
// Emit a 7-bit character with 1 byte.
data[segmentOffset + i++] = c.toByte() // 0xxxxxxx
// Fast-path contiguous runs of ASCII characters. This is ugly, but yields a ~4x performance
// improvement over independent calls to writeByte().
while (i < runLimit) {
c = string[i].code
if (c >= 0x80) break
data[segmentOffset + i++] = c.toByte() // 0xxxxxxx
}
val runSize = i + segmentOffset - tail.limit // Equivalent to i - (previous i).
tail.limit += runSize
size += runSize.toLong()
}
c < 0x800 -> {
// Emit a 11-bit character with 2 bytes.
val tail = writableSegment(2)
/* ktlint-disable no-multi-spaces */
tail.data[tail.limit ] = (c shr 6 or 0xc0).toByte() // 110xxxxx
tail.data[tail.limit + 1] = (c and 0x3f or 0x80).toByte() // 10xxxxxx
/* ktlint-enable no-multi-spaces */
tail.limit += 2
size += 2L
i++
}
c.isHighSurrogate -> {
// c is a high surrogate. Make sure its successor is a low surrogate. If not, the UTF-16 is
// invalid, in which case we emit a replacement character.
val low = (if (i + 1 < endIndex) string[i + 1].code else 0)
if (!low.isLowSurrogate) {
writeByte('?'.code)
i++
} else {
val codePoint = combineSurrogates(c, low)
// Emit a 21-bit character with 4 bytes.
val tail = writableSegment(4)
/* ktlint-disable no-multi-spaces */
tail.data[tail.limit ] = (codePoint shr 18 or 0xf0).toByte() // 11110xxx
tail.data[tail.limit + 1] = (codePoint shr 12 and 0x3f or 0x80).toByte() // 10xxxxxx