ByteBuffer
public struct ByteBuffer
extension ByteBuffer: CustomStringConvertible
extension ByteBuffer: Equatable
extension ByteBuffer: Hashable
ByteBuffer
stores contiguously allocated raw bytes. It is a random and sequential accessible sequence of zero or
more bytes (octets).
Allocation
Use allocator.buffer(capacity: desiredCapacity)
to allocate a new ByteBuffer
.
Supported types
A variety of types can be read/written from/to a ByteBuffer
. Using Swift’s extension
mechanism you can easily
create ByteBuffer
support for your own data types. Out of the box, ByteBuffer
supports for example the following
types (non-exhaustive list):
String
/StaticString
- Swift’s various (unsigned) integer types
Foundation
‘sData
[UInt8]
and generally anyCollection
ofUInt8
Random Access
For every supported type ByteBuffer
usually contains two methods for random access:
get<Type>(at: Int, length: Int)
where<type>
is for exampleString
,Data
,Bytes
(for[UInt8]
)set<Type>(at: Int)
Example:
var buf = ...
buf.setString("Hello World", at: 0)
buf.moveWriterIndex(to: 11)
let helloWorld = buf.getString(at: 0, length: 11)
let written = buf.setInteger(17 as Int, at: 11)
buf.moveWriterIndex(forwardBy: written)
let seventeen: Int? = buf.getInteger(at: 11)
If needed, ByteBuffer
will automatically resize its storage to accommodate your set
request.
Sequential Access
ByteBuffer
provides two properties which are indices into the ByteBuffer
to support sequential access:
readerIndex
, the index of the next readable bytewriterIndex
, the index of the next byte to write
For every supported type ByteBuffer
usually contains two methods for sequential access:
read<Type>(length: Int)
to readlength
bytes from the currentreaderIndex
(and then advance the reader index bylength
bytes)write<Type>(Type)
to write, advancing thewriterIndex
by the appropriate amount
Example:
var buf = ...
buf.writeString("Hello World")
buf.writeInteger(17 as Int)
let helloWorld = buf.readString(length: 11)
let seventeen: Int = buf.readInteger()
Layout
+-------------------+------------------+------------------+
| discardable bytes | readable bytes | writable bytes |
| | (CONTENT) | |
+-------------------+------------------+------------------+
| | | |
0 <= readerIndex <= writerIndex <= capacity
The 'discardable bytes’ are usually bytes that have already been read, they can however still be accessed using
the random access methods. ‘Readable bytes’ are the bytes currently available to be read using the sequential
access interface (read<Type>
/write<Type>
). Getting writableBytes
(bytes beyond the writer index) is undefined
behaviour and might yield arbitrary bytes (not 0
initialised).
Slicing
ByteBuffer
supports slicing a ByteBuffer
without copying the underlying storage.
Example:
var buf = ...
let dataBytes: [UInt8] = [0xca, 0xfe, 0xba, 0xbe]
let dataBytesLength = UInt32(dataBytes.count)
buf.writeInteger(dataBytesLength) /* the header */
buf.writeBytes(dataBytes) /* the data */
let bufDataBytesOnly = buf.getSlice(at: 4, length: dataBytes.count)
/* `bufDataByteOnly` and `buf` will share their storage */
Notes
All ByteBuffer
methods that don’t contain the word ‘unsafe’ will only allow you to access the ‘readable bytes’.
-
Undocumented
Declaration
Swift
public typealias _Index = UInt32
-
Undocumented
Declaration
Swift
public typealias _Capacity = UInt32
-
The number of bytes writable until
ByteBuffer
will need to grow its underlying storage which will likely trigger a copy of the bytes.Declaration
Swift
@inlinable public var writableBytes: Int { get }
-
The number of bytes readable (
readableBytes
=writerIndex
-readerIndex
).Declaration
Swift
@inlinable public var readableBytes: Int { get }
-
The current capacity of the storage of this
ByteBuffer
, this is not constant and does not signify the number of bytes that have been written to thisByteBuffer
.Declaration
Swift
public var capacity: Int { get }
-
The current capacity of the underlying storage of this
ByteBuffer
. A COW slice of the buffer (e.g. readSlice(length: x)) will posses the same storageCapacity as the original buffer until new data is written.Declaration
Swift
public var storageCapacity: Int { get }
-
Reserves enough space to store the specified number of bytes.
This method will ensure that the buffer has space for at least as many bytes as requested. This includes any bytes already stored, and completely disregards the reader/writer indices. If the buffer already has space to store the requested number of bytes, this method will be a no-op.
Declaration
Swift
public mutating func reserveCapacity(_ minimumCapacity: Int)
Parameters
minimumCapacity
The minimum number of bytes this buffer must be able to store.
-
Reserves enough space to write at least the specified number of bytes.
This method will ensure that the buffer has enough writable space for at least as many bytes as requested. If the buffer already has space to write the requested number of bytes, this method will be a no-op.
Declaration
Swift
public mutating func reserveCapacity(minimumWritableBytes: Int)
Parameters
minimumWritableBytes
The minimum number of writable bytes this buffer must have.
-
Yields a mutable buffer pointer containing this
ByteBuffer
‘s readable bytes. You may modify those bytes.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@inlinable public mutating func withUnsafeMutableReadableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes.
Return Value
The value returned by
body
. -
Yields the bytes currently writable (
bytesWritable
=capacity
-writerIndex
). Before reading those bytes you must first write to them otherwise you will trigger undefined behaviour. The writer index will remain unchanged.Note
In almost all cases you should use
writeWithUnsafeMutableBytes
which will move the write pointer instead of this methodWarning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@inlinable public mutating func withUnsafeMutableWritableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes and return the number of bytes written.
Return Value
The number of bytes written.
-
This vends a pointer of the
ByteBuffer
at thewriterIndex
after ensuring that the buffer has at leastminimumWritableBytes
of writable bytes available.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@discardableResult @inlinable public mutating func writeWithUnsafeMutableBytes(minimumWritableBytes: Int, _ body: (UnsafeMutableRawBufferPointer) throws -> Int) rethrows -> Int
Parameters
minimumWritableBytes
The number of writable bytes to reserve capacity for before vending the
ByteBuffer
pointer tobody
.body
The closure that will accept the yielded bytes and return the number of bytes written.
Return Value
The number of bytes written.
-
Undocumented
Declaration
Swift
@discardableResult @inlinable public mutating func writeWithUnsafeMutableBytes(_ body: (UnsafeMutableRawBufferPointer) throws -> Int) rethrows -> Int
-
This vends a pointer to the storage of the
ByteBuffer
. It’s marked as very unsafe because it might contain uninitialised memory and it’s undefined behaviour to read it. In most cases you should usewithUnsafeReadableBytes
.Warning
Do not escape the pointer from the closure for later use.Declaration
Swift
@inlinable public func withVeryUnsafeBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T
-
This vends a pointer to the storage of the
ByteBuffer
. It’s marked as very unsafe because it might contain uninitialised memory and it’s undefined behaviour to read it. In most cases you should usewithUnsafeMutableWritableBytes
.Warning
Do not escape the pointer from the closure for later use.Declaration
Swift
@inlinable public mutating func withVeryUnsafeMutableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T
-
Yields a buffer pointer containing this
ByteBuffer
‘s readable bytes.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@inlinable public func withUnsafeReadableBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes.
Return Value
The value returned by
body
. -
Yields a buffer pointer containing this
ByteBuffer
‘s readable bytes. You may hold a pointer to those bytes even after the closure returned iff you model the lifetime of those bytes correctly using theUnmanaged
instance. If you don’t require the pointer after the closure returns, usewithUnsafeReadableBytes
.If you escape the pointer from the closure, you must call
storageManagement.retain()
to get ownership to the bytes and you also must callstorageManagement.release()
if you no longer require those bytes. Calls toretain
andrelease
must be balanced.Declaration
Swift
@inlinable public func withUnsafeReadableBytesWithStorageManagement<T>(_ body: (UnsafeRawBufferPointer, Unmanaged<AnyObject>) throws -> T) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes and the
storageManagement
.Return Value
The value returned by
body
. -
See
withUnsafeReadableBytesWithStorageManagement
andwithVeryUnsafeBytes
.Declaration
Swift
@inlinable public func withVeryUnsafeBytesWithStorageManagement<T>(_ body: (UnsafeRawBufferPointer, Unmanaged<AnyObject>) throws -> T) rethrows -> T
-
Returns a slice of size
length
bytes, starting atindex
. TheByteBuffer
this is invoked on and theByteBuffer
returned will share the same underlying storage. However, the byte atindex
in thisByteBuffer
will correspond to index0
in the returnedByteBuffer
. ThereaderIndex
of the returnedByteBuffer
will be0
, thewriterIndex
will belength
.The selected bytes must be readable or else
nil
will be returned.Declaration
Swift
public func getSlice(at index: Int, length: Int) -> ByteBuffer?
Parameters
index
The index the requested slice starts at.
length
The length of the requested slice.
Return Value
A
ByteBuffer
containing the selected bytes as readable bytes ornil
if the selected bytes were not readable in the initialByteBuffer
. -
Discard the bytes before the reader index. The byte at index
readerIndex
before calling this method will be at index0
after the call returns.Declaration
Swift
@discardableResult public mutating func discardReadBytes() -> Bool
Return Value
true
if one or more bytes have been discarded,false
if there are no bytes to discard. -
The reader index or the number of bytes previously read from this
ByteBuffer
.readerIndex
is0
for a newly allocatedByteBuffer
.Declaration
Swift
@inlinable public var readerIndex: Int { get }
-
The write index or the number of bytes previously written to this
ByteBuffer
.writerIndex
is0
for a newly allocatedByteBuffer
.Declaration
Swift
@inlinable public var writerIndex: Int { get }
-
Set both reader index and writer index to
0
. This will reset the state of thisByteBuffer
to the state of a freshly allocated one, if possible without allocations. This is the cheapest way to recycle aByteBuffer
for a new use-case.Note
This method will allocate if the underlying storage is referenced by anotherByteBuffer
. Even if an allocation is necessary this will be cheaper as the copy of the storage is elided.Declaration
Swift
public mutating func clear()
-
Set both reader index and writer index to
0
. This will reset the state of thisByteBuffer
to the state of a freshly allocated one, if possible without allocations. This is the cheapest way to recycle aByteBuffer
for a new use-case.Note
This method will allocate if the underlying storage is referenced by another
ByteBuffer
. Even if an allocation is necessary this will be cheaper as the copy of the storage is elided.Declaration
Swift
@available(*, deprecated, message: "Use an `Int` as the argument") public mutating func clear(minimumCapacity: UInt32)
Parameters
minimumCapacity
The minimum capacity that will be (re)allocated for this buffer
-
Set both reader index and writer index to
0
. This will reset the state of thisByteBuffer
to the state of a freshly allocated one, if possible without allocations. This is the cheapest way to recycle aByteBuffer
for a new use-case.Note
This method will allocate if the underlying storage is referenced by another
ByteBuffer
. Even if an allocation is necessary this will be cheaper as the copy of the storage is elided.Declaration
Swift
public mutating func clear(minimumCapacity: Int)
Parameters
minimumCapacity
The minimum capacity that will be (re)allocated for this buffer
-
Get
length
bytes starting atindex
and return the result as[UInt8]
. This will not change the reader index. The selected bytes must be readable or elsenil
will be returned.Declaration
Swift
public func getBytes(at index: Int, length: Int) -> [UInt8]?
Parameters
index
The starting index of the bytes of interest into the
ByteBuffer
.length
The number of bytes of interest.
Return Value
A
[UInt8]
value containing the bytes of interest ornil
if the bytesByteBuffer
are not readable. -
Read
length
bytes off thisByteBuffer
, move the reader index forward bylength
bytes and return the result as[UInt8]
.Declaration
Swift
public mutating func readBytes(length: Int) -> [UInt8]?
Parameters
length
The number of bytes to be read from this
ByteBuffer
.Return Value
A
[UInt8]
value containinglength
bytes ornil
if there aren’t at leastlength
bytes readable.
-
Write the static
string
into thisByteBuffer
using UTF-8 encoding, moving the writer index forward appropriately.Declaration
Swift
@discardableResult public mutating func writeStaticString(_ string: StaticString) -> Int
Parameters
string
The string to write.
Return Value
The number of bytes written.
-
Write the static
string
into thisByteBuffer
atindex
using UTF-8 encoding, moving the writer index forward appropriately.Declaration
Swift
public mutating func setStaticString(_ string: StaticString, at index: Int) -> Int
Parameters
string
The string to write.
index
The index for the first serialized byte.
Return Value
The number of bytes written.
-
Write
string
into thisByteBuffer
using UTF-8 encoding, moving the writer index forward appropriately.Declaration
Swift
@discardableResult public mutating func writeString(_ string: String) -> Int
Parameters
string
The string to write.
Return Value
The number of bytes written.
-
Write
string
into thisByteBuffer
atindex
using UTF-8 encoding. Does not move the writer index.Declaration
Swift
@discardableResult @inlinable public mutating func setString(_ string: String, at index: Int) -> Int
Parameters
string
The string to write.
index
The index for the first serialized byte.
Return Value
The number of bytes written.
-
Get the string at
index
from thisByteBuffer
decoding using the UTF-8 encoding. Does not move the reader index. The selected bytes must be readable or elsenil
will be returned.Declaration
Swift
public func getString(at index: Int, length: Int) -> String?
Parameters
index
The starting index into
ByteBuffer
containing the string of interest.length
The number of bytes making up the string.
Return Value
A
String
value containing the UTF-8 decoded selected bytes from thisByteBuffer
ornil
if the requested bytes are not readable. -
Read
length
bytes off thisByteBuffer
, decoding it asString
using the UTF-8 encoding. Move the reader index forward bylength
.Declaration
Swift
public mutating func readString(length: Int) -> String?
Parameters
length
The number of bytes making up the string.
Return Value
A
String
value deserialized from thisByteBuffer
ornil
if there aren’t at leastlength
bytes readable.
-
Write
substring
into thisByteBuffer
using UTF-8 encoding, moving the writer index forward appropriately.Declaration
Swift
@discardableResult public mutating func writeSubstring(_ substring: Substring) -> Int
Parameters
substring
The substring to write.
Return Value
The number of bytes written.
-
Write
substring
into thisByteBuffer
atindex
using UTF-8 encoding. Does not move the writer index.Declaration
Swift
@discardableResult @inlinable public mutating func setSubstring(_ substring: Substring, at index: Int) -> Int
Parameters
substring
The substring to write.
index
The index for the first serilized byte.
Return Value
The number of bytes written
-
Write
dispatchData
into thisByteBuffer
, moving the writer index forward appropriately.Declaration
Swift
@discardableResult public mutating func writeDispatchData(_ dispatchData: DispatchData) -> Int
Parameters
dispatchData
The
DispatchData
instance to write to theByteBuffer
.Return Value
The number of bytes written.
-
Write
dispatchData
into thisByteBuffer
atindex
. Does not move the writer index.Declaration
Swift
@discardableResult public mutating func setDispatchData(_ dispatchData: DispatchData, at index: Int) -> Int
Parameters
dispatchData
The
DispatchData
to write.index
The index for the first serialized byte.
Return Value
The number of bytes written.
-
Get the bytes at
index
from thisByteBuffer
as aDispatchData
. Does not move the reader index. The selected bytes must be readable or elsenil
will be returned.Declaration
Swift
public func getDispatchData(at index: Int, length: Int) -> DispatchData?
Parameters
index
The starting index into
ByteBuffer
containing the string of interest.length
The number of bytes.
Return Value
A
DispatchData
value deserialized from thisByteBuffer
ornil
if the requested bytes are not readable. -
Read
length
bytes off thisByteBuffer
and return them as aDispatchData
. Move the reader index forward bylength
.Declaration
Swift
public mutating func readDispatchData(length: Int) -> DispatchData?
Parameters
length
The number of bytes.
Return Value
A
DispatchData
value containing the bytes from thisByteBuffer
ornil
if there aren’t at leastlength
bytes readable.
-
Yields an immutable buffer pointer containing this
ByteBuffer
‘s readable bytes. Will move the reader index by the number of bytes returned bybody
.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@discardableResult @inlinable public mutating func readWithUnsafeReadableBytes(_ body: (UnsafeRawBufferPointer) throws -> Int) rethrows -> Int
Parameters
body
The closure that will accept the yielded bytes and returns the number of bytes it processed.
Return Value
The number of bytes read.
-
Yields an immutable buffer pointer containing this
ByteBuffer
‘s readable bytes. Will move the reader index by the number of bytesbody
returns in the first tuple component.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@inlinable public mutating func readWithUnsafeReadableBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> (Int, T)) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes and returns the number of bytes it processed along with some other value.
Return Value
The value
body
returned in the second tuple component. -
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 bybody
but leave writer index as it was.Warning
Do not escape the pointer from the closure for later use.
Declaration
Swift
@discardableResult @inlinable public mutating func readWithUnsafeMutableReadableBytes(_ body: (UnsafeMutableRawBufferPointer) throws -> Int) rethrows -> Int
Parameters
body
The closure that will accept the yielded bytes and returns the number of bytes it processed.
Return Value
The number of bytes read.
-
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 bytesbody
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.
Declaration
Swift
@inlinable public mutating func readWithUnsafeMutableReadableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> (Int, T)) rethrows -> T
Parameters
body
The closure that will accept the yielded bytes and returns the number of bytes it processed along with some other value.
Return Value
The value
body
returned in the second tuple component. -
Copy
buffer
‘s readable bytes into thisByteBuffer
starting atindex
. Does not move any of the reader or writer indices.Declaration
Swift
@available(*, deprecated, renamed: "setBuffer(_:at:﹚") @discardableResult public mutating func set(buffer: ByteBuffer, at index: Int) -> Int
Parameters
buffer
The
ByteBuffer
to copy.index
The index for the first byte.
Return Value
The number of bytes written.
-
Copy
buffer
‘s readable bytes into thisByteBuffer
starting atindex
. Does not move any of the reader or writer indices.Declaration
Swift
@discardableResult public mutating func setBuffer(_ buffer: ByteBuffer, at index: Int) -> Int
Parameters
buffer
The
ByteBuffer
to copy.index
The index for the first byte.
Return Value
The number of bytes written.
-
Write
buffer
‘s readable bytes into thisByteBuffer
starting atwriterIndex
. This will move both thisByteBuffer
’s writer index as well asbuffer
’s reader index by the number of bytes readable inbuffer
.Declaration
Swift
@discardableResult public mutating func writeBuffer(_ buffer: inout ByteBuffer) -> Int
Parameters
buffer
The
ByteBuffer
to write.Return Value
The number of bytes written to this
ByteBuffer
which is equal to the number of bytes read frombuffer
. -
Write
bytes
, aSequence
ofUInt8
into thisByteBuffer
. Moves the writer index forward by the number of bytes written.Declaration
Swift
@discardableResult @inlinable public mutating func writeBytes<Bytes>(_ bytes: Bytes) -> Int where Bytes : Sequence, Bytes.Element == UInt8
Parameters
bytes
A
Collection
ofUInt8
to be written.Return Value
The number of bytes written or
bytes.count
. -
Write
bytes
into thisByteBuffer
. Moves the writer index forward by the number of bytes written.Declaration
Swift
@discardableResult @inlinable public mutating func writeBytes(_ bytes: UnsafeRawBufferPointer) -> Int
Parameters
bytes
An
UnsafeRawBufferPointer
Return Value
The number of bytes written or
bytes.count
. -
Writes
byte
count
times. Moves the writer index forward by the number of bytes written.Declaration
Swift
@discardableResult public mutating func writeRepeatingByte(_ byte: UInt8, count: Int) -> Int
Parameters
byte
The
UInt8
byte to repeat.count
How many times to repeat the given
byte
Return Value
How many bytes were written.
-
Sets the given
byte
count
times at the givenindex
. Will reserve more memory if necessary. Does not move the writer index.Declaration
Swift
@discardableResult public mutating func setRepeatingByte(_ byte: UInt8, count: Int, at index: Int) -> Int
Parameters
byte
The
UInt8
byte to repeat.count
How many times to repeat the given
byte
Return Value
How many bytes were written.
-
Slice the readable bytes off this
ByteBuffer
without modifying the reader index. This method will return aByteBuffer
sharing the underlying storage with theByteBuffer
the method was invoked on. The returnedByteBuffer
will contain the bytes in the rangereaderIndex..<writerIndex
of the originalByteBuffer
.Note
Because
ByteBuffer
implements copy-on-write a copy of the storage will be automatically triggered when either of theByteBuffer
s sharing storage is written to.Declaration
Swift
public func slice() -> ByteBuffer
Return Value
A
ByteBuffer
sharing storage containing the readable bytes only. -
Slice
length
bytes off thisByteBuffer
and move the reader index forward bylength
. If enough bytes are readable theByteBuffer
returned by this method will share the underlying storage with theByteBuffer
the method was invoked on. The returnedByteBuffer
will contain the bytes in the rangereaderIndex..<(readerIndex + length)
of the originalByteBuffer
. ThereaderIndex
of the returnedByteBuffer
will be0
, thewriterIndex
will belength
.Note
Because
ByteBuffer
implements copy-on-write a copy of the storage will be automatically triggered when either of theByteBuffer
s sharing storage is written to.Declaration
Swift
public mutating func readSlice(length: Int) -> ByteBuffer?
Parameters
length
The number of bytes to slice off.
Return Value
A
ByteBuffer
sharing storage containinglength
bytes ornil
if the not enough bytes were readable. -
Undocumented
Declaration
Swift
@discardableResult public mutating func writeImmutableBuffer(_ buffer: ByteBuffer) -> Int
-
Return an empty
ByteBuffer
allocated withByteBufferAllocator()
.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
, orByteBufferAllocator
it is recommended usingchannel.allocator.buffer(capacity: 0)
. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
@inlinable public init()
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing the bytes of thestring
encoded as UTF-8.This will allocate a new
ByteBuffer
with enough space to fitstring
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(string:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteString
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(string: String)
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing the bytes of thestring
encoded as UTF-8.This will allocate a new
ByteBuffer
with enough space to fitstring
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(substring:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteSubstring
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(substring string: Substring)
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing the bytes of thestring
encoded as UTF-8.This will allocate a new
ByteBuffer
with enough space to fitstring
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(staticString:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteStaticString
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(staticString string: StaticString)
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing thebytes
.This will allocate a new
ByteBuffer
with enough space to fitbytes
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(bytes:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteBytes
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
@inlinable public init<Bytes>(bytes: Bytes) where Bytes : Sequence, Bytes.Element == UInt8
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing the bytes of the byte representation in the givenendianness
ofinteger
.This will allocate a new
ByteBuffer
with enough space to fitinteger
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(integer:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteInteger
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
@inlinable public init<I>(integer: I, endianness: Endianness = .big, as: I.Type = I.self) where I : FixedWidthInteger
- info: If you have access to a
-
Create a fresh
ByteBuffer
containingcount
repetitions ofbyte
.This will allocate a new
ByteBuffer
with at leastcount
bytes.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(repeating:count:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteRepeatingByte
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(repeating byte: UInt8, count: Int)
- info: If you have access to a
-
Create a fresh
ByteBuffer
containing the readable bytes ofbuffer
.This may allocate a new
ByteBuffer
with enough space to fitbuffer
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 thatByteBuffer
is a value type, defensive copies are not necessary. If you have aByteBuffer
but would like thereaderIndex
to start at0
, considerreadSlice
instead.info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(buffer:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteImmutableBuffer
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(buffer: ByteBuffer)
-
Create a fresh
ByteBuffer
containing the bytes contained in the givenDispatchData
.This will allocate a new
ByteBuffer
with enough space to fit the bytes of theDispatchData
and potentially some extra space using the default allocator.- info: If you have access to a
Channel
,ChannelHandlerContext
, orByteBufferAllocator
we recommend usingchannel.allocator.buffer(dispatchData:)
. Or if you want to write multiple items into the buffer usechannel.allocator.buffer(capacity: ...)
to allocate aByteBuffer
of the right size followed by awriteDispatchData
instead of using this method. This allows SwiftNIO to do accounting and optimisations of resources acquired for operations on a givenChannel
in the future.
Declaration
Swift
public init(dispatchData: DispatchData)
- info: If you have access to a
-
A
String
describing thisByteBuffer
. Example:ByteBuffer { readerIndex: 0, writerIndex: 4, readableBytes: 4, capacity: 512, storageCapacity: 1024, slice: 256..<768, storage: 0x0000000103001000 (1024 bytes)}
The format of the description is not API.
Declaration
Swift
public var description: String { get }
Return Value
A description of this
ByteBuffer
. -
A
String
describing thisByteBuffer
with some portion of the readable bytes dumped too. Example:ByteBuffer { readerIndex: 0, writerIndex: 4, readableBytes: 4, capacity: 512, slice: 256..<768, storage: 0x0000000103001000 (1024 bytes)} readable bytes (max 1k): [ 00 01 02 03 ]
The format of the description is not API.
Declaration
Swift
public var debugDescription: String { get }
Return Value
A description of this
ByteBuffer
useful for debugging. -
Copy the collection of
bytes
into theByteBuffer
atindex
. Does not move the writer index.Declaration
Swift
@discardableResult @inlinable public mutating func setBytes<Bytes>(_ bytes: Bytes, at index: Int) -> Int where Bytes : Sequence, Bytes.Element == UInt8
-
Copy
bytes
into theByteBuffer
atindex
. Does not move the writer index.Declaration
Swift
@discardableResult @inlinable public mutating func setBytes(_ bytes: UnsafeRawBufferPointer, at index: Int) -> Int
-
Move the reader index forward by
offset
bytes.Warning
By contract the bytes between (including)readerIndex
and (excluding)writerIndex
must be initialised, ie. have been written before. Also thereaderIndex
must always be less than or equal to thewriterIndex
. Failing to meet either of these requirements leads to undefined behaviour.Declaration
Swift
public mutating func moveReaderIndex(forwardBy offset: Int)
Parameters
offset
The number of bytes to move the reader index forward by.
-
Set the reader index to
offset
.Warning
By contract the bytes between (including)readerIndex
and (excluding)writerIndex
must be initialised, ie. have been written before. Also thereaderIndex
must always be less than or equal to thewriterIndex
. Failing to meet either of these requirements leads to undefined behaviour.Declaration
Swift
public mutating func moveReaderIndex(to offset: Int)
Parameters
offset
The offset in bytes to set the reader index to.
-
Move the writer index forward by
offset
bytes.Warning
By contract the bytes between (including)readerIndex
and (excluding)writerIndex
must be initialised, ie. have been written before. Also thereaderIndex
must always be less than or equal to thewriterIndex
. Failing to meet either of these requirements leads to undefined behaviour.Declaration
Swift
public mutating func moveWriterIndex(forwardBy offset: Int)
Parameters
offset
The number of bytes to move the writer index forward by.
-
Set the writer index to
offset
.Warning
By contract the bytes between (including)readerIndex
and (excluding)writerIndex
must be initialised, ie. have been written before. Also thereaderIndex
must always be less than or equal to thewriterIndex
. Failing to meet either of these requirements leads to undefined behaviour.Declaration
Swift
public mutating func moveWriterIndex(to offset: Int)
Parameters
offset
The offset in bytes to set the reader index to.
-
Copies
length
bytes
starting at thefromIndex
totoIndex
. Does not move the writer index.Note
Overlapping ranges, for examplecopyBytes(at: 1, to: 2, length: 5)
are allowed.Precondition
The range represented byfromIndex
andlength
must be readable bytes, that is:fromIndex >= readerIndex
andfromIndex + length <= writerIndex
.Declaration
Swift
@discardableResult @inlinable public mutating func copyBytes(at fromIndex: Int, to toIndex: Int, length: Int) throws -> Int
Parameters
fromIndex
The index of the first byte to copy.
toIndex
The index into to which the first byte will be copied.
length
The number of bytes which should be copied.
-
Errors thrown when calling
See morecopyBytes
.Declaration
Swift
public struct CopyBytesError : Error
extension ByteBuffer.CopyBytesError: Hashable
extension ByteBuffer.CopyBytesError: CustomDebugStringConvertible
-
Compare two
ByteBuffer
values. TwoByteBuffer
values are considered equal if the readable bytes are equal.Declaration
Swift
public static func == (lhs: ByteBuffer, rhs: ByteBuffer) -> Bool
-
The hash value for the readable bytes.
Declaration
Swift
public func hash(into hasher: inout Hasher)
-
Modify this
ByteBuffer
if thisByteBuffer
is known to uniquely own its storage.In some cases it is possible that code is holding a
ByteBuffer
that has been shared with other parts of the code, and may want to mutate thatByteBuffer
. In some cases it may be worth modifying aByteBuffer
only if thatByteBuffer
is guaranteed to not perform a copy-on-write operation to do so, for example when a different buffer could be used or more cheaply allocated instead.This function will execute the provided block only if it is guaranteed to be able to avoid a copy-on-write operation. If it cannot execute the block the returned value will be
nil
.Declaration
Swift
@inlinable public mutating func modifyIfUniquelyOwned<T>(_ body: (inout ByteBuffer) throws -> T) rethrows -> T?
Parameters
body
The modification operation to execute, with this
ByteBuffer
passedinout
as an argument.Return Value
The return value of
body
. -
Read an integer off this
ByteBuffer
, move the reader index forward by the integer’s byte size and return the result.Declaration
Swift
@inlinable public mutating func readInteger<T>(endianness: Endianness = .big, as: T.Type = T.self) -> T? where T : FixedWidthInteger
Parameters
endianness
The endianness of the integer in this
ByteBuffer
(defaults to big endian).as
the desired
FixedWidthInteger
type (optional parameter)Return Value
An integer value deserialized from this
ByteBuffer
ornil
if there aren’t enough bytes readable. -
Get the integer at
index
from thisByteBuffer
. Does not move the reader index. The selected bytes must be readable or elsenil
will be returned.Declaration
Swift
@inlinable public func getInteger<T>(at index: Int, endianness: Endianness = Endianness.big, as: T.Type = T.self) -> T? where T : FixedWidthInteger
Parameters
index
The starting index of the bytes for the integer into the
ByteBuffer
.endianness
The endianness of the integer in this
ByteBuffer
(defaults to big endian).as
the desired
FixedWidthInteger
type (optional parameter)Return Value
An integer value deserialized from this
ByteBuffer
ornil
if the bytes of interest are not readable. -
Write
integer
into thisByteBuffer
, moving the writer index forward appropriately.Declaration
Swift
@discardableResult @inlinable public mutating func writeInteger<T: FixedWidthInteger>(_ integer: T, endianness: Endianness = .big, as: T.Type = T.self) -> Int
Parameters
integer
The integer to serialize.
endianness
The endianness to use, defaults to big endian.
Return Value
The number of bytes written.
-
Write
integer
into thisByteBuffer
starting atindex
. This does not alter the writer index.Declaration
Swift
@discardableResult @inlinable public mutating func setInteger<T>(_ integer: T, at index: Int, endianness: Endianness = .big, as: T.Type = T.self) -> Int where T : FixedWidthInteger
Parameters
integer
The integer to serialize.
index
The index of the first byte to write.
endianness
The endianness to use, defaults to big endian.
Return Value
The number of bytes written.
-
A view into the readable bytes of the
ByteBuffer
.Declaration
Swift
@inlinable public var readableBytesView: ByteBufferView { get }
-
Returns a view into some portion of the readable bytes of a
ByteBuffer
.Declaration
Swift
@inlinable public func viewBytes(at index: Int, length: Int) -> ByteBufferView?
Parameters
index
The index the view should start at
length
The length of the view (in bytes)
Return Value
A view into a portion of a
ByteBuffer
ornil
if the requested bytes were not readable. -
Create a
ByteBuffer
from the givenByteBufferView
s range.Declaration
Swift
@inlinable public init(_ view: ByteBufferView)
Parameters
view
The
ByteBufferView
which you want to get aByteBuffer
from.