mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-06-16 13:34:04 +08:00
Replace inline `buffer.find("\n\n")` SSE splitting logic across streaming,
streaming_responses, response_handler, and response_processor with a shared
`take_sse_block` function that handles both `\n\n` and `\r\n\r\n` delimiters.
72 lines
2.0 KiB
Rust
72 lines
2.0 KiB
Rust
#[inline]
|
|
pub(crate) fn strip_sse_field<'a>(line: &'a str, field: &str) -> Option<&'a str> {
|
|
line.strip_prefix(&format!("{field}: "))
|
|
.or_else(|| line.strip_prefix(&format!("{field}:")))
|
|
}
|
|
|
|
#[inline]
|
|
pub(crate) fn take_sse_block(buffer: &mut String) -> Option<String> {
|
|
let mut best: Option<(usize, usize)> = None;
|
|
|
|
for (delimiter, len) in [("\r\n\r\n", 4usize), ("\n\n", 2usize)] {
|
|
if let Some(pos) = buffer.find(delimiter) {
|
|
if best.is_none_or(|(best_pos, _)| pos < best_pos) {
|
|
best = Some((pos, len));
|
|
}
|
|
}
|
|
}
|
|
|
|
let (pos, len) = best?;
|
|
let block = buffer[..pos].to_string();
|
|
buffer.drain(..pos + len);
|
|
Some(block)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::{strip_sse_field, take_sse_block};
|
|
|
|
#[test]
|
|
fn strip_sse_field_accepts_optional_space() {
|
|
assert_eq!(
|
|
strip_sse_field("data: {\"ok\":true}", "data"),
|
|
Some("{\"ok\":true}")
|
|
);
|
|
assert_eq!(
|
|
strip_sse_field("data:{\"ok\":true}", "data"),
|
|
Some("{\"ok\":true}")
|
|
);
|
|
assert_eq!(
|
|
strip_sse_field("event: message_start", "event"),
|
|
Some("message_start")
|
|
);
|
|
assert_eq!(
|
|
strip_sse_field("event:message_start", "event"),
|
|
Some("message_start")
|
|
);
|
|
assert_eq!(strip_sse_field("id:1", "data"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn take_sse_block_supports_lf_delimiters() {
|
|
let mut buffer = "data: {\"ok\":true}\n\nrest".to_string();
|
|
|
|
assert_eq!(
|
|
take_sse_block(&mut buffer),
|
|
Some("data: {\"ok\":true}".to_string())
|
|
);
|
|
assert_eq!(buffer, "rest");
|
|
}
|
|
|
|
#[test]
|
|
fn take_sse_block_supports_crlf_delimiters() {
|
|
let mut buffer = "data: {\"ok\":true}\r\n\r\nrest".to_string();
|
|
|
|
assert_eq!(
|
|
take_sse_block(&mut buffer),
|
|
Some("data: {\"ok\":true}".to_string())
|
|
);
|
|
assert_eq!(buffer, "rest");
|
|
}
|
|
}
|