|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the swift-nio-redis open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2018 ZeeZide GmbH. and the swift-nio-redis project authors |
| 6 | +// Licensed under Apache License v2.0 |
| 7 | +// |
| 8 | +// See LICENSE.txt for license information |
| 9 | +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors |
| 10 | +// |
| 11 | +// SPDX-License-Identifier: Apache-2.0 |
| 12 | +// |
| 13 | +//===----------------------------------------------------------------------===// |
| 14 | + |
| 15 | +import struct NIO.ByteBuffer |
| 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 { |
| 36 | + |
| 37 | + @discardableResult |
| 38 | + public mutating func write<T: SignedInteger>(integerAsString integer: T, |
| 39 | + as: T.Type = T.self) -> Int |
| 40 | + { |
| 41 | + let bytesWritten = set(integerAsString: integer, at: self.writerIndex) |
| 42 | + moveWriterIndex(forwardBy: bytesWritten) |
| 43 | + return Int(bytesWritten) |
| 44 | + } |
| 45 | + |
| 46 | + @discardableResult |
| 47 | + public mutating func set<T: SignedInteger>(integerAsString integer: T, |
| 48 | + at index: Int, |
| 49 | + as: T.Type = T.self) -> Int |
| 50 | + { |
| 51 | + let charCount = integer.numberOfDecimalDigits + (integer < 0 ? 1 : 0) |
| 52 | + let avail = capacity - index |
| 53 | + |
| 54 | + if avail < charCount { |
| 55 | + changeCapacity(to: 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 |
| 81 | + } |
| 82 | +} |
0 commit comments