mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
A convenience method to write a message and prepend its length in front of it. ### Motivation: Many protocols use a length field to split a byte stream into multiple separate messages. `swift-nio-extras` supports these kind of protocols through `LengthFieldPrepender` and friends. However, sometimes a channel handler is not the right tool, especially if the a message itself contains multiple dynamic length fields. One example is [RSocket Routing Metadata Extensions](https://github.com/rsocket/rsocket/blob/master/Extensions/Routing.md). A `ByteBuffer` is probably a better tool to create this message. This can be tricky to get right if strings are part of the message. A naive solution like the following has two issues: ```swift func add(tag: String, to buffer: inout ByteBuffer) { let length = tag.count buffer.writeInteger(UInt8(length)) buffer.writeString(tag) } ``` The `count` property in Swift is different than in most other languages. It does **not** return the number of UTF-8 code points and can result in incorrect behavior if multi-byte characters are used (e.g. Emojis). Furthermore, the size of the string could be larger than `UInt8` can represent. ### Modifications: This PR introduces a new method on `ByteBuffer` called `writeLengthPrefix(endianness:as:writeMessage:)`. It solves both problems mentioned above. It first reserves space for the length prefix and delegates the actually writing of the message to `writeMessage`. Afterwards, it counts how many bytes were written during the call to `writeMessage` and then sets it on the previously reserved space in front of the actually message. ### Result: We can now write arbitrary content to a buffer and prefix it with the number of bytes written. ```swift func add(tag: String, to buffer: inout ByteBuffer) { buffer.writeLengthPrefix(as: UInt8.self) { buffer in buffer.writeString(tag) } } ```