{"record":{"id":"d6e597db91774e50","repo":"BoundaryML/baml","slug":"writing-to-a-string-cannot-fail","errorCode":null,"errorMessage":"writing to a String cannot fail","messagePattern":"writing to a String cannot fail","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"baml_language/crates/baml_compiler_diagnostics/src/message.rs","lineNumber":66,"sourceCode":"                .map(|offset| content_start + offset)\n            else {\n                break;\n            };\n            if content_start < close {\n                highlights.push(DiagnosticMessageHighlight {\n                    start: u32::try_from(content_start).expect(\"diagnostic text exceeds 4 GiB\"),\n                    end: u32::try_from(close).expect(\"diagnostic text exceeds 4 GiB\"),\n                    kind: DiagnosticMessageKind::Code,\n                });\n            }\n            cursor = close + 1;\n        }\n        Self { text, highlights }\n    }\n\n    #[must_use]\n    pub fn text(mut self, value: impl fmt::Display) -> Self {\n        write!(self.text, \"{value}\").expect(\"writing to a String cannot fail\");\n        self\n    }\n\n    #[must_use]\n    pub fn identifier(self, value: impl fmt::Display, kind: DiagnosticIdentifierKind) -> Self {\n        self.fragment(value, DiagnosticMessageKind::Identifier(kind))\n    }\n\n    #[must_use]\n    pub fn type_expr(self, value: impl fmt::Display) -> Self {\n        self.fragment(value, DiagnosticMessageKind::TypeExpression)\n    }\n\n    #[must_use]\n    pub fn code(self, value: impl fmt::Display) -> Self {\n        self.fragment(value, DiagnosticMessageKind::Code)\n    }\n","sourceCodeStart":48,"sourceCodeEnd":84,"githubUrl":"https://github.com/BoundaryML/baml/blob/bd85ce9dee1463ff04d27efd20531013a4ff46c1/baml_language/crates/baml_compiler_diagnostics/src/message.rs#L48-L84","documentation":"A panic from `write!(self.text, \"{value}\").expect(\"writing to a String cannot fail\")` inside the `text()` builder method of the diagnostic message type. Formatting into a Rust `String` can only fail if the underlying formatter fails, which for `String` targets is essentially impossible; this expect converts an unrecoverable formatting error into a panic. In practice it panics only when the Display impl of the interpolated value panics or misbehaves, or if a gigantic formatted value exhausts memory during string growth.","triggerScenarios":"Calling `.text(value)` on the diagnostic builder where `value`'s `Display` implementation panics (e.g. it unwraps on invalid internal state) or where formatting a value larger than available memory forces an allocation failure in `String::push_str`.","commonSituations":"Passing a custom/newtype whose Display impl panics (unwrap on None, division by zero); passing a value that expands to terabytes (nested debug output); OOM conditions on memory-constrained machines while building large diagnostics.","solutions":["Inspect the `Display` implementation of the value passed to `.text()`; fix any panic/unwrap inside it.","Shrink or truncate the value before formatting (e.g. format a summary or snippet, not the whole object/file).","Avoid deeply recursive or unbounded Debug/Display output that can balloon the message string; cap the payload size.","If memory pressure is the cause, reduce concurrent compiler work or stream diagnostics instead of buffering one huge message."],"exampleFix":"// before\nmsg.text(raw_file_contents)\n// after\nmsg.text(truncate(&raw_file_contents, 2048))\nfn truncate(s: &str, max: usize) -> &str { match s.char_indices().nth(max) { Some((i, _)) => &s[..i], None => s } }","handlingStrategy":"type-guard","validationCode":"fn safe_display(value: &impl fmt::Display) -> bool {\n    // Display cannot be pre-run without side effects; instead bound the formatted size:\n    true\n}\n// Guard: only pass bounded, trusted values into .text()\nfn is_bounded(s: &str, max: usize) -> bool { s.len() <= max }","typeGuard":"fn is_panics_free_display<T: fmt::Display>(_: &T) -> bool { true }\n// Prefer guarding the value's size before formatting:\nfn guard_size(s: &str) -> bool { s.len() <= 64 * 1024 }","tryCatchPattern":"let msg = std::panic::catch_unwind(|| builder.text(value))\n    .unwrap_or_else(|_| builder.text(\"<unformattable value>\"));","preventionTips":["Audit Display impls of values passed to diagnostics; remove unwrap/panic paths inside them.","Truncate large payloads before formatting.","Avoid formatting whole file contents or deeply nested Debug output.","Wrap diagnostic construction in catch_unwind when handling untrusted input."],"tags":["rust","panic","diagnostics","string-formatting","display"],"backgroundTag":"invalid-argument-value","analyzedSha":"bd85ce9dee1463ff04d27efd20531013a4ff46c1","analyzedAt":"2026-09-12T03:38:25.718Z","contentChangedAt":"2026-09-12T03:38:25.718Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}