mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
introduce & test ByteBuffer.readString
This commit is contained in:
1 parent
e72569e329
commit
40edb34d8f
3 files changed
+33
No files matched your search
@@ -87,6 +87,17 @@ extension ByteBuffer {
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func readString(length: Int) -> String? {
|
||||
precondition(length >= 0, "length must not be negative")
|
||||
guard self.readableBytes >= length else {
|
||||
return nil
|
||||
}
|
||||
defer {
|
||||
self.moveReaderIndex(forwardBy: length)
|
||||
}
|
||||
return self.string(at: self.readerIndex, length: length)! /* must work, enough readable bytes */
|
||||
}
|
||||
|
||||
// MARK: Other APIs
|
||||
public mutating func readWithUnsafeReadableBytes(_ fn: (UnsafeRawBufferPointer) throws -> Int) rethrows -> Int {
|
||||
let bytesRead = try self.withUnsafeReadableBytes(fn)
|
||||
|
||||
@@ -95,6 +95,8 @@ extension ByteBufferTest {
|
||||
("testSomePotentialIntegerUnderOrOverflows", testSomePotentialIntegerUnderOrOverflows),
|
||||
("testWriteForContiguousCollections", testWriteForContiguousCollections),
|
||||
("testWriteForNonContiguousCollections", testWriteForNonContiguousCollections),
|
||||
("testReadStringOkay", testReadStringOkay),
|
||||
("testReadStringTooMuch", testReadStringTooMuch),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -930,4 +930,24 @@ class ByteBufferTest: XCTestCase {
|
||||
XCTAssertEqual(expected, buf.readBytes(length: written)!)
|
||||
}
|
||||
|
||||
func testReadStringOkay() throws {
|
||||
buf.clear()
|
||||
let expected = "hello"
|
||||
buf.write(string: expected)
|
||||
let actual = buf.readString(length: expected.utf8.count)
|
||||
XCTAssertEqual(expected, actual)
|
||||
XCTAssertEqual("", buf.readString(length: 0))
|
||||
XCTAssertNil(buf.readString(length: 1))
|
||||
}
|
||||
|
||||
func testReadStringTooMuch() throws {
|
||||
buf.clear()
|
||||
XCTAssertNil(buf.readString(length: 1))
|
||||
|
||||
buf.write(string: "a")
|
||||
XCTAssertNil(buf.readString(length: 2))
|
||||
|
||||
XCTAssertEqual("a", buf.readString(length: 1))
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user