From 41b4181a2001f5b6297a870e2875dc72e09b1989 Mon Sep 17 00:00:00 2001 From: René Kijewski Date: Mon, 27 Mar 2023 05:10:14 +0200 Subject: Use `try_reserve()` instead of `with_capacity()` `String::with_capacity()` panics if the requested memory could not be allocated. `Template::render()` is fallible method, and the fact that it can panic is not documented. This commit uses `String::try_reserve()` instead, so even for an exceedingly large `SIZE_HINT` the method should not panic. In the generated code `write!()` calls will fail instead with `Err(std::fmt::Error)`. I do not test if `try_reserve()` returned an error, because the rendering might succeed anyway, if less bytes are written than estimated. --- askama/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/askama/src/lib.rs b/askama/src/lib.rs index 906c79a..8806490 100644 --- a/askama/src/lib.rs +++ b/askama/src/lib.rs @@ -82,7 +82,8 @@ pub use crate::error::{Error, Result}; pub trait Template: fmt::Display { /// Helper method which allocates a new `String` and renders into it fn render(&self) -> Result { - let mut buf = String::with_capacity(Self::SIZE_HINT); + let mut buf = String::new(); + let _ = buf.try_reserve(Self::SIZE_HINT); self.render_into(&mut buf)?; Ok(buf) } -- cgit