From b915af9987ead35ee2bfabcdb0682b60cf13af37 Mon Sep 17 00:00:00 2001 From: Norman Maurer Date: Thu, 1 Jun 2017 16:23:46 +0200 Subject: [PATCH] Rename write(string) to writeString(...), make it faster and add setter as well --- Sources/NIO/ByteBuffer.swift | 25 ++++++++++++++++--------- Tests/NIOTests/ByteBufferTest.swift | 12 ++++++------ 2 files changed, 22 insertions(+), 15 deletions(-) diff --git a/Sources/NIO/ByteBuffer.swift b/Sources/NIO/ByteBuffer.swift index 1f9a847e0..8a2313b62 100644 --- a/Sources/NIO/ByteBuffer.swift +++ b/Sources/NIO/ByteBuffer.swift @@ -336,16 +336,23 @@ public struct ByteBuffer { // TODO: Equatable, Comparable // TODO: indexOf, bytesBefore, forEachByte, backing byte array access? // TODO: Generics to avoid this? - public mutating func write(string: String) { - let _ = withMutableWritePointer { (writePtr: UnsafeMutablePointer, size: Int) -> Int in - // TODO: Can we avoid the double copy? getBytes seems almost, but not quite right. - if let data = string.data(using: .utf8) { - let _ = data.withUnsafeBytes { writePtr.assign(from: $0, count: data.count) } - return data.count - } else { - return 0 - } + public mutating func writeString(value: String) -> Int?{ + if let bytes = setString(index: writerIndex, value: value) { + writerIndex += bytes + return bytes } + return nil + } + + public mutating func setString(index: Int, value: String) -> Int? { + let string = value.utf8 + let count = string.count + if expandIfNeeded(index: index, size: count) { + let idx = applyOffset(index) + data.replaceSubrange(idx..