Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 36 additions & 1 deletion src/collapsed_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ pub struct CollapsedStack {
/// Contains the data collected by the profiler in collapsed stacks format.
/// The main use case is to call `write_to_file` on a `CollapsedStacks` instance.
/// The resulting file can be opened in a variety of profiling tools.
/// Frame names percent-encode `%`, `;`, carriage returns, and newlines so they
/// cannot be confused with frame or sample delimiters.
/// The format is explained here: https://github.com/jlfwong/speedscope/wiki/Importing-from-custom-sources#brendan-greggs-collapsed-stack-format
pub struct CollapsedStacks(Vec<CollapsedStack>);

Expand Down Expand Up @@ -42,7 +44,15 @@ impl fmt::Display for CollapsedStack {
} else {
write!(f, ";")?;
}
write!(f, "{}", frame)?;
for character in frame.chars() {
match character {
'%' => write!(f, "%25")?,
';' => write!(f, "%3B")?,
'\r' => write!(f, "%0D")?,
'\n' => write!(f, "%0A")?,
other => write!(f, "{other}")?,
}
}
}
write!(f, " {}", self.weight)
}
Expand All @@ -56,3 +66,28 @@ impl fmt::Display for CollapsedStacks {
Ok(())
}
}

#[cfg(test)]
mod tests {
use super::CollapsedStacks;

#[test]
fn escapes_frame_delimiters_and_literal_percent_signs() {
let stacks = CollapsedStacks::new(
vec!["leaf;frame\nnext\r%3B".into(), "root".into()],
vec![vec![0, 1]],
Some(vec![7]),
);
assert_eq!(stacks.to_string(), "root;leaf%3Bframe%0Anext%0D%253B 7\n");
}

#[test]
fn preserves_ordinary_frame_names() {
let stacks = CollapsedStacks::new(
vec!["space::foo(int, β)".into(), "root".into()],
vec![vec![0, 1]],
Some(vec![7]),
);
assert_eq!(stacks.to_string(), "root;space::foo(int, β) 7\n");
}
}
Loading