Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Removed dependency on Foundation #22

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading