Commit Graph
31 Commits
Author SHA1 Message Date
Rick Newton-Rogers 661bfc5aea ByteBuffer custom allocator support
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
2026-02-27 09:39:33 +00:00
Mahdi Bahrami f2ad915d57 [perf] Manually implement lastIndex(where:) in ByteBufferView (#3413)
### 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.
2025-10-21 14:02:55 +01:00
Mahdi Bahrami 767ea9ee09 [perf] Manually implement firstIndex(where:) in ByteBufferView (#3412)
### 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
2025-10-17 07:15:44 +00:00
Fabian FettandCory Benfield a3ed8e10ab Drop Swift 5.10 (#3393)
This PR drops Swift 5.10 and enables Swift 6 language mode.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2025-10-06 10:58:33 +01:00
Cory Benfield 2143eb91f1 Tweak test availability to avoid segfaults (#3397)
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.
2025-10-04 09:30:21 +01:00
Mahdi BahramiandCory Benfield 2e22c89844 Add InlineArray helpers to ByteBuffer (#3252)
### 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>
2025-09-24 09:18:00 +00:00
Johannes Weiss 0b65385fad improve inEventLoop checks (#3302)
### 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
2025-07-14 17:15:10 +01:00
Orhan Yigit Yazicilar cddbde511a Adding RawSpan support to writeBytes in ByteBuffer (#3269)
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.
2025-06-16 17:11:03 +00:00
Rick Newton-Rogers 14dcafc6ec Update Array+FileSystem.swift to add visionOS (#3220)
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
2025-05-07 13:22:23 +00:00
Tony Allevato 6615a44917 Fix ByteBufferTests when compiling with Swift 6 but running on macOS 14. (#3217)
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.
2025-04-22 08:43:06 +00:00
Raghav Roy 8440498328 Add More Peek API Variants for ByteBuffer (#3174)
### 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.
2025-04-10 14:44:53 +00:00
Raghav RoyandCory Benfield 12d8a4c6d7 Add Peek API for Multiple Integers (#3175)
### 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>
2025-04-10 10:23:27 +00:00
Raghav Roy 1d7a94655f Add Peek API variants for ByteBuffer (#3160)
### 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!*
2025-03-31 10:30:37 +01:00
Raghav RoyandGeorge Barnett e8260eb721 Add peekInteger API to ByteBuffer (#3157)
### 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>
2025-03-27 09:54:07 +00:00
456ca25693 Adds Int(buffer:) initializer to FixedWidthInteger types (#3047)
### 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>
2025-01-17 17:13:40 +00:00
Adam FowlerandCory Benfield 74cf44e261 Add ByteBuffer methods getUTF8ValidatedString and readUTF8ValidatedString (#2973)
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>
2024-11-21 17:44:42 +00:00
Cory Benfield 37b31b95c2 Complete NIOCore strict concurrency (#2959)
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.
2024-10-31 20:35:57 +00:00
67dd9ca974 Issue-2748 - Add ByteBuffer Hex init & write (#2837)
Add ability for below two functions 
`ByteBuffer(hexEncodedBytes: "68 65 6c 6c 6f 20 77 6f 72 6c 64 0a")`
` buffer.writeHexEncodedBytes("68656c6c6f20776f726c640a")`

### Motivation:

https://github.com/apple/swift-nio/issues/2748

---------

Co-authored-by: Ali Ali <ali.ali@qantas.com.au>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-09-30 17:26:37 +00:00
8307ad610a Issue-2734 - Clamp buffer to maximum upon large write operation (#2745)
### 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>
2024-09-18 10:12:03 +00:00
Mirza UčanbarlićandFranz Busch 3615f9cfa0 Making ByteBuffer's description more useful (#2864)
### 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>
2024-09-04 08:07:14 +00:00
196928d0ce Add .compact format to ByteBuffer's hexdump method (#2856)
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>
2024-09-03 09:13:03 +00:00
Franz Busch c9756e1083 Adopt swift-format (#2794)
* 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.
2024-07-19 11:48:17 +02:00
Harish Yerra a0e0c68d71 [arch] Add arm64_32 to the 32-bit platform check (#2625)
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.
2024-01-17 05:34:01 -08:00
Natik Gadzhi 34a7663c05 Make ByteBuffer Codable (#2509)
This commit adds Codable to ByteBuffer. It encodes in Base64 into a singleValue
container.

- Base64 implementation moved into _NIODataStructures
- Base64 now supports decoding.
2023-08-30 10:32:45 +01:00
cdfbb20e92 Adding ByteBuffer.hexDump in xxd and hexdump -C formats (#2475)
* 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>
2023-08-15 02:39:53 -07:00
Cory Benfield 4ad2c37338 Avoid integer literals that won't fit. (#2348)
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.
2023-01-13 13:53:17 +00:00
Cory Benfield 184df88ec6 Avoid actually allocating a giant buffer (#2347)
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.
2023-01-12 02:33:54 -08:00
taylorswiftandCory Benfield 75970eb980 add witnesses for ByteBufferView.reserveCapacity(_:), append(_:), and append(contentsOf:) (#2309)
* add witnesses for ByteBufferView.reserveCapacity(_:), append(_:), and append(contentsOf:)

* align with project style

* fix incorrect ByteBufferView implementations, add unit tests

* use withUnsafeBytes(of:) instead of CollectionOfOne in ByteBufferView.append(_:)

* address review comments

* Add missing Linux tests

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-11-14 10:01:25 +00:00
carolinacass af41276062 Use #fileID/#filePath instead of #file (#2306)
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
2022-11-03 16:43:13 +00:00
Anish Aggarwal d05d2fd125 Added test for BufferView custom contains function (#2227)
* Added test for BufferView custom contains function

* Fixed test case

* testBufferViewContains fixed
2022-07-26 17:04:54 +01:00
Si BeaumontandCory Benfield cd11cf8202 Move tests of NIOCore types from NIOPosixTests to NIOCoreTests (#2093)
* 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>
2022-05-04 08:14:18 -07:00