-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathRoute.swift
101 lines (91 loc) · 2.54 KB
/
Route.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/// A parser that attempts to run a number of parsers to accumulate output associated with a
/// particular URL endpoint.
///
/// `Route` is a domain-specific version of `Parse`, suited to URL request routing.
public struct Route<Parsers: Parser>: Parser where Parsers.Input == URLRequestData {
@usableFromInline
let parsers: Parsers
@inlinable
public init<Upstream, NewOutput>(
_ transform: @escaping (Upstream.Output) -> NewOutput,
@ParserBuilder with build: () -> Upstream
)
where
Upstream.Input == URLRequestData,
Parsers == Parsing.Parsers.Map<Upstream, NewOutput>
{
self.parsers = build().map(transform)
}
@_disfavoredOverload
@inlinable
public init<Upstream, NewOutput>(
_ output: NewOutput,
@ParserBuilder with build: () -> Upstream
)
where
Upstream.Input == URLRequestData,
Parsers == Parsing.Parsers.MapConstant<Upstream, NewOutput>
{
self.parsers = build().map { output }
}
@inlinable
public init<NewOutput>(
_ output: NewOutput
)
where
Parsers == Parsing.Parsers.MapConstant<Always<URLRequestData, Void>, NewOutput>
{
self.init(output) {
Always<URLRequestData, Void>(())
}
}
@inlinable
public init<C: Conversion, P: Parser>(
_ conversion: C,
@ParserBuilder with parsers: () -> P
)
where
P.Input == URLRequestData,
Parsers == Parsing.Parsers.MapConversion<P, C>
{
self.parsers = parsers().map(conversion)
}
@inlinable
public init<C: Conversion>(
_ conversion: C
) where Parsers == Parsing.Parsers.MapConversion<Always<URLRequestData, Void>, C> {
self.init(conversion) {
Always<URLRequestData, Void>(())
}
}
@inlinable
public func parse(_ input: inout URLRequestData) throws -> Parsers.Output {
let output = try self.parsers.parse(&input)
if input.method != nil {
try Method.get.parse(&input)
}
try PathEnd().parse(input)
return output
}
}
extension Route: ParserPrinter where Parsers: ParserPrinter {
@inlinable
public func print(_ output: Parsers.Output, into input: inout URLRequestData) rethrows {
try self.parsers.print(output, into: &input)
}
}
@usableFromInline
struct PathEnd: ParserPrinter {
@inlinable
public init() {}
@inlinable
public func parse(_ input: inout URLRequestData) throws {
guard var first = input.path.first else { return }
try End().parse(&first)
}
@inlinable
public func print(_ output: (), into input: inout Input) throws {
guard var first = input.path.first else { return }
try End().print((), into: &first)
}
}