-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBlockingArrayBasedJSONStream.swift
83 lines (66 loc) · 1.75 KB
/
BlockingArrayBasedJSONStream.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
import AtomicModels
import Dispatch
import Foundation
public final class BlockingArrayBasedJSONStream: AppendableJSONStream {
private let readLock = NSLock()
private let writeLock = DispatchSemaphore(value: 0)
private let storage = AtomicValue<[UInt8]>([])
private var willProvideMoreData = true
public init() {}
public func append(bytes: [UInt8]) {
storage.withExclusiveAccess {
$0.insert(contentsOf: bytes.reversed(), at: 0)
}
onNewData()
}
// MARK: - JSONStream
public func touch() -> UInt8? {
return lastByte(delete: false)
}
public func read() -> UInt8? {
return lastByte(delete: true)
}
public func close() {
willProvideMoreData = false
onStreamClose()
}
private func lastByte(delete: Bool) -> UInt8? {
readLock.lock()
defer {
readLock.unlock()
}
if storage.currentValue().isEmpty {
if willProvideMoreData {
waitForNewDataOrStreamCloseEvent()
} else {
return nil
}
}
return storage.withExclusiveAccess {
if delete {
return $0.popLast()
} else {
return $0.last
}
}
}
private func waitForNewDataOrStreamCloseEvent() {
writeLock.waitForUnblocking()
}
private func onNewData() {
writeLock.unblock()
}
private func onStreamClose() {
writeLock.unblock()
}
}
extension DispatchSemaphore {
func waitForUnblocking() {
wait()
signal()
}
func unblock() {
signal()
wait()
}
}