Skip to content

Commit 782e6d3

Browse files
committed
Merge branch 'develop' into main
2 parents 2a61e55 + 80261d2 commit 782e6d3

File tree

1 file changed

+18
-57
lines changed

1 file changed

+18
-57
lines changed

Sources/NIOIRC/Helpers/ByteBufferExtras.swift

Lines changed: 18 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -14,69 +14,30 @@
1414

1515
import struct NIO.ByteBuffer
1616

17-
fileprivate extension BinaryInteger {
18-
19-
var numberOfDecimalDigits : Int {
20-
@inline(__always) get {
21-
var value = self
22-
var count = 0
23-
24-
repeat {
25-
value /= 10
26-
count += 1
27-
}
28-
while value != 0
29-
30-
return count
31-
}
32-
}
33-
}
34-
35-
extension ByteBuffer {
17+
public extension ByteBuffer {
18+
// This looks expensive, but isn't. As per @weissi String's store up to 15
19+
// bytes inline, no alloc necessary.
3620

21+
/**
22+
* Write an Integer as an ASCII String.
23+
*/
24+
@inlinable
3725
@discardableResult
38-
public mutating func write<T: SignedInteger>(integerAsString integer: T,
39-
as: T.Type = T.self) -> Int
26+
mutating func write<T: SignedInteger>(integerAsString integer: T,
27+
as: T.Type = T.self) -> Int
4028
{
41-
let bytesWritten = set(integerAsString: integer, at: self.writerIndex)
42-
moveWriterIndex(forwardBy: bytesWritten)
43-
return Int(bytesWritten)
29+
return self.writeString(String(integer, radix: 10))
4430
}
4531

32+
/**
33+
* Set an Integer as an ASCII String.
34+
*/
35+
@inlinable
4636
@discardableResult
47-
public mutating func set<T: SignedInteger>(integerAsString integer: T,
48-
at index: Int,
49-
as: T.Type = T.self) -> Int
37+
mutating func set<T: SignedInteger>(integerAsString integer: T,
38+
at index: Int,
39+
as: T.Type = T.self) -> Int
5040
{
51-
let charCount = integer.numberOfDecimalDigits + (integer < 0 ? 1 : 0)
52-
let avail = capacity - index
53-
54-
if avail < charCount {
55-
reserveCapacity(capacity + (charCount - avail))
56-
}
57-
58-
self.withVeryUnsafeBytes { rbpp in
59-
let mrbpp = UnsafeMutableRawBufferPointer(mutating: rbpp)
60-
let base = mrbpp.baseAddress!.assumingMemoryBound(to: UInt8.self)
61-
.advanced(by: index)
62-
var cursor = base.advanced(by: charCount)
63-
64-
let c0 : T = 48
65-
var negativeAbsoluteValue = integer < 0 ? integer : -integer
66-
repeat {
67-
cursor -= 1
68-
cursor.pointee = UInt8(c0 - (negativeAbsoluteValue % 10))
69-
negativeAbsoluteValue /= 10;
70-
}
71-
while negativeAbsoluteValue != 0
72-
73-
if integer < 0 {
74-
cursor -= 1
75-
cursor.pointee = 45 // -
76-
}
77-
78-
}
79-
80-
return charCount
41+
return self.setString(String(integer, radix: 10), at: index)
8142
}
8243
}

0 commit comments

Comments
 (0)