Skip to content

Commit

Permalink
#154 Fixed FixedWidthInteger.toHexadecimal() support for Embedded S…
Browse files Browse the repository at this point in the history
…wift
  • Loading branch information
colemancda committed Nov 6, 2024
1 parent c36b496 commit 6883c2c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
22 changes: 18 additions & 4 deletions Sources/Bluetooth/Extensions/Hexadecimal.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,26 @@
internal extension FixedWidthInteger {

func toHexadecimal() -> String {

var string = String(self, radix: 16)
while string.utf8.count < (MemoryLayout<Self>.size * 2) {
let length = MemoryLayout<Self>.size * 2
var string: String
#if hasFeature(Embedded) || (canImport(Darwin) && DEBUG)
string = ""
string.reserveCapacity(length)
self.bigEndian.bytes.forEach { byte in
string.append(String(format: "%02X", length: 2, byte)!)
}
#else // Linux and non-Embedded release builds use Swift StdLib
string = String(self, radix: 16, uppercase: true)
// Add Zero padding
while string.utf8.count < length {
string = "0" + string
}
return string.uppercased()
#endif
assert(string.utf8.count == length)
#if !hasFeature(Embedded)
assert(string == string.uppercased(), "String should be uppercased")
#endif
return string
}
}

Expand Down
28 changes: 28 additions & 0 deletions Sources/Bluetooth/Extensions/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
// Created by Alsey Coleman Miller on 11/4/24.
//

#if canImport(Darwin)
import Darwin
#endif

internal extension String {

/// Initialize from UTF8 data.
Expand All @@ -19,4 +23,28 @@ internal extension String {
}
#endif
}

#if hasFeature(Embedded)
// Can't use `CVarArg` in Embedded Swift
init?(format: String, length: Int, _ value: UInt8) {
var cString: [CChar] = .init(repeating: 0, count: length + 1)
guard _snprintf_uint8_t(&cString, cString.count, format, value) >= 0 else {
return nil
}
self.init(cString: cString)
}
#elseif canImport(Darwin)
init?<T: CVarArg>(format: String, length: Int, _ value: T) {
var cString: [CChar] = .init(repeating: 0, count: length + 1)
guard snprintf(ptr: &cString, cString.count, format, value) >= 0 else {
return nil
}
self.init(cString: cString)
}
#endif
}

#if hasFeature(Embedded)
@_silgen_name("snprintf")
internal func _snprintf_uint8_t(_ pointer: UnsafeMutablePointer<CChar>, _ length: Int, _ format: UnsafePointer<CChar>, _ arg: UInt8) -> Int32
#endif

0 comments on commit 6883c2c

Please sign in to comment.