Commit Graph
41 Commits
Author SHA1 Message Date
scottmarchant cc38f7abcf feat: Enable NIOFoundationCompat to compile using Swift for WebAssembly. Fix NIOCore WASI compilation issue. (#3422)
Fix Swift for WebAssembly compilation in NIOFoundationCompat.

### Motivation:

NIO is a common dependency, and it is important to enable compiling NIO
using Swift for WebAssembly. This PR fixes compilation for
NIOFoundationCompat.

### Modifications:

- Fix NIOFoundationCompat compilation

### Result:

With these changes, the following build commands succeed: ✅ 

```
swift build --swift-sdk wasm32-unknown-wasip1-threads --target NIOCore
swift build --swift-sdk wasm32-unknown-wasip1-threads --target NIOFoundationCompat
```

### Context:

This PR is [part of a larger effort by
PassiveLogic](https://github.com/PassiveLogic/swift-web-examples/issues/1)
to improve Swift for WebAssembly support
2025-11-05 19:55:48 +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
Johannes WeissandCory Benfield 49b9d9725e fix remaining warnings & enable -warnings-as-errors in CI (#3000)
### Motivation:

Warnings are annoying.

### Modifications:

- Remove unnecessary use of `Foundation.Thread` which isn't Sendable.
- Remove now unnecessary `@retroactive`s.
- Enable `-warnings-as-errors` in CI

### Result:

- Warnings can't sneak in as easily anymore
- No more warnings left in `swift-nio`

```
$ rm -rf .build/arm64-apple-macosx/ && swift build --build-tests -Xswiftc -warnings-as-errors > /dev/null
echo $?
$ echo $?
0
```

Co-authored-by: Cory Benfield <lukasa@apple.com>
2024-11-26 16:02:36 +00:00
Johannes Weiss d6be946626 ByteBuffer: one fewer allocs to go to Data (#1839)
Motivation:

When getting a `Data` from a `ByteBuffer` we currently allocate twice
(`__DataStorage`) and the closure for `Data.Deallocator`.

Modifications:

We can optimise that by making the closure capture exactly one
`AnyObject` which is already a reference counted object. The compiler
realises that (on Linux) and saves us an alloc.

Thanks @lukasa for the suggestion here:
https://github.com/apple/swift-nio/pull/1836#issuecomment-830044155

Result:

Fewer allocs.
2024-11-26 11:36:30 +00:00
Johannes Weiss 2a8811acd6 EventLoopFuture.waitSpinningRunLoop() (#2985)
### Motivation:

In some (probably niche) scenarios, especially in pre-Concurrency UI
applications on Darwin, it can be useful to wait for an a value whilst
still running the current `RunLoop`. That allows the UI and other things
to work whilst we're waiting for a future to complete.

### Modifications:

- Add `NIOFoundationCompat.EventLoopFuture.waitSpinningRunLoop()`.

### Result:

Better compatibility with Cocoa.
2024-11-21 18:22:42 +00:00
Rick Newton-Rogers adfd61adc5 Use Swift 6.0 docs pipeline (#2966)
### Motivation:

Documentation checking catches more issues in Swift 6.0.

### Modifications:

Adopt the Swift 6.0 image and fix the errors.

### Result:

More accurate docs.
2024-11-07 13:03:47 +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
Johannes Weiss cd51717926 clean up @retroactive conformances (#2719) 2024-05-09 13:01:33 +01:00
George Barnett 23977a932f Fix spelling of retroactive guard (#2586)
Motivation:

`hasFeature(RetroactiveAttribute)` doesn't work as expected, but
`$RetroactiveAttribute` does.

Modifications:

Switch from `hasFeature` to `$RetroactiveAttribute`.

Result:

- `@retroactive` is applied appropriately
2023-11-06 12:38:18 +00:00
Rick Newton-Rogers 853522d908 use feature-specific guard for @retroactive (#2581)
Motivation:

We should use the more granular guard for uses of @retroactive rather
than coarse swift versions to guard against corner-cases

Modifications:

Switch `#if compiler(>=5.11)` for `#if hasFeature(RetroactiveAttribute)`

Result:

No change in most cases, more protected against corner-cases.
2023-11-01 03:34:16 -07:00
Cory Benfield 86d05fb79f Mark retroactive conformances appropriately. (#2569)
Motivation:

In nightly Swift, we now need to mark retroactive conformances when
they are intentional. These conformances are safe for us, so we can
safely suppress the warnings.

Modifications:

- Mark NIOFoundationCompat retroactive conformances.

Result:

Nightly builds work again
2023-10-23 19:00:13 +01:00
Iceman b0d43ec5b6 Fix huge compile time of setUUIDBytes (#2482) 2023-07-26 01:17:48 -07:00
George BarnettandCory Benfield edfceecba1 Add utilties for reading and writing UUIDs (#2045)
Motivation:

UUIDs are often sent over the wire but writing and reading their bytes
to/from a buffer is a bit of a pain.

Modifications:

- Add utilties to 'NIOFoundationCompat' for reading/writing and
  getting/setting a UUID on a `ByteBuffer`.

Result:

Easier to write/read UUIDs to/from a buffer.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-10-31 06:25:28 -07:00
David Nadoba 16b5b2b793 Replace NIOSendable with Sendable (#2291) 2022-10-13 15:56:27 +01:00
David Nadoba 48f4e2978f Adopt Sendable in NIOFoundationCompat (#2203) 2022-06-21 09:33:04 +01:00
Stepan UlyaninandCory Benfield d1814ea5cf replace the double encoding by writing bytes directly to the buffer (#2043)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2022-02-08 23:41:13 -08:00
Fabian Fett ea7d9b50c9 [ByteBuffer] Replace use of .map with guard in Data read (#1979) 2021-10-25 10:36:49 +02:00
Cory BenfieldandGeorge Barnett 64285cbff2 Clean up dependencies and imports. (#1935)
Motivation:

As we've largely completed our move to split out our core abstractions,
we now have an opportunity to clean up our dependencies and imports. We
should arrange for everything to only import NIO if it actually needs
it, and to correctly express dependencies on NIOCore and NIOEmbedded
where they exist.

We aren't yet splitting out tests that only test functionality in
NIOCore, that will follow in a separate patch.

Modifications:

- Fixed up imports
- Made sure our protocols only require NIOCore.

Result:

Better expression of dependencies.

Co-authored-by: George Barnett <gbarnett@apple.com>
2021-08-12 13:49:46 +01:00
Matt EatonandCory Benfield 4c0c5e555c issue-1891: API Addition for JSONSerialization in NIOFoundationCompat (#1906)
Motivation:

Issue for #1891 to add JSONSerialization in NIOFoundationCompat.

Modifications:

Adds:
JSONSerialization+ByteBuffer.swift
JSONSerialization+ByteBufferTest.swift
JSONSerialization+ByteBufferTest+XCTest.swift

Result:

Support for transforming byteBuffer data to a Foundation object.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2021-07-26 14:21:42 +01:00
Peter Tolsma 3f33ef369f Make ByteBuffer unconditionally use zero-copy for JSON Decoding (#1889) 2021-07-05 08:05:16 +01:00
Cory Benfield 8dfcb578fc Support writing ContiguousBytes and DataProtocol to ByteBuffers (#1615)
Motivation:

Per SR-10219, Data does not implement withContiguousStorageWithAvailable
and the maintainers do not believe it can. This forces code that writes
Data into ByteBuffers into slow-paths. Given that Data conforms to
ContiguousBytes and DataProtocol, we can arrange to serve a number of
use-cases by providing fast paths for all conforming types. This makes
it easier to use types vended by other Foundation-using libraries, such
as Swift Crypto.

Modifications:

- Implement `writeContiguousBytes` and `setContiguousBytes`.
- Implement `writeData` and `setData` for `DataProtocol` implementations

Result:

Better support for writing `Data` and friends into `ByteBuffer`s.
2020-08-12 08:04:52 +01:00
Johannes WeissandCory Benfield e57122bd89 ByteBuffer: add convenience initialisers (#1533)
Motivation:

There are multiple sub-optimal ByteBuffer creation patterns that occur
in the wild. Most often they happen when people don't actually have
access to a `Channel` just want to "convert" a `String` into a
`ByteBuffer`. To do this, they are forced to type

    var buffer = ByteBufferAllocator().buffer(capacity: string.utf8.count)
    buffer.writeString(string)

Sometimes, they don't get the capacity calculation right or just put a
`0`.

Similar problems happen if NIO users want to cache a ByteBuffer in their
`ChannelHandler`. You will then find this code:

```swift
if self.buffer == nil {
    self.buffer = receivedBuffer
} else {
    var receivedBuffer = receivedBuffer
    self.buffer!.writeBuffer(&receivedBuffer)
}
```

And lastly, sometimes people want to append one `ByteBuffer` to another
without mutating the appendee. That's also cumbersome because we only
support a mutable version of `writeBuffer`.

Modifications:

- add `ByteBuffer` convenience initialisers
- add convenience `writeBuffer` methods to `Optional<ByteBuffer>`
- add `writeBufferImmutable` which doesn't mutate the appendee.

Result:

More convenience.

Co-authored-by: Cory Benfield <lukasa@apple.com>

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-06-04 21:02:11 +01:00
David Evans 6b0ed24408 Convenient initialisers from ByteBuffer (#1457) 2020-03-31 09:23:25 +01:00
George Barnett 302dee3e1a Make ByteBufferView mutable (#1208)
Motivation:

ByteBufferView isn't a mutable collection, but it probably should be.

Modifications:

- Add `copyBytes(at:to:length)` to `ByteBuffer` to copy bytes from a
  readable region of a buffer to another part of the buffer
- Conform `ByteBufferView` to `MutableCollection`, `RangeReplaceableCollection`
  and `MutableDataProtocol`
- Add an allocation counting test

Result:

`ByteBufferView` is now mutable.
2019-11-27 10:25:15 +00:00
Johannes Weiss e572cf42c4 ByteBuffer: readJSONDecodable: use specified decoder (#1228)
Motivation:

ByteBuffer.readJSONDecodable just ignored the JSONDecoder that got
passed in.

Modifications:

Pass through the JSONDecoder that was specified.

Result:

Respect the user's choices.
2019-11-09 17:06:57 +00:00
Gwynne Raskind 1a9a543b6b Use self as the decoder when decoding a ByteBuffer (#1221)
Motivation:

JSONDecoder settings should be respected but were not.

Modifications:

This allows actually configuring the `JSONDecoder` instead of being stuck with the defaults.

Result:

Settings respected.
2019-11-06 16:08:31 +00:00
Johannes Weiss 8dd62cb068 ByteBuffer: add direct Codable support (#1153)
Motivation:

So far, it has been harder than necessary to use Codable & ByteBuffer.
These new APIs should simplify that and allow future optimisations.

Modifications:

Add new API to use `JSONEncoder` and `JSONDecoder` directly with
`ByteBuffer`.

Result:

Easier Codable + ByteBuffer usage.
2019-10-17 16:03:44 -07:00
Johannes Weiss 1549cd7e87 ByteBuffer.get/readData: Heuristic when to copy/not copy (#1046)
Motivation:

Previously, ByteBuffer tried to never copy the bytes when transferring
to a `Data`. For small copies that's definitely not a good choice
because it means an extra allocation.

Modifications:

- introduce `ByteTransferStrategy` so the user can choose
- make a heuristic: copy is less than 256kB, try not to copy above

Result:

More sensible defaults.
2019-06-19 17:46:25 +01:00
Johannes Weiss 0f72b759cf conform ByteBufferView to DataProtocol
Motivation:

ByteBufferView should conform to DataProtocol.

Modifications:

Conform ByteBufferView to DataProtocol.

Result:

ByteBufferView conforms to DataProtocol.
2019-03-18 16:57:55 +00:00
Johannes Weiss 357b931bda ByteBuffer: improve and simplify get* implementations (#896)
Motivation:

For historic reasons, the get* implementations checked the same indices
repeatedly and the checks were also repetitive.

Modifications:

unify and de-deplicate get* range checks

Result:

fixes #884
2019-03-13 17:35:34 +00:00
Johannes Weiss 796a7d6d7e ByteBuffer get* now respects reader/writer indexes (#869)
Motivation:

Previously, ByteBuffers get* methods would get bytes from anywhere, even
if the bytes were not readable. That can lead to security issues in code
that doesn't expect this. NIO shouldn't contain such unsafe methods
without the word 'unsafe'.

Modifications:

Made all `get*` methods respect reader/writerIndex.

Result:

safer user code
2019-03-05 13:52:17 +00:00
Johannes Weiss 47a3e7a7a0 conform ByteBufferView to Foundation's ContiguousBytes protocol (#800)
Motivation:

- Foundation has (on master) introduces a ContiguousBytes protocol and we
  should conform to that.
- Sequence has withContiguousStorageIfAvailable and ByteBufferView
  should conform to that too

Modifications:

add conformance

Result:

more compatibility.
2019-03-04 15:07:29 +00:00
Johannes Weiss 1198931823 ByteBuffer: rename set(<type>:, ...) to set<Type>(...) (#812)
Motivation:

ByteBuffer methods like `set(string:)` never felt very Swift-like and
also didn't look the same as their counterparts like `getString(...)`.

Modifications:

- rename all `ByteBuffer.set/write(<type>:,...)` methods to
  `ByteBuffer.set/write<Type>(...)`
- polyfill the old spellings in `_NIO1APIShims`

Result:

code more Swift-like
2019-02-12 11:11:45 +00:00
Johannes Weiss 531745d71a remove ContiguousCollection (#709)
Motivation:

ContiguousCollection is no longer necessary because Sequence gained
withContiguousStorageIfAvailable.

Modifications:

Removed ContiguousCollection and switch to withContiguousStorageIfAvailable.

Result:

less code
2018-12-18 09:20:37 +00:00
Cory Benfield 15be5243ef Improve ByteBuffer String APIs (#696)
Motivation:

ByteBuffer has pretty good string writing APIs, but they're imperfect.
In particular, the methods in ByteBuffer-aux both return optional Int,
which is strange as they cannot fail. We also only have support for writing
strings in UTF-8.

Modifications:

- ByteBuffer.set(string:at:) and ByteBuffer.write(string:) now both
     return `Int`, and their return value has been made discardable.
- NIOFoundationCompat has been expanded with two new methods for writing
     strings to ByteBuffers in various encodings using Foundation's
     encoding support: ByteBuffer.set(string:encoding:at:) and
     ByteBuffer.write(string:encoding:).
- NIOFoundationCompat has also been expanded with a companion to the
     already existing ByteBuffer.getString(at:length:encoding), namely
     ByteBuffer.readString(length:encoding:).
- New error enum for reporting failures to encode.

Result:

Easier to work with strings in a wider variety of cases with
ByteBuffer

Resolves #253.
2018-12-14 17:25:13 +00:00
Johannes Weiss 9b78557aff kick off NIO2 (#678)
Motivation:

NIO2 development starts now.

Modifications:

Made NIO Swift 5-only for everything else see docs/public-api-changes-NIO1-to-NIO2.md

Result:

NIO2 development can start.
2018-12-07 21:15:34 +00:00
Johannes Weiss 3913771129 improve documentation for ByteBuffer.get* methods (#535)
Motivation:

`ByteBuffer`'s `get*` methods can be used in an unsafe way and we didn't
warn the user enough.

Modifications:

Warn the user in the documentation of all the `get*` methods.

Result:

Less confusion.
2018-07-31 12:03:57 +01:00
Johannes Weiß 69c3d28a0b two missing @_inlineables (#360)
Motivation:

@_inlineable is important for at least all performance sensitive
functions that use generics and/or closures.

Modifications:

added two missing @_inlineable

Result:

fewer allocations (not measurable because https://bugs.swift.org/browse/SR-7542)
2018-04-26 18:32:21 +01:00
Norman Maurer 95a6e44e93 Remove return when possible. (#122)
Motivation:

We can cleanup the code by removing return keywords in closures sometimes.

Modifications:

Remove return when possible.

Result:

Cleaner code.
2018-03-11 22:47:29 +09:00
Johannes Weiß 73a805c7f6 minor stylistic improvements (#36)
Motivation:

Sometimes we deviated from the style the Swift stdlib sets out for no
reason.

Modifications:

Fixed some stylistic deviations.

Result:

Looks more Swift-like.
2018-02-26 15:52:49 +00:00
Johannes Weiss 225951e7c3 remove Foundation dependency
Motivation:

Foundation is problematic for a few reasons:
- its implementation is different on Linux and on macOS which means our
  macOS tests might be inaccurate
- on macOS it uses ObjC Foundation which means the autorelease pool
  might get populated
- it links the world on Linux which means we can't do static
  binaries at all

Modifications:

removed the last bits of Foundation dependency

Result:

no Foundation dependency
2018-02-19 17:22:38 +00:00