Skip to content

Commit 8fb92e7

Browse files
avolokhovMrLotU
andauthored
fix Buckets helpers to not throw fatal error (#41)
* fix Buckets to not throw fatal error * fix compiler warning * simplify linear buckets creation Co-authored-by: Jari (LotU) <j.koopman@jarict.nl>
1 parent f4d4adf commit 8fb92e7

File tree

2 files changed

+16
-8
lines changed

2 files changed

+16
-8
lines changed

Sources/Prometheus/MetricTypes/Histogram.swift

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,7 @@ public struct Buckets: ExpressibleByArrayLiteral {
3939
/// - count: Amount of buckets to generate, should be larger than zero. The +Inf bucket is not included in this count.
4040
public static func linear(start: Double, width: Double, count: Int) -> Buckets {
4141
assert(count >= 1, "Bucket.linear needs a count larger than 1")
42-
var arr = [Double]()
43-
var s = start
44-
for x in 0..<count {
45-
arr[x] = s
46-
s += width
47-
}
42+
let arr = (0..<count).map { Double(start) + Double($0) * Double(width) }
4843
return Buckets(arr)
4944
}
5045

@@ -60,8 +55,8 @@ public struct Buckets: ExpressibleByArrayLiteral {
6055
assert(factor > 1, "Bucket.exponential needs a factor larger than 1")
6156
var arr = [Double]()
6257
var s = start
63-
for x in 0..<count {
64-
arr[x] = s
58+
for _ in 0..<count {
59+
arr.append(s)
6560
s *= factor
6661
}
6762
return Buckets(arr)
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import XCTest
2+
import Prometheus
3+
class BucketsTests: XCTestCase {
4+
func testExponentialDoesNotThrow() {
5+
let buckets = Buckets.exponential(start: 1, factor: 2, count: 4)
6+
XCTAssertEqual([1.0, 2.0, 4.0, 8.0, Double.greatestFiniteMagnitude], buckets.buckets)
7+
}
8+
9+
func testLinearDoesNotThrow() {
10+
let buckets = Buckets.linear(start: 1, width: 20, count: 4)
11+
XCTAssertEqual([1, 21, 41, 61, Double.greatestFiniteMagnitude], buckets.buckets)
12+
}
13+
}

0 commit comments

Comments
 (0)