From d8439b8e2c480b4de17b51482fde3061c1ccde3a Mon Sep 17 00:00:00 2001 From: Brad Howes Date: Thu, 7 Nov 2024 11:24:02 +0100 Subject: [PATCH] Removed dependency on Foundation (#22) --- Sources/Histogram/Histogram.swift | 33 ++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Sources/Histogram/Histogram.swift b/Sources/Histogram/Histogram.swift index d6112e8..c5be0dc 100644 --- a/Sources/Histogram/Histogram.swift +++ b/Sources/Histogram/Histogram.swift @@ -10,7 +10,12 @@ // swiftlint:disable file_length type_body_length line_length identifier_name -import Foundation +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#endif + import Numerics /** @@ -1369,4 +1374,30 @@ extension Histogram: TextOutputStreamable { } } +private extension String { + // Replacement for Foundation formatting routine. + // Loosly Based on example code found on + // https://developer.apple.com/documentation/swift/using-imported-c-functions-in-swift + // but using vsnprintf instead of vasprintf due to the latter being unavailabie in Glibc. + // + init(format: String, _ arguments: any CVarArg...) { + guard let value: String = withVaList(arguments, { va_list in + let bufferSize = 1_024 + var buffer = [Int8](repeating: 0, count: bufferSize) + let valid = buffer.withUnsafeMutableBytes { ptr in + // vsnprintf guarantees not to write more than bufferSize - 1 characters plus a final null byte. + // Negative value indicates some failure; positive values indicate a valid null-terminated + // string. + 0..