|
14 | 14 |
|
15 | 15 | import struct NIO.ByteBuffer |
16 | 16 |
|
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. |
36 | 20 |
|
| 21 | + /** |
| 22 | + * Write an Integer as an ASCII String. |
| 23 | + */ |
| 24 | + @inlinable |
37 | 25 | @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 |
40 | 28 | { |
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)) |
44 | 30 | } |
45 | 31 |
|
| 32 | + /** |
| 33 | + * Set an Integer as an ASCII String. |
| 34 | + */ |
| 35 | + @inlinable |
46 | 36 | @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 |
50 | 40 | { |
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) |
81 | 42 | } |
82 | 43 | } |
0 commit comments