-
Notifications
You must be signed in to change notification settings - Fork 768
Expand file tree
/
Copy pathByteBuffer-aux.swift
More file actions
1103 lines (1021 loc) · 50.1 KB
/
Copy pathByteBuffer-aux.swift
File metadata and controls
1103 lines (1021 loc) · 50.1 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import _NIOBase64
#if canImport(Dispatch)
import Dispatch
#endif
extension ByteBuffer {
// MARK: Bytes ([UInt8]) APIs
/// Get `length` bytes starting at `index` and return the result as `[UInt8]`. This will not change the reader index.
/// The selected bytes must be readable or else `nil` will be returned.
///
/// - Parameters:
/// - index: The starting index of the bytes of interest into the `ByteBuffer`.
/// - length: The number of bytes of interest.
/// - Returns: A `[UInt8]` value containing the bytes of interest or `nil` if the bytes `ByteBuffer` are not readable.
@inlinable
public func getBytes(at index: Int, length: Int) -> [UInt8]? {
guard let range = self.rangeWithinReadableBytes(index: index, length: length) else {
return nil
}
return self.withUnsafeReadableBytes { ptr in
// this is not technically correct because we shouldn't just bind
// the memory to `UInt8` but it's not a real issue either and we
// need to work around https://bugs.swift.org/browse/SR-9604
[UInt8](UnsafeRawBufferPointer(rebasing: ptr[range]).bindMemory(to: UInt8.self))
}
}
/// Read `length` bytes off this `ByteBuffer`, move the reader index forward by `length` bytes and return the result
/// as `[UInt8]`.
///
/// - Parameters:
/// - length: The number of bytes to be read from this `ByteBuffer`.
/// - Returns: A `[UInt8]` value containing `length` bytes or `nil` if there aren't at least `length` bytes readable.
@inlinable
public mutating func readBytes(length: Int) -> [UInt8]? {
guard let result = self.getBytes(at: self.readerIndex, length: length) else {
return nil
}
self._moveReaderIndex(forwardBy: length)
return result
}
#if compiler(>=6.2)
@inlinable
@available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *)
public mutating func readInlineArray<
let count: Int,
IntegerType: FixedWidthInteger
>(
endianness: Endianness = .big,
as: InlineArray<count, IntegerType>.Type = InlineArray<count, IntegerType>.self
) -> InlineArray<count, IntegerType>? {
// use stride to account for padding bytes
let stride = MemoryLayout<IntegerType>.stride
let bytesRequired = stride * count
guard self.readableBytes >= bytesRequired else {
return nil
}
let inlineArray = InlineArray<count, IntegerType> { (outputSpan: inout OutputSpan<IntegerType>) in
for index in 0..<count {
// already made sure of 'self.readableBytes >= bytesRequired' above,
// so this is safe to force-unwrap as it's guaranteed to exist
let integer = self.getInteger(
// this is less than 'bytesRequired' so is safe to multiply
at: stride &* index,
endianness: endianness,
as: IntegerType.self
)!
outputSpan.append(integer)
}
}
// already made sure of 'self.readableBytes >= bytesRequired' above
self._moveReaderIndex(forwardBy: bytesRequired)
return inlineArray
}
#endif
/// Returns the Bytes at the current reader index without advancing it.
///
/// This method is equivalent to calling `getBytes(at: readerIndex, ...)`
///
/// - Parameters:
/// - length: The number of bytes of interest.
/// - Returns: A `[UInt8]` value containing the bytes of interest or `nil` if the bytes `ByteBuffer` are not readable.
@inlinable
public func peekBytes(length: Int) -> [UInt8]? {
self.getBytes(at: self.readerIndex, length: length)
}
// MARK: StaticString APIs
/// Write the static `string` into this `ByteBuffer` using UTF-8 encoding, moving the writer index forward appropriately.
///
/// - Parameters:
/// - string: The string to write.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writeStaticString(_ string: StaticString) -> Int {
let written = self.setStaticString(string, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Write the static `string` into this `ByteBuffer` at `index` using UTF-8 encoding, moving the writer index forward appropriately.
///
/// - Parameters:
/// - string: The string to write.
/// - index: The index for the first serialized byte.
/// - Returns: The number of bytes written.
@inlinable
public mutating func setStaticString(_ string: StaticString, at index: Int) -> Int {
// please do not replace the code below with code that uses `string.withUTF8Buffer { ... }` (see SR-7541)
self.setBytes(
UnsafeRawBufferPointer(
start: string.utf8Start,
count: string.utf8CodeUnitCount
),
at: index
)
}
// MARK: Hex encoded string APIs
/// Write ASCII hexadecimal `string` into this `ByteBuffer` as raw bytes, decoding the hexadecimal & moving the writer index forward appropriately.
/// This method will throw if the string input is not of the "plain" hex encoded format.
/// - Parameters:
/// - plainHexEncodedBytes: The hex encoded string to write. Plain hex dump format is hex bytes optionally separated by spaces, i.e. `48 65 6c 6c 6f` or `48656c6c6f` for `Hello`.
/// This format is compatible with `xxd` CLI utility.
/// - Returns: The number of bytes written.
@_disfavoredOverload
@discardableResult
@inlinable
public mutating func writePlainHexEncodedBytes(_ plainHexEncodedBytes: String) throws -> Int {
try self.writePlainHexEncodedBytes(plainHexEncodedBytes)
}
// MARK: Hex encoded string APIs
/// Write ASCII hexadecimal `string` into this `ByteBuffer` as raw bytes, decoding the hexadecimal & moving the writer index forward appropriately.
/// This method will throw if the string input is not of the "plain" hex encoded format.
/// - Parameters:
/// - plainHexEncodedBytes: The hex encoded string to write. Plain hex dump format is hex bytes optionally separated by spaces, i.e. `48 65 6c 6c 6f` or `48656c6c6f` for `Hello`.
/// This format is compatible with `xxd` CLI utility.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writePlainHexEncodedBytes(_ plainHexEncodedBytes: some StringProtocol) throws -> Int {
var slice = plainHexEncodedBytes.utf8[...]
let initialWriterIndex = self.writerIndex
do {
while let nextByte = try slice.popNextHexByte() {
self.writeInteger(nextByte)
}
return self.writerIndex - initialWriterIndex
} catch {
self.moveWriterIndex(to: initialWriterIndex)
throw error
}
}
// MARK: String APIs
/// Write `string` into this `ByteBuffer` using UTF-8 encoding, moving the writer index forward appropriately.
///
/// - Parameters:
/// - string: The string to write.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writeString(_ string: String) -> Int {
let written = self.setString(string, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Write `string` into this `ByteBuffer` null terminated using UTF-8 encoding, moving the writer index forward appropriately.
///
/// - Parameters:
/// - string: The string to write.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writeNullTerminatedString(_ string: String) -> Int {
let written = self.setNullTerminatedString(string, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
@inline(never)
@inlinable
mutating func _setStringSlowpath(_ string: String, at index: Int) -> Int {
// slow path, let's try to force the string to be native
if let written = (string + "").utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
return written
} else {
return self.setBytes(string.utf8, at: index)
}
}
/// Write `string` into this `ByteBuffer` at `index` using UTF-8 encoding. Does not move the writer index.
///
/// - Parameters:
/// - string: The string to write.
/// - index: The index for the first serialized byte.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func setString(_ string: String, at index: Int) -> Int {
// Do not implement setString via setSubstring. Before Swift version 5.3,
// Substring.UTF8View did not implement withContiguousStorageIfAvailable
// and therefore had no fast access to the backing storage.
if let written = string.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
// fast path, directly available
return written
} else {
return self._setStringSlowpath(string, at: index)
}
}
/// Write `string` null terminated into this `ByteBuffer` at `index` using UTF-8 encoding. Does not move the writer index.
///
/// - Parameters:
/// - string: The string to write.
/// - index: The index for the first serialized byte.
/// - Returns: The number of bytes written.
@inlinable
public mutating func setNullTerminatedString(_ string: String, at index: Int) -> Int {
let length = self.setString(string, at: index)
self.setInteger(UInt8(0), at: index &+ length)
return length &+ 1
}
/// Get the string at `index` from this `ByteBuffer` decoding using the UTF-8 encoding. Does not move the reader index.
/// The selected bytes must be readable or else `nil` will be returned.
///
/// - Parameters:
/// - index: The starting index into `ByteBuffer` containing the string of interest.
/// - length: The number of bytes making up the string.
/// - Returns: A `String` value containing the UTF-8 decoded selected bytes from this `ByteBuffer` or `nil` if
/// the requested bytes are not readable.
@inlinable
public func getString(at index: Int, length: Int) -> String? {
guard let range = self.rangeWithinReadableBytes(index: index, length: length) else {
return nil
}
return self.withUnsafeReadableBytes { pointer in
assert(range.lowerBound >= 0 && (range.upperBound - range.lowerBound) <= pointer.count)
return String(
decoding: UnsafeRawBufferPointer(rebasing: pointer[range]),
as: Unicode.UTF8.self
)
}
}
/// Get the string at `index` from this `ByteBuffer` decoding using the UTF-8 encoding. Does not move the reader index.
/// The selected bytes must be readable or else `nil` will be returned.
///
/// - Parameters:
/// - index: The starting index into `ByteBuffer` containing the null terminated string of interest.
/// - Returns: A `String` value deserialized from this `ByteBuffer` or `nil` if there isn't a complete null-terminated string,
/// including null-terminator, in the readable bytes after `index` in the buffer
@inlinable
public func getNullTerminatedString(at index: Int) -> String? {
guard let stringLength = self._getNullTerminatedStringLength(at: index) else {
return nil
}
return self.getString(at: index, length: stringLength)
}
@inlinable
func _getNullTerminatedStringLength(at index: Int) -> Int? {
guard self.readerIndex <= index && index < self.writerIndex else {
return nil
}
guard let endIndex = self.readableBytesView[index...].firstIndex(of: 0) else {
return nil
}
return endIndex &- index
}
/// Read `length` bytes off this `ByteBuffer`, decoding it as `String` using the UTF-8 encoding. Move the reader index forward by `length`.
///
/// - Parameters:
/// - length: The number of bytes making up the string.
/// - Returns: A `String` value deserialized from this `ByteBuffer` or `nil` if there aren't at least `length` bytes readable.
@inlinable
public mutating func readString(length: Int) -> String? {
guard let result = self.getString(at: self.readerIndex, length: length) else {
return nil
}
self._moveReaderIndex(forwardBy: length)
return result
}
/// Read a null terminated string off this `ByteBuffer`, decoding it as `String` using the UTF-8 encoding. Move the reader index
/// forward by the string's length and its null terminator.
///
/// - Returns: A `String` value deserialized from this `ByteBuffer` or `nil` if there isn't a complete null-terminated string,
/// including null-terminator, in the readable bytes of the buffer
@inlinable
public mutating func readNullTerminatedString() -> String? {
guard let stringLength = self._getNullTerminatedStringLength(at: self.readerIndex) else {
return nil
}
let result = self.readString(length: stringLength)
self.moveReaderIndex(forwardBy: 1) // move forward by null terminator
return result
}
// MARK: Substring APIs
/// Write `substring` into this `ByteBuffer` using UTF-8 encoding, moving the writer index forward appropriately.
///
/// - Parameters:
/// - substring: The substring to write.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writeSubstring(_ substring: Substring) -> Int {
let written = self.setSubstring(substring, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Write `substring` into this `ByteBuffer` at `index` using UTF-8 encoding. Does not move the writer index.
///
/// - Parameters:
/// - substring: The substring to write.
/// - index: The index for the first serialized byte.
/// - Returns: The number of bytes written
@discardableResult
@inlinable
public mutating func setSubstring(_ substring: Substring, at index: Int) -> Int {
// Substring.UTF8View implements withContiguousStorageIfAvailable starting with
// Swift version 5.3.
if let written = substring.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
// fast path, directly available
return written
} else {
// slow path, convert to string
return self.setString(String(substring), at: index)
}
}
/// Return a String decoded from the bytes at the current reader index using UTF-8 encoding.
///
/// This is equivalent to calling `getString(at: readerIndex, length: ...)` and does not advance the reader index.
///
/// - Parameter length: The number of bytes making up the string.
/// - Returns: A String containing the decoded bytes, or `nil` if the requested bytes are not readable.
@inlinable
public func peekString(length: Int) -> String? {
self.getString(at: self.readerIndex, length: length)
}
/// Return a null-terminated String starting at the current reader index.
///
/// This is equivalent to calling `getNullTerminatedString(at: readerIndex)` and does not advance the reader index.
///
/// - Returns: A String decoded from the null-terminated bytes, or `nil` if a complete null-terminated string is not available.
@inlinable
public func peekNullTerminatedString() -> String? {
self.getNullTerminatedString(at: self.readerIndex)
}
#if canImport(Dispatch)
// MARK: DispatchData APIs
/// Write `dispatchData` into this `ByteBuffer`, moving the writer index forward appropriately.
///
/// - Parameters:
/// - dispatchData: The `DispatchData` instance to write to the `ByteBuffer`.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func writeDispatchData(_ dispatchData: DispatchData) -> Int {
let written = self.setDispatchData(dispatchData, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Write `dispatchData` into this `ByteBuffer` at `index`. Does not move the writer index.
///
/// - Parameters:
/// - dispatchData: The `DispatchData` to write.
/// - index: The index for the first serialized byte.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func setDispatchData(_ dispatchData: DispatchData, at index: Int) -> Int {
let allBytesCount = dispatchData.count
self.reserveCapacity(index + allBytesCount)
self.withVeryUnsafeMutableBytes { destCompleteStorage in
assert(destCompleteStorage.count >= index + allBytesCount)
let dest = destCompleteStorage[index..<index + allBytesCount]
dispatchData.copyBytes(to: .init(rebasing: dest), count: dest.count)
}
return allBytesCount
}
/// Get the bytes at `index` from this `ByteBuffer` as a `DispatchData`. Does not move the reader index.
/// The selected bytes must be readable or else `nil` will be returned.
///
/// - Parameters:
/// - index: The starting index into `ByteBuffer` containing the string of interest.
/// - length: The number of bytes.
/// - Returns: A `DispatchData` value deserialized from this `ByteBuffer` or `nil` if the requested bytes
/// are not readable.
@inlinable
public func getDispatchData(at index: Int, length: Int) -> DispatchData? {
guard let range = self.rangeWithinReadableBytes(index: index, length: length) else {
return nil
}
return self.withUnsafeReadableBytes { pointer in
DispatchData(bytes: UnsafeRawBufferPointer(rebasing: pointer[range]))
}
}
/// Read `length` bytes off this `ByteBuffer` and return them as a `DispatchData`. Move the reader index forward by `length`.
///
/// - Parameters:
/// - length: The number of bytes.
/// - Returns: A `DispatchData` value containing the bytes from this `ByteBuffer` or `nil` if there aren't at least `length` bytes readable.
@inlinable
public mutating func readDispatchData(length: Int) -> DispatchData? {
guard let result = self.getDispatchData(at: self.readerIndex, length: length) else {
return nil
}
self._moveReaderIndex(forwardBy: length)
return result
}
/// Return a DispatchData object containing the bytes at the current reader index.
///
/// This is equivalent to calling `getDispatchData(at: readerIndex, length: ...)` and does not advance the reader index.
///
/// - Parameter length: The number of bytes to be retrieved.
/// - Returns: A DispatchData object, or `nil` if the requested bytes are not readable.
@inlinable
public func peekDispatchData(length: Int) -> DispatchData? {
self.getDispatchData(at: self.readerIndex, length: length)
}
#endif
// MARK: Other APIs
/// Yields an immutable buffer pointer containing this `ByteBuffer`'s readable bytes. Will move the reader index
/// by the number of bytes returned by `body`.
///
/// - warning: Do not escape the pointer from the closure for later use.
///
/// - Parameters:
/// - body: The closure that will accept the yielded bytes and returns the number of bytes it processed.
/// - Returns: The number of bytes read.
@discardableResult
@inlinable
public mutating func readWithUnsafeReadableBytes(_ body: (UnsafeRawBufferPointer) throws -> Int) rethrows -> Int {
let bytesRead = try self.withUnsafeReadableBytes({ try body($0) })
self._moveReaderIndex(forwardBy: bytesRead)
return bytesRead
}
/// Yields a mutable buffer pointer containing this `ByteBuffer`'s readable bytes. You may modify the yielded bytes.
/// Will move the reader index by the number of bytes returned by `body` but leave writer index as it was.
///
/// - warning: Do not escape the pointer from the closure for later use.
///
/// - Parameters:
/// - body: The closure that will accept the yielded bytes and returns the number of bytes it processed.
/// - Returns: The number of bytes read.
@discardableResult
@inlinable
public mutating func readWithUnsafeMutableReadableBytes(
_ body: (UnsafeMutableRawBufferPointer) throws -> Int
) rethrows -> Int {
let bytesRead = try self.withUnsafeMutableReadableBytes({ try body($0) })
self._moveReaderIndex(forwardBy: bytesRead)
return bytesRead
}
/// Copy `buffer`'s readable bytes into this `ByteBuffer` starting at `index`. Does not move any of the reader or writer indices.
///
/// - Parameters:
/// - buffer: The `ByteBuffer` to copy.
/// - index: The index for the first byte.
/// - Returns: The number of bytes written.
@discardableResult
@available(*, deprecated, renamed: "setBuffer(_:at:)")
public mutating func set(buffer: ByteBuffer, at index: Int) -> Int {
self.setBuffer(buffer, at: index)
}
/// Copy `buffer`'s readable bytes into this `ByteBuffer` starting at `index`. Does not move any of the reader or writer indices.
///
/// - Parameters:
/// - buffer: The `ByteBuffer` to copy.
/// - index: The index for the first byte.
/// - Returns: The number of bytes written.
@discardableResult
@inlinable
public mutating func setBuffer(_ buffer: ByteBuffer, at index: Int) -> Int {
buffer.withUnsafeReadableBytes { p in
self.setBytes(p, at: index)
}
}
/// Write `buffer`'s readable bytes into this `ByteBuffer` starting at `writerIndex`. This will move both this
/// `ByteBuffer`'s writer index as well as `buffer`'s reader index by the number of bytes readable in `buffer`.
///
/// - Parameters:
/// - buffer: The `ByteBuffer` to write.
/// - Returns: The number of bytes written to this `ByteBuffer` which is equal to the number of bytes read from `buffer`.
@discardableResult
@inlinable
public mutating func writeBuffer(_ buffer: inout ByteBuffer) -> Int {
let written = self.setBuffer(buffer, at: writerIndex)
self._moveWriterIndex(forwardBy: written)
buffer._moveReaderIndex(forwardBy: written)
return written
}
/// Write `bytes`, a `Sequence` of `UInt8` into this `ByteBuffer`. Moves the writer index forward by the number of bytes written.
///
/// - Parameters:
/// - bytes: A `Collection` of `UInt8` to be written.
/// - Returns: The number of bytes written or `bytes.count`.
@discardableResult
@inlinable
public mutating func writeBytes<Bytes: Sequence>(_ bytes: Bytes) -> Int where Bytes.Element == UInt8 {
let written = self.setBytes(bytes, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Write `bytes` into this `ByteBuffer`. Moves the writer index forward by the number of bytes written.
///
/// - Parameters:
/// - bytes: An `UnsafeRawBufferPointer`
/// - Returns: The number of bytes written or `bytes.count`.
@discardableResult
@inlinable
public mutating func writeBytes(_ bytes: UnsafeRawBufferPointer) -> Int {
let written = self.setBytes(bytes, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
#if compiler(>=6.2)
/// Write `bytes` into this `ByteBuffer`. Moves the writer index forward by the number of bytes written.
///
/// - Parameters:
/// - bytes: A `RawSpan`
/// - Returns: The number of bytes written or `bytes.byteCount`.
@discardableResult
@inlinable
@available(macOS 26, iOS 26, tvOS 26, watchOS 26, visionOS 26, *)
public mutating func writeBytes(_ bytes: RawSpan) -> Int {
let written = self.setBytes(bytes, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
#endif
/// Writes `byte` `count` times. Moves the writer index forward by the number of bytes written.
///
/// - Parameters:
/// - byte: The `UInt8` byte to repeat.
/// - count: How many times to repeat the given `byte`
/// - Returns: How many bytes were written.
@discardableResult
@inlinable
public mutating func writeRepeatingByte(_ byte: UInt8, count: Int) -> Int {
let written = self.setRepeatingByte(byte, count: count, at: self.writerIndex)
self._moveWriterIndex(forwardBy: written)
return written
}
/// Sets the given `byte` `count` times at the given `index`. Will reserve more memory if necessary. Does not move the writer index.
///
/// - Parameters:
/// - byte: The `UInt8` byte to repeat.
/// - count: How many times to repeat the given `byte`
/// - index: The starting index of the bytes into the `ByteBuffer`.
/// - Returns: How many bytes were written.
@discardableResult
@inlinable
public mutating func setRepeatingByte(_ byte: UInt8, count: Int, at index: Int) -> Int {
precondition(count >= 0, "Can't write fewer than 0 bytes")
self.reserveCapacity(index + count)
self.withVeryUnsafeMutableBytes { pointer in
let dest = UnsafeMutableRawBufferPointer(rebasing: pointer[index..<index + count])
_ = dest.initializeMemory(as: UInt8.self, repeating: byte)
}
return count
}
/// Slice the readable bytes off this `ByteBuffer` without modifying the reader index. This method will return a
/// `ByteBuffer` sharing the underlying storage with the `ByteBuffer` the method was invoked on. The returned
/// `ByteBuffer` will contain the bytes in the range `readerIndex..<writerIndex` of the original `ByteBuffer`.
///
/// - Note: Because `ByteBuffer` implements copy-on-write a copy of the storage will be automatically triggered when either of the `ByteBuffer`s sharing storage is written to.
///
/// - Returns: A `ByteBuffer` sharing storage containing the readable bytes only.
@inlinable
public func slice() -> ByteBuffer {
// must work, bytes definitely in the buffer// must work, bytes definitely in the buffer
self.getSlice(at: self.readerIndex, length: self.readableBytes)!
}
/// Slice `length` bytes off this `ByteBuffer` and move the reader index forward by `length`.
/// If enough bytes are readable the `ByteBuffer` returned by this method will share the underlying storage with
/// the `ByteBuffer` the method was invoked on.
/// The returned `ByteBuffer` will contain the bytes in the range `readerIndex..<(readerIndex + length)` of the
/// original `ByteBuffer`.
/// The `readerIndex` of the returned `ByteBuffer` will be `0`, the `writerIndex` will be `length`.
///
/// - Note: Because `ByteBuffer` implements copy-on-write a copy of the storage will be automatically triggered when either of the `ByteBuffer`s sharing storage is written to.
///
/// - Parameters:
/// - length: The number of bytes to slice off.
/// - Returns: A `ByteBuffer` sharing storage containing `length` bytes or `nil` if the not enough bytes were readable.
@inlinable
public mutating func readSlice(length: Int) -> ByteBuffer? {
guard let result = self.getSlice_inlineAlways(at: self.readerIndex, length: length) else {
return nil
}
self._moveReaderIndex(forwardBy: length)
return result
}
@discardableResult
@inlinable
public mutating func writeImmutableBuffer(_ buffer: ByteBuffer) -> Int {
var mutable = buffer
return self.writeBuffer(&mutable)
}
}
// swift-format-ignore: AmbiguousTrailingClosureOverload
extension ByteBuffer {
/// Yields a mutable buffer pointer containing this `ByteBuffer`'s readable bytes. You may modify the yielded bytes.
/// Will move the reader index by the number of bytes `body` returns in the first tuple component but leave writer index as it was.
///
/// - warning: Do not escape the pointer from the closure for later use.
///
/// - Parameters:
/// - body: The closure that will accept the yielded bytes and returns the number of bytes it processed along with some other value.
/// - Returns: The value `body` returned in the second tuple component.
@inlinable
public mutating func readWithUnsafeMutableReadableBytes<T>(
_ body: (UnsafeMutableRawBufferPointer) throws -> (Int, T)
) rethrows -> T {
let (bytesRead, ret) = try self.withUnsafeMutableReadableBytes({ try body($0) })
self._moveReaderIndex(forwardBy: bytesRead)
return ret
}
/// Yields an immutable buffer pointer containing this `ByteBuffer`'s readable bytes. Will move the reader index
/// by the number of bytes `body` returns in the first tuple component.
///
/// - warning: Do not escape the pointer from the closure for later use.
///
/// - Parameters:
/// - body: The closure that will accept the yielded bytes and returns the number of bytes it processed along with some other value.
/// - Returns: The value `body` returned in the second tuple component.
@inlinable
public mutating func readWithUnsafeReadableBytes<T>(
_ body: (UnsafeRawBufferPointer) throws -> (Int, T)
) rethrows -> T {
let (bytesRead, ret) = try self.withUnsafeReadableBytes({ try body($0) })
self._moveReaderIndex(forwardBy: bytesRead)
return ret
}
}
extension ByteBuffer {
/// Return an empty `ByteBuffer` allocated with `ByteBufferAllocator()`.
///
/// Calling this constructor will not allocate because it will return a `ByteBuffer` that wraps a shared storage
/// object. As soon as you write to the constructed buffer however, you will incur an allocation because a
/// copy-on-write will happen.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` it is
/// recommended using `channel.allocator.buffer(capacity: 0)`. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init() {
self = ByteBufferAllocator.zeroCapacityWithDefaultAllocator
}
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space using
/// the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(string:)`. Or if you want to write multiple items into the
/// buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeString` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(string: String) {
self = ByteBufferAllocator().buffer(string: string)
}
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space using
/// the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(substring:)`. Or if you want to write multiple items into
/// the buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeSubstring` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(substring string: Substring) {
self = ByteBufferAllocator().buffer(substring: string)
}
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space using
/// the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(staticString:)`. Or if you want to write multiple items into
/// the buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeStaticString` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(staticString string: StaticString) {
self = ByteBufferAllocator().buffer(staticString: string)
}
/// Create a fresh `ByteBuffer` containing the `bytes`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `bytes` and potentially some extra space using
/// the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(bytes:)`. Or if you want to write multiple items into the
/// buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeBytes` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init<Bytes: Sequence>(bytes: Bytes) where Bytes.Element == UInt8 {
self = ByteBufferAllocator().buffer(bytes: bytes)
}
/// Create a fresh `ByteBuffer` containing the bytes of the byte representation in the given `endianness` of
/// `integer`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `integer` and potentially some extra space using
/// the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(integer:)`. Or if you want to write multiple items into the
/// buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeInteger` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init<I: FixedWidthInteger>(integer: I, endianness: Endianness = .big, as: I.Type = I.self) {
self = ByteBufferAllocator().buffer(integer: integer, endianness: endianness, as: `as`)
}
/// Create a fresh `ByteBuffer` containing `count` repetitions of `byte`.
///
/// This will allocate a new `ByteBuffer` with at least `count` bytes.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(repeating:count:)`. Or if you want to write multiple items
/// into the buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeRepeatingByte` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(repeating byte: UInt8, count: Int) {
self = ByteBufferAllocator().buffer(repeating: byte, count: count)
}
/// Create a fresh `ByteBuffer` containing the readable bytes of `buffer`.
///
/// This may allocate a new `ByteBuffer` with enough space to fit `buffer` and potentially some extra space using
/// the default allocator.
///
/// - Note: Use this method only if you deliberately want to reallocate a potentially smaller `ByteBuffer` than the
/// one you already have. Given that `ByteBuffer` is a value type, defensive copies are not necessary. If
/// you have a `ByteBuffer` but would like the `readerIndex` to start at `0`, consider `readSlice` instead.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(buffer:)`. Or if you want to write multiple items into the
/// buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeImmutableBuffer` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(buffer: ByteBuffer) {
self = ByteBufferAllocator().buffer(buffer: buffer)
}
#if canImport(Dispatch)
/// Create a fresh `ByteBuffer` containing the bytes contained in the given `DispatchData`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit the bytes of the `DispatchData` and potentially
/// some extra space using the default allocator.
///
/// - info: If you have access to a `Channel`, `ChannelHandlerContext`, or `ByteBufferAllocator` we
/// recommend using `channel.allocator.buffer(dispatchData:)`. Or if you want to write multiple items into
/// the buffer use `channel.allocator.buffer(capacity: ...)` to allocate a `ByteBuffer` of the right
/// size followed by a `writeDispatchData` instead of using this method. This allows SwiftNIO to do
/// accounting and optimisations of resources acquired for operations on a given `Channel` in the future.
@inlinable
public init(dispatchData: DispatchData) {
self = ByteBufferAllocator().buffer(dispatchData: dispatchData)
}
#endif
}
extension ByteBuffer: Codable {
/// Creates a ByteByffer by decoding from a Base64 encoded single value container.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let base64String = try container.decode(String.self)
self = try ByteBuffer(bytes: base64String._base64Decoded())
}
/// Encodes this buffer as a base64 string in a single value container.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
let base64String = String(_base64Encoding: self.readableBytesView)
try container.encode(base64String)
}
}
extension ByteBufferAllocator {
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(string: String) -> ByteBuffer {
var buffer = self.buffer(capacity: string.utf8.count)
buffer.writeString(string)
return buffer
}
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(substring string: Substring) -> ByteBuffer {
var buffer = self.buffer(capacity: string.utf8.count)
buffer.writeSubstring(string)
return buffer
}
/// Create a fresh `ByteBuffer` containing the bytes of the `string` encoded as UTF-8.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `string` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(staticString string: StaticString) -> ByteBuffer {
var buffer = self.buffer(capacity: string.utf8CodeUnitCount)
buffer.writeStaticString(string)
return buffer
}
/// Create a fresh `ByteBuffer` containing the `bytes`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `bytes` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer<Bytes: Sequence>(bytes: Bytes) -> ByteBuffer where Bytes.Element == UInt8 {
var buffer = self.buffer(capacity: bytes.underestimatedCount)
buffer.writeBytes(bytes)
return buffer
}
/// Create a fresh `ByteBuffer` containing the `bytes` decoded from the ASCII `plainHexEncodedBytes` string .
///
/// This will allocate a new `ByteBuffer` with enough space to fit `bytes` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@_disfavoredOverload
@inlinable
public func buffer(plainHexEncodedBytes string: String) throws -> ByteBuffer {
try buffer(plainHexEncodedBytes: string)
}
/// Create a fresh `ByteBuffer` containing the `bytes` decoded from the ASCII `plainHexEncodedBytes` string .
///
/// This will allocate a new `ByteBuffer` with enough space to fit `bytes` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(plainHexEncodedBytes string: some StringProtocol) throws -> ByteBuffer {
var buffer = self.buffer(capacity: string.utf8.count / 2)
try buffer.writePlainHexEncodedBytes(string)
return buffer
}
/// Create a fresh `ByteBuffer` containing the bytes of the byte representation in the given `endianness` of
/// `integer`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit `integer` and potentially some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer<I: FixedWidthInteger>(
integer: I,
endianness: Endianness = .big,
as: I.Type = I.self
) -> ByteBuffer {
var buffer = self.buffer(capacity: MemoryLayout<I>.size)
buffer.writeInteger(integer, endianness: endianness, as: `as`)
return buffer
}
/// Create a fresh `ByteBuffer` containing `count` repetitions of `byte`.
///
/// This will allocate a new `ByteBuffer` with at least `count` bytes.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(repeating byte: UInt8, count: Int) -> ByteBuffer {
var buffer = self.buffer(capacity: count)
buffer.writeRepeatingByte(byte, count: count)
return buffer
}
/// Create a fresh `ByteBuffer` containing the readable bytes of `buffer`.
///
/// This may allocate a new `ByteBuffer` with enough space to fit `buffer` and potentially some extra space.
///
/// - Note: Use this method only if you deliberately want to reallocate a potentially smaller `ByteBuffer` than the
/// one you already have. Given that `ByteBuffer` is a value type, defensive copies are not necessary. If
/// you have a `ByteBuffer` but would like the `readerIndex` to start at `0`, consider `readSlice` instead.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(buffer: ByteBuffer) -> ByteBuffer {
var newBuffer = self.buffer(capacity: buffer.readableBytes)
newBuffer.writeImmutableBuffer(buffer)
return newBuffer
}
#if canImport(Dispatch)
/// Create a fresh `ByteBuffer` containing the bytes contained in the given `DispatchData`.
///
/// This will allocate a new `ByteBuffer` with enough space to fit the bytes of the `DispatchData` and potentially
/// some extra space.
///
/// - Returns: The `ByteBuffer` containing the written bytes.
@inlinable
public func buffer(dispatchData: DispatchData) -> ByteBuffer {
var buffer = self.buffer(capacity: dispatchData.count)
buffer.writeDispatchData(dispatchData)
return buffer
}
#endif
}
extension Optional where Wrapped == ByteBuffer {
/// If `nil`, replace `self` with `.some(buffer)`. If non-`nil`, write `buffer`'s readable bytes into the
/// `ByteBuffer` starting at `writerIndex`.
///
/// This method will not modify `buffer`, meaning its `readerIndex` and `writerIndex` stays intact.
///
/// - Parameters:
/// - buffer: The `ByteBuffer` to write.
/// - Returns: The number of bytes written to this `ByteBuffer` which is equal to the number of `readableBytes` in
/// `buffer`.