File tree Expand file tree Collapse file tree 2 files changed +51
-5
lines changed
Expand file tree Collapse file tree 2 files changed +51
-5
lines changed Original file line number Diff line number Diff line change 1+ //
2+ // Data+Trim.swift
3+ // EventSource
4+ //
5+ // Created by Firdavs Khaydarov on 06/07/2025.
6+ //
7+
8+ import Foundation
9+
10+ extension Data {
11+ package func trimmingPrefix( while predicate: ( Element ) -> Bool ) -> SubSequence {
12+ let start = endOfPrefix ( while: predicate)
13+ return self [ start..< endIndex]
14+ }
15+
16+ package func trimmingSuffix( while predicate: ( Element ) -> Bool ) -> SubSequence {
17+ let end = startOfSuffix ( while: predicate)
18+ return self [ startIndex..< end]
19+ }
20+
21+ package func trimming( while predicate: ( Element ) -> Bool ) -> SubSequence {
22+ trimmingPrefix ( while: predicate) . trimmingSuffix ( while: predicate)
23+ }
24+
25+ package func endOfPrefix( while predicate: ( Element ) -> Bool ) -> Index {
26+ var index = startIndex
27+ while index != endIndex && predicate ( self [ index] ) {
28+ formIndex ( after: & index)
29+ }
30+ return index
31+ }
32+
33+ package func startOfSuffix( while predicate: ( Element ) -> Bool ) -> Index {
34+ var index = endIndex
35+ while index != startIndex {
36+ let after = index
37+ formIndex ( before: & index)
38+ if !predicate( self [ index] ) {
39+ return after
40+ }
41+ }
42+ return index
43+ }
44+ }
Original file line number Diff line number Diff line change @@ -77,16 +77,18 @@ struct ServerEventParser: EventParser {
7777
7878 private func cleanMessageData( _ messageData: Data ) -> Data {
7979 var cleanData = messageData
80+
8081 // remove trailing CR/LF characters from the end
8182 while !cleanData. isEmpty, cleanData. last == Self . cr || cleanData. last == Self . lf {
8283 cleanData = cleanData. dropLast ( )
8384 }
84- guard let messageString = String ( data : cleanData , encoding : . utf8 ) else { return cleanData }
85+
8586 // also clean internal lines within each message to remove trailing \r
86- let cleanedLines = messageString. components ( separatedBy: . newlines)
87- . map { $0. trimmingCharacters ( in: CharacterSet ( charactersIn: " \r " ) ) }
88- let cleanedMessage = cleanedLines. joined ( separator: " \n " )
89- return Data ( cleanedMessage. utf8)
87+ let cleanedLines = cleanData. split ( separator: Self . lf)
88+ . map { line in line. trimming ( while: { $0 == Self . cr } ) }
89+ . joined ( separator: [ Self . lf] )
90+
91+ return Data ( cleanedLines)
9092 }
9193}
9294
You can’t perform that action at this time.
0 commit comments