Fix time serialization in v2 encoder

This commit is contained in:
Marcin Kulik
2025-03-31 10:56:53 +02:00
parent 287daeda31
commit dc2444453f
2 changed files with 26 additions and 4 deletions

View File

@@ -251,7 +251,7 @@ mod tests {
let mut enc = Encoder::new(0);
data.extend(enc.header(&header));
data.extend(enc.event(&Event::output(1000001, "hello\r\n".to_owned())));
data.extend(enc.event(&Event::output(1000000, "hello\r\n".to_owned())));
let mut enc = Encoder::new(1000001);
data.extend(enc.event(&Event::output(1000001, "world".to_owned())));
@@ -265,7 +265,7 @@ mod tests {
assert_eq!(lines[0]["width"], 80);
assert_eq!(lines[0]["height"], 24);
assert!(lines[0]["timestamp"].is_null());
assert_eq!(lines[1][0], 1.000001);
assert_eq!(lines[1][0], 1.000000);
assert_eq!(lines[1][1], "o");
assert_eq!(lines[1][2], "hello\r\n");
assert_eq!(lines[2][0], 2.000002);

View File

@@ -194,7 +194,7 @@ impl Encoder {
Ok(format!(
"[{}, {}, {}]",
format_time(event.time + self.time_offset).trim_end_matches('0'),
format_time(event.time + self.time_offset),
serde_json::to_string(&code)?,
data,
))
@@ -202,7 +202,18 @@ impl Encoder {
}
fn format_time(time: u64) -> String {
format!("{}.{:0>6}", time / 1_000_000, time % 1_000_000)
let mut formatted_time = format!("{}.{:0>6}", time / 1_000_000, time % 1_000_000);
let dot_idx = formatted_time.find('.').unwrap();
for idx in (dot_idx + 2..=formatted_time.len() - 1).rev() {
if formatted_time.as_bytes()[idx] != b'0' {
break;
}
formatted_time.truncate(idx);
}
formatted_time
}
impl serde::Serialize for V2Header {
@@ -380,3 +391,14 @@ impl From<&V2Theme> for tty::Theme {
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn format_time() {
assert_eq!(super::format_time(0), "0.0");
assert_eq!(super::format_time(1000001), "1.000001");
assert_eq!(super::format_time(12300000), "12.3");
assert_eq!(super::format_time(12000003), "12.000003");
}
}