File tree Expand file tree Collapse file tree 2 files changed +31
-10
lines changed
Networking/Sources/Networking Expand file tree Collapse file tree 2 files changed +31
-10
lines changed Original file line number Diff line number Diff line change @@ -62,32 +62,45 @@ public final class Stream: Sendable {
62
62
}
63
63
64
64
public func receive( ) async -> Data ? {
65
- if let data = nextData. value {
66
- nextData. value = nil
65
+ if let data = nextData. exchange ( nil ) {
67
66
return data
68
67
}
69
68
return await channel. receive ( )
70
69
}
71
70
72
71
public func receiveByte( ) async -> UInt8 ? {
73
- if var data = nextData. value {
74
- let byte = data. removeFirst ( )
75
- if data. isEmpty {
76
- nextData. value = nil
72
+ let byte = nextData. write { nextData -> UInt8 ? in
73
+ if var data = nextData {
74
+ let byte = data. removeFirst ( )
75
+ if data. isEmpty {
76
+ nextData = nil
77
+ } else {
78
+ nextData = data
79
+ }
80
+ return byte
77
81
} else {
78
- nextData . value = data
82
+ return nil
79
83
}
84
+ }
85
+ if let byte {
80
86
return byte
81
87
}
82
88
83
89
guard var data = await receive ( ) else {
84
90
return nil
85
91
}
86
92
87
- let byte = data. removeFirst ( )
93
+ let byte2 = data. removeFirst ( )
88
94
if !data. isEmpty {
89
- nextData. value = data
95
+ // TODO: this can append data in wrong order if receiveByte is called concurrently
96
+ nextData. write { nextData in
97
+ if let currentData = nextData {
98
+ nextData = currentData + data
99
+ } else {
100
+ nextData = data
101
+ }
102
+ }
90
103
}
91
- return byte
104
+ return byte2
92
105
}
93
106
}
Original file line number Diff line number Diff line change @@ -24,6 +24,14 @@ public final class ThreadSafeContainer<T>: @unchecked Sendable {
24
24
}
25
25
}
26
26
27
+ public func exchange( _ value: T ) -> T {
28
+ lock. withWriteLock {
29
+ let ret = self . storage
30
+ self . storage = value
31
+ return ret
32
+ }
33
+ }
34
+
27
35
public var value : T {
28
36
get {
29
37
read { $0 }
You can’t perform that action at this time.
0 commit comments