mirror of
https://github.com/farion1231/cc-switch.git
synced 2026-06-16 13:34:04 +08:00
refactor(proxy): extract take_sse_block helper with CRLF delimiter support
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.
This commit is contained in:
@@ -4,9 +4,27 @@ pub(crate) fn strip_sse_field<'a>(line: &'a str, field: &str) -> Option<&'a str>
|
||||
.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;
|
||||
use super::{strip_sse_field, take_sse_block};
|
||||
|
||||
#[test]
|
||||
fn strip_sse_field_accepts_optional_space() {
|
||||
@@ -28,4 +46,26 @@ mod tests {
|
||||
);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user