Rename write(string) to writeString(...), make it faster and add setter as well

This commit is contained in:
Norman Maurer committed 2017-06-01 16:23:46 +02:00
1 parent 89badeec24
commit b915af9987
2 files changed
+22 -15

No files matched your search

+16 -9
View File
@@ -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<UInt8>, 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..<idx + count, with: string)
return count
}
return nil
}
/**
+6 -6
View File
@@ -30,13 +30,13 @@ class ByteBufferTest: XCTestCase {
XCTAssertEqual(size, 0)
})
buf.write(string: "Hello world!")
buf.writeString(value: "Hello world!")
buf.withReadPointer(body: { ptr, size in XCTAssertEqual(12, size) })
}
func testWriteStringMovesWriterIndex() {
var buf = try! allocator.buffer(capacity: 1024)
buf.write(string: "hello")
buf.writeString(value: "hello")
XCTAssertEqual(5, buf.writerIndex)
let _ = buf.withMutableReadPointer { ptr, size in
let s = String(bytesNoCopy: ptr, length: size, encoding: .utf8, freeWhenDone: false)
@@ -51,17 +51,17 @@ class ByteBufferTest: XCTestCase {
}
func testResetWriterIndex() {
buf.write(string: "hello")
buf.writeString(value: "hello")
XCTAssertEqual(5, buf.writerIndex)
buf.markWriterIndex()
buf.write(string: " world!")
buf.writeString(value: " world!")
XCTAssertEqual(12, buf.writerIndex)
buf.resetWriterIndex()
XCTAssertEqual(5, buf.writerIndex)
}
func testResetReaderIndex() {
buf.write(string: "hello")
buf.writeString(value: "hello")
let bytesConsumed = buf.withMutableReadPointer { _,_ in return 5 }
XCTAssertEqual(5, bytesConsumed)
@@ -74,7 +74,7 @@ class ByteBufferTest: XCTestCase {
XCTAssertEqual(0, buf.readerIndex)
// We use mutable read pointers when we're consuming the data
// so first we need some data there!
buf.write(string: "hello again")
buf.writeString(value: "hello again")
let bytesConsumed = buf.withMutableReadPointer(body: { dst, size in
// Pretend we did some operation which made use of entire 11 byte string