Optimized SSE message formatting with minimal allocations. :param data: The message data :param event: Optional event type :param id: Optional event ID :param retry: Optional retry time in milliseconds :return: SSE-formatted string
(data: str, event: str | None = None, id: str | None = None, retry: int | None = None)
| 193 | |
| 194 | |
| 195 | def SSEMessage(data: str, event: str | None = None, id: str | None = None, retry: int | None = None) -> str: |
| 196 | """ |
| 197 | Optimized SSE message formatting with minimal allocations. |
| 198 | |
| 199 | :param data: The message data |
| 200 | :param event: Optional event type |
| 201 | :param id: Optional event ID |
| 202 | :param retry: Optional retry time in milliseconds |
| 203 | :return: SSE-formatted string |
| 204 | """ |
| 205 | # Pre-calculate size to avoid multiple string concatenations |
| 206 | parts = [] |
| 207 | |
| 208 | # Add optional fields first |
| 209 | if event: |
| 210 | parts.append(f"event: {event}\n") |
| 211 | if id: |
| 212 | parts.append(f"id: {id}\n") |
| 213 | if retry: |
| 214 | parts.append(f"retry: {retry}\n") |
| 215 | |
| 216 | # Handle data with optimized multi-line processing |
| 217 | if data: |
| 218 | data_str = str(data) |
| 219 | # Fast path for single-line data (most common case) |
| 220 | if "\n" not in data_str and "\r" not in data_str: |
| 221 | parts.append(f"data: {data_str}\n") |
| 222 | else: |
| 223 | # Multi-line data handling |
| 224 | normalized_data = data_str.replace("\r\n", "\n").replace("\r", "\n") |
| 225 | for line in normalized_data.split("\n"): |
| 226 | parts.append(f"data: {line}\n") |
| 227 | else: |
| 228 | parts.append("data: \n") |
| 229 | |
| 230 | # Add the required double newline terminator |
| 231 | parts.append("\n") |
| 232 | |
| 233 | # Single join operation for optimal performance |
| 234 | return "".join(parts) |
no outgoing calls