-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathBool.swift
50 lines (44 loc) · 1.3 KB
/
Bool.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import Benchmark
import Foundation
import Parsing
/// This benchmark demonstrates how to parse a boolean from the front of an input and compares its
/// performance against `Bool.init`, which does not incrementally parse, and Foundation's `Scanner`
/// type. `Scanner` does not have a `scanBool` method, but we can emulate this functionality by calling
/// `scanString` twice and mapping each result to a boolean.
let boolSuite = BenchmarkSuite(name: "Bool") { suite in
var input = "true"
var expected = true
var output: Bool!
suite.benchmark("Bool.init") {
output = Bool(input)
} tearDown: {
tearDown()
}
suite.benchmark("Bool.parser") {
var input = input[...].utf8
output = try Bool.parser().parse(&input)
} tearDown: {
tearDown()
}
if #available(macOS 10.15, *) {
var scanner: Scanner!
suite.benchmark("Scanner.scanBool") {
output = scanner.scanBool()
} setUp: {
scanner = Scanner(string: input)
} tearDown: {
tearDown()
}
}
func tearDown() {
precondition(output == expected)
(input, expected) = expected ? ("false", false) : ("true", true)
}
}
extension Scanner {
@available(macOS 10.15, *)
func scanBool() -> Bool? {
self.scanString("true").map { _ in true }
?? self.scanString("false").map { _ in false }
}
}