Skip to content

Commit

Permalink
Merge branch 'HdrHistogram:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
freef4ll authored Nov 7, 2024
2 parents e98f9e0 + d8439b8 commit 7842dca
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion Sources/Histogram/Histogram.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

/**
Expand Down Expand Up @@ -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..<bufferSize ~= format.withCString {
Int(vsnprintf(ptr.baseAddress, bufferSize, $0, va_list))
}
}
return valid ? String(validatingUTF8: buffer) : ""
}) else {
fatalError("Invalid String format for given arguments")
}
self = value
}
}

// swiftlint:enable file_length type_body_length line_length identifier_name

0 comments on commit 7842dca

Please sign in to comment.