Skip to main content

restore_leading

Function restore_leading 

Source
pub fn restore_leading(formatted: String, had_bom: bool) -> String
Expand description

Re-prepend a leading BOM if had_bom. Idempotent: a call where formatted already starts with a BOM returns the input unchanged.

Takes and returns an owned String so the no-BOM path (the overwhelming majority of files) returns the input with zero reallocation and zero byte copies.

The BOM-prepend path is one allocation (guaranteed by the explicit reserve(BOM_LEN) before insert_str) plus an O(n) memmove of the existing bytes by 3 positions. Without the explicit reserve, format_source’s typically-tight-capacity String would force insert_str to grow the buffer first AND THEN shift — two passes over the bytes instead of one.

let body = "2024-01-01 open Assets:Bank\n".to_string();

// No BOM requested → return as-is.
let out = restore_leading(body.clone(), false);
assert_eq!(out, body);

// BOM requested and not present → prepend.
let out = restore_leading(body.clone(), true);
assert!(out.starts_with(BOM));
assert_eq!(&out[BOM.len()..], body);

// BOM requested and already present → idempotent no-op.
let with_bom = format!("{BOM}{body}");
let out = restore_leading(with_bom.clone(), true);
assert_eq!(out, with_bom);