Skip to content

Commit 7842dca

Browse files
authored
Merge branch 'HdrHistogram:main' into main
2 parents e98f9e0 + d8439b8 commit 7842dca

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

Sources/Histogram/Histogram.swift

+32-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,12 @@
1010

1111
// swiftlint:disable file_length type_body_length line_length identifier_name
1212

13-
import Foundation
13+
#if canImport(Darwin)
14+
import Darwin
15+
#elseif canImport(Glibc)
16+
import Glibc
17+
#endif
18+
1419
import Numerics
1520

1621
/**
@@ -1369,4 +1374,30 @@ extension Histogram: TextOutputStreamable {
13691374
}
13701375
}
13711376

1377+
private extension String {
1378+
// Replacement for Foundation formatting routine.
1379+
// Loosly Based on example code found on
1380+
// https://developer.apple.com/documentation/swift/using-imported-c-functions-in-swift
1381+
// but using vsnprintf instead of vasprintf due to the latter being unavailabie in Glibc.
1382+
//
1383+
init(format: String, _ arguments: any CVarArg...) {
1384+
guard let value: String = withVaList(arguments, { va_list in
1385+
let bufferSize = 1_024
1386+
var buffer = [Int8](repeating: 0, count: bufferSize)
1387+
let valid = buffer.withUnsafeMutableBytes { ptr in
1388+
// vsnprintf guarantees not to write more than bufferSize - 1 characters plus a final null byte.
1389+
// Negative value indicates some failure; positive values indicate a valid null-terminated
1390+
// string.
1391+
0..<bufferSize ~= format.withCString {
1392+
Int(vsnprintf(ptr.baseAddress, bufferSize, $0, va_list))
1393+
}
1394+
}
1395+
return valid ? String(validatingUTF8: buffer) : ""
1396+
}) else {
1397+
fatalError("Invalid String format for given arguments")
1398+
}
1399+
self = value
1400+
}
1401+
}
1402+
13721403
// swiftlint:enable file_length type_body_length line_length identifier_name

0 commit comments

Comments
 (0)