Motivation
* Other libraries often have byte buffer storage with similar concepts as
NIO's `ByteBuffer`, linear storage with reader and writer indices - it would
be nice to have efficient conversion to and from these objects.
* Efficienct conversion would likely mean taking ownership of the byte
storage allocated by the other object and exposing `ByteBuffer`s
internals so that they may be owned by another object, there is no API
for this currently.
Modifications
* Added new methods behind `CustomByteBufferAllocator` SPI.
* Added public `ByteBuffer` initializer for adopting externally-allocated memory
* Made `ByteBufferAllocator` initializer public with custom `malloc`/`realloc`/`free`/`memcpy` hooks
* Updated `realloc` signature to pass old capacity alongside new capacity to allow implementations to
copy over bytes
* Added `withVeryUnsafeMutableBytesWithStorageManagement` for mutable storage access
* Updated all existing tests using internal allocator API to use the new API
* Added tests for custom allocator functionality
Result
* Custom allocators can manage `ByteBuffer` memory with full size information
* External systems can transfer memory ownership to `ByteBuffer`
* System allocator maintains zero overhead due to inlining of the wrapper
* API (SPI) is extensible for future allocation system integrations
### Motivation:
`ByteBuffer.lastIndex(where:)` is of suboptimal performance.
The default Collection implementations don't go through any "magic
underscored" functions like `_customIndexOfEquatableElement`.
### Modifications:
Manually implement `lastIndex(where:)`.
### Result:
Basically free performance boost. 2x+ boost even for not big buffers of
a few hundred bytes.
This function is currently used in
`ByteBufferView.trim(limitingElements:)`.
I have no immediate use case for this function, but it's still an issue
worth addressing.
### Motivation:
`ByteBuffer.firsIndex` is of suboptimal performance.
The default Collection implementations don't go through any "magic
underscored" functions like `_customIndexOfEquatableElement`.
### Modifications:
Manually implement `firstIndex(where:)`.
### Result:
Basically free performance boost. 2x+ boost even for not big buffers of
a few hundred bytes.
There are some usage of this function in `BufferedReader`. Those will
become much faster.
Also this function is used in `ByteBufferView.trim(limitingElements:)`.
Also makes #3411 stuff faster. See:
https://github.com/apple/swift-nio/pull/3411#discussion_r2436260691
Motivation
Availability guards on test functions don't work the way we'd want them
to: in particular, xctest still ends up calling these functions even on
platforms that are less available than the functions in question. We
need to move these to checks in in the function themselves.
Modifications
Replace @available with guard available
Result
No more segfaults in tests.
### Motivation:
Useful for parsing packets, for example `ipv4: InlineArray<4, UInt8>`
and `ipv6: InlineArray<16, UInt8>`.
### Modifications:
For now I've only added a `readInlineArray` function. I know some other
functions are missing, such as `writeInlineArray`.
I wanted to first open up a discussion and see if these changes are
acceptable. I can add those functions too if required, in this PR or
other PRs.
### Result:
Users can read `ByteBuffer` into stack-allocated memory, which can be
more performant than the other alternatives like `Array`, or more
convenient than reading as a tuple like `(UInt8, UInt8, UInt8, UInt8)`.
### Caveats:
Swift 6.2 is required so I've used `#if compiler(>=6.2)`.
Furthermore, `InlineArray` is marked as available on `macOS(9999)` since
the Swift team have yet to update that mark, although `InlineArray` is
planned for Swift 6.2 per the
[proposal](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0453-vector.md).
Edit: to be clear things work fine on Linux and that's where I've been
using this same `readInlineArray` function that I've proposed.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
`inEventLoop` is very much in the performance path of SwiftNIO,
especially these days with Concurrency, `NIOLoopBound` and friends.
Previously, we relied on `pthread_equal(pthread_self(), myPthread)`,
however, this could cause a number of issues.
1. Holding onto a `pthread_t` after `.join` is actually illegal (fixed
in #3297)
2. Potential ABA issues when `pthread_t` pointer are re-used for new
pthreads
3. Fix would require a lock around `myPthread` which makes things (2x
slower, even without contention)
### Modifications:
- New type `SelectableEventLoopUniqueID` which can be packed into a
`UInt`
- Attach them into a C thread local
### Result:
- Even faster than the old, incorrect version
- old: `measuring: el_in_eventloop_100M: 0.257395375, 0.241049208,
0.243188792, 0.259125916, 0.24843225, 0.229690125, 0.244281541,
0.225078834, 0.236395, 0.233305167`
- new: `measuring: el_in_eventloop_100M: 0.175561125, 0.187225625,
0.199269375, 0.19740975, 0.1922695, 0.179850958, 0.177612458,
0.17665125, 0.17897475, 0.18038775`
- More correct
- Groundwork to make #3297 not make things slower
Motivation:
With the new Swift version (6.2) we get access to spans for safely
interacting with the contiguous memory owned by other types. Allow users
write bytes to the ByteBuffer with RawSpans.
Modifications:
* ByteBuffer-core: Overload the setBytes, _setBytes, and
_setBytesAssumingUniqueBufferAccess to use RawSpan instead of
UnsafeRawBufferPointer
* ByteBuffer-aux: Overload the writeBytes to use RawSpan instead of
UnsafeRawBufferPointer
Result:
Users can now write the contiguous memory of other types into ByteBuffer
using the new RawSpan overloads, removing the need for unsafe pointer
handling.
Fix visionOS builds and tests
### Motivation:
visionOS builds and tests were failing because of missing cases in
availability guards.
### Modifications:
Spell guards in terms of Darwin where appropriate, add visionOS
### Result:
Example run of this working in CI
https://github.com/apple/swift-nio/actions/runs/14876166161/job/41773757638?pr=3220
Writing `@available(someOS...)` on an XCTest test method only affects
whether the compiler allows known-available APIs to be called, but it
doesn't actually prevent the test from running on older OSes (XCTest
doesn't see the annotation since it's not part of the Objective-C
runtime metadata). So if this code is compiled with Swift 6 but run on
an older OS, it will segfault when it tries to call an API that doesn't
exist on that platform.
These tests need to use an `#available` guard instead to make the
decision to skip them at runtime.
### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address issue #2034 and issue #2736, and is a continuation
of PR #3157
### Modifications:
Introduced peekSlice(), peekLengthPrefixedSlice(), peekData(),
peekUUIDBytes() and peekWebSocketErrorCode().
Added tests for each peek API covering normal, empty and repeated peek
scenarios.
### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
### Motivation:
The current readMultipleIntegers methods are used to consume multiple
integer values at once, but lack an equivalent nonmutating API. This can
lead to unnecessary complexity when users want to inspect values without
advancing readerIndex. THis patch introduces peekMultipleIntegers which
uses the current readerIndex, improving safety. This extends previous
work on peek methods (issue #2034, issue #2736).
### Modifications:
Updated the generation script (.sh file) to produce peekMultipleIntegers
variants for each arity of readMultipleIntegers.
Added new tests mirroring the existing multi-read/write tests
### Result:
Users can now inspect multiple integer values in a ByteBuffer without
consuming them, enabling safer workflows.
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
### Motivation:
Existing get APIs require passing an explicit index and can be misused,
leading to verbose and error-prone code. Adding peek variants that
automatically use the current readerIndex improves safety and clarity.
This aims to address https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736, and is a continuation of
PR https://github.com/apple/swift-nio/pull/3157
### Modifications:
- Introduced peekBytes(), peekString(), peekNullTerminatedString(),
peekUTF8ValidatedString() and peekDispatchData().
- Added tests for each peek API covering normal, empty, repeated, and
partial read scenarios.
### Result:
Developers can now use nonmutating peek APIs to inspect ByteBuffer
contents without altering the reader index.
***PS**: I have focussed on the ByteBuffer-aux get\* implementations, so
I'm not sure if I am missing any other important/error-prone get\*
elsewhere, if so, please point me to them and I'll be happy to add
respective peek\*'s!*
### Motivation:
The existing getInteger API is often used incorrectly, leading to
verbose or error-prone code as mentioned in
https://github.com/apple/swift-nio/issues/2034 and
https://github.com/apple/swift-nio/issues/2736. Users may
unintentionally access data without correctly managing the reader index.
To address this, I added a peekInteger API that reads integers using the
current readerIndex without modifying it.
### Modifications:
* Added a peekInteger method to ByteBuffer, which provides a nonmutating
way to read integers using the current readerIndex.
* Implemented peekInteger using the existing getInteger function.
* Added comprehensive unit tests to validate correct behavior, including
scenarios for different integer types, insufficient bytes, and
multi-write scenarios.
### Result:
* Users now have access to a safer API for inspecting integers in a
buffer without modifying state.
* Added tests for integer reading scenarios.
---------
Co-authored-by: George Barnett <gbarnett@apple.com>
### Motivation:
Makes it possible to make integers out of ByteBuffers directly with an
initializer. I.e. `UInt32(buffer: ByteBuffer(bytes: [0, 1, 2, 3]))`.
Closes#3012.
### Modifications:
- Adds the `Int(buffer:)` initializer in `ByteBuffer-int.swift`
- Adds tests in `ByteBufferTest.swift`. _Holy hell this file is huge._
- Note that `Int(buffer:)` will crash if the buffer does not have enough
bytes in it to represent the desired integer type.
- It also does _not_ expose endianness and uses `Endianness.host`, to
keep the public API clean and simple. It's a convenience initializer, so
I thought keeping it minimal is a good idea.
### Result:
Nicer direct initializer for integers from ByteBuffers.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Add methods to ByteBuffer to read validated UTF8 strings
### Motivation:
The current `readString` and `getString` methods of `ByteBuffer` do not
verify that the string being read is valid UTF8. The Swift 6 standard
library comes with a new initialiser `String(validating:as:)`. This PR
adds alternative methods to ByteBuffer which uses this instead of
`String(decoding:as:)`.
### Modifications:
Added `ByteBuffer.getUTF8ValidatedString(at:length:)`
Added `ByteBuffer.readUTF8ValidatedString(length:)`
### Result:
You can read strings from a ByteBuffer and be certain they are valid
UTF8
---------
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
With our earlier big refactors, NIOCore is now currently strict
concurrency clean. Let's lock in the win by adopting the relevant Swift
settings and fixing up the tests.
Modifications:
- Adopt our strict concurrency settings in NIOCore and NIOCoreTests
- Clean up the tests
Result:
One step closer to a world without warnings.
### Motivation:
Fix Issue 2734
### Modifications:
- Added a function to clamp storage by copying bytes and setting new
capacity of storage
- Adding a function to clamp the capacity of ByteBuffer
- Added the ability to specify he maxBufferCapacity to
MessageToByteHandler
### Result:
Once a write message that is larger than the capacity of the
MessageToByteHandler's maxBufferCapacity, it clamps the byteBuffer down.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Franz Busch <f.busch@apple.com>
Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
### Motivation:
Resolving the following issue:
https://github.com/apple/swift-nio/issues/2863
### Modifications:
Rewrote `description` and `debugDescription` on `ByteBuffer` to make it
more useful. Also fixed a bug in the in `hexDumpCompact`.
### Result:
A more useful `description` and `debugDescription`.
---------
Co-authored-by: Franz Busch <f.busch@apple.com>
Add compact formatting option to ByteBuffer's hexdump method.
### Motivation:
Resolving the following issue:
https://github.com/apple/swift-nio/issues/2825.
### Modifications:
• Added a compact format for ByteBuffer's hexdump method
### Result:
A new format which is analog to the `.plain` but without whitespaces.
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: Si Beaumont <beaumont@apple.com>
* Apply formatting
* Apply no block comments rule
* Apply OmitExplicitReturns
* Apple OnlyOneTrailingClosureArgument
* Apply NoAssignmentInExpressions
* Fix up DontRepeatTypeInStaticProperties lint errors
* Apply `OrderedImports`
* Apply `ReplaceForEachWithForLoop`
* format file
* Enable the formatting pipeline
* Adopt `AmbiguousTrailingClosureOverload`
* Fix license header
* Fix format check
* Fix `EndOfLineComment`
* Fix CI
* Adapt CI script to check if changes when running formatting
* Separate lint and format into to steps
* Fix format
* Adopt `UseEarlyExits`
* Revert "Adopt `UseEarlyExits`"
This reverts commit d1ac5bbe12.
On watchOS, the arm64_32 bit architecture restricts software to ILP32 which means integers are 32-bit. This expands our existing 32-bit checks to include arm64_32.
This commit adds Codable to ByteBuffer. It encodes in Base64 into a singleValue
container.
- Base64 implementation moved into _NIODataStructures
- Base64 now supports decoding.
* Initial implementation of hexdump for ByteBuffer
* Put that iff back there
* Reword hexDumpShort(): naming, tests, offset and full length support
* Use writerIndex to figure out the convinience end of useful content in the buffer
* hexDumpLong(offset:) — supports offset, and reads full buffer slice, not just readableBytes
* hexDumpLong() extra line failing test
* Using ByteBuffer(string:) instead of the allocator
* Move hexDumps code into ByteBuffer-hexdump.swift
* Optimized String(byte: poadding:)
* Avoid using storage.dumpBytes in hexDumpShort()
* Implemented a cleaner long hexdump
* Implemented the public hexdump API
* Revert ByteBuffer-core.swift to main
* Addressed review feedback!
* hexdump long format with clipped length
* reserve capacity in hexDumpLines
* Addressing review feedback
* String(_ value, radix, padding) and the final test case
* Make the hexDump(format: .detailed) format cleaner
* Spell out if let for Swift 5.8
* Fixed a formatting bug in multiline maxBytes detailed format
* Apply suggestions from code review
Co-authored-by: George Barnett <gbarnett@apple.com>
* Cleaner way to dump a line in .detailed format
* Cleaner generic argument type for String(_, radix:, padding:)
* Revert _storage.dumpBytes test to match previous format
* Simplify printable bytes closure to a single expression so Swift 5.6 is happy
---------
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Co-authored-by: George Barnett <gbarnett@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
While the "giant buffer" test doesn't run on 32-bit systems, it does
need to compile. That means we can't set a pointer to a value that won't
fit into an Int.
Modifications:
Smaller pointers!
Result:
The compile should work again.
Motivation:
Our CI system is beginning to struggle with allocating a giant buffer in
testSliceOfMassiveBufferWithAdvancedReaderIndexIsOk. We can work around
this by faking out the allocation.
Modifications:
- Provide a fake allocator that doesn't actually allocate memory.
- Rewrite the test to use it.
Result:
Test still validates the behaviour but doesn't touch memory anymore.
Motivation:
#fileID introduced in Swift 5.3, so no longer need to use #file anywhere
Modifications:
Changed #file to #filePath or #fileID depending on the situation
* Move tests of NIOCore types from NIOPosixTests to NIOCoreTests
* fixup: LinuxTest
Signed-off-by: Si Beaumont <beaumont@apple.com>
* fixup: Port some test utils to not use NIOPosix
Signed-off-by: Si Beaumont <beaumont@apple.com>
* fixup: No swift-system, duh
Signed-off-by: Si Beaumont <beaumont@apple.com>
* fixup: read-write for temporary file in test helper
Signed-off-by: Si Beaumont <beaumont@apple.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>