Skip to content

Commit

Permalink
fix: logify could panic if truncating mid-code point (#70)
Browse files Browse the repository at this point in the history
  • Loading branch information
keelerm84 authored Dec 12, 2023
1 parent b6e61d6 commit 37316c4
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions eventsource-client/src/event_parser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,9 @@ pub struct Event {
}

const LOGIFY_MAX_CHARS: usize = 100;
fn logify(bytes: &[u8]) -> &str {
fn logify(bytes: &[u8]) -> String {
let stringified = from_utf8(bytes).unwrap_or("<bad utf8>");
if stringified.len() <= LOGIFY_MAX_CHARS {
stringified
} else {
&stringified[..LOGIFY_MAX_CHARS - 1]
}
stringified.chars().take(LOGIFY_MAX_CHARS).collect()
}

fn parse_field(line: &[u8]) -> Result<Option<(&str, &str)>> {
Expand Down Expand Up @@ -367,6 +363,8 @@ impl EventParser {

#[cfg(test)]
mod tests {
use std::str::FromStr;

use super::{Error::*, *};
use proptest::proptest;
use test_case::test_case;
Expand All @@ -388,6 +386,19 @@ mod tests {
}
}

#[test]
fn test_logify_handles_code_point_boundaries() {
let phase = String::from_str(
"这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。",
)
.expect("Invalid sample string");

let input: &[u8] = phase.as_bytes();
let result = logify(input);

assert!(result == "这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如此。这是一条很长的消息,最初导致我们的代码出现恐慌。我希望情况不再如");
}

#[test]
fn test_parse_field_invalid() {
assert!(parse_field(b"").is_err());
Expand Down

0 comments on commit 37316c4

Please sign in to comment.