mirror of
https://github.com/apple/swift-nio
synced 2026-11-23 04:34:23 +00:00
### 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.
54 lines
2.0 KiB
Swift
54 lines
2.0 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
import NIOCore
|
|
import NIOWebSocket
|
|
import XCTest
|
|
|
|
final class ByteBufferWebSocketTests: XCTestCase {
|
|
private var buffer = ByteBuffer()
|
|
|
|
func testPeekWebSocketErrorCode_Normal() {
|
|
var buffer = ByteBuffer()
|
|
let errorCode = WebSocketErrorCode(codeNumber: 1002)
|
|
buffer.write(webSocketErrorCode: errorCode)
|
|
|
|
guard let webSocketCode = buffer.peekWebSocketErrorCode() else {
|
|
XCTFail("Expected to read a valid WebSocketErrorCode.")
|
|
return
|
|
}
|
|
XCTAssertEqual(webSocketCode, errorCode, "Should match the written error code.")
|
|
XCTAssertEqual(buffer.readerIndex, 0, "peekWebSocketErrorCode() should not advance the reader index.")
|
|
}
|
|
|
|
func testPeekWebSocketErrorCode_NotEnoughBytes() {
|
|
var buffer = ByteBuffer()
|
|
// Only write a single byte, insufficient for a UInt16.
|
|
buffer.writeInteger(UInt8(0x03))
|
|
let code = buffer.peekWebSocketErrorCode()
|
|
XCTAssertNil(code, "Should return nil if not enough bytes to form an error code.")
|
|
}
|
|
|
|
func testPeekWebSocketErrorCode_Repeated() {
|
|
var buffer = ByteBuffer()
|
|
let errorCode = WebSocketErrorCode(codeNumber: 1011)
|
|
buffer.write(webSocketErrorCode: errorCode)
|
|
|
|
let firstPeek = buffer.peekWebSocketErrorCode()
|
|
let secondPeek = buffer.peekWebSocketErrorCode()
|
|
XCTAssertEqual(firstPeek, secondPeek, "Repeated peeks should yield the same code.")
|
|
XCTAssertEqual(buffer.readerIndex, 0, "peekWebSocketErrorCode() should not advance reader index.")
|
|
}
|
|
}
|