Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preallocate space for rendered ensure message #197

Merged
merged 2 commits into from Nov 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
38 changes: 24 additions & 14 deletions src/ensure.rs
@@ -1,5 +1,6 @@
use crate::{anyhow, Error};
use core::fmt::{self, Debug, Display, Write};
use crate::Error;
use alloc::string::String;
use core::fmt::{self, Debug, Write};
use core::mem::MaybeUninit;
use core::ptr;
use core::slice;
Expand Down Expand Up @@ -43,6 +44,15 @@ impl Buf {
written: 0,
}
}

fn as_str(&self) -> &str {
unsafe {
str::from_utf8_unchecked(slice::from_raw_parts(
self.bytes.as_ptr().cast::<u8>(),
self.written,
))
}
}
}

impl Write for Buf {
Expand All @@ -68,23 +78,23 @@ impl Write for Buf {
}
}

impl Display for Buf {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(unsafe {
str::from_utf8_unchecked(slice::from_raw_parts(
self.bytes.as_ptr().cast::<u8>(),
self.written,
))
})
}
}

fn render(msg: &'static str, lhs: &dyn Debug, rhs: &dyn Debug) -> Error {
let mut lhs_buf = Buf::new();
if fmt::write(&mut lhs_buf, format_args!("{:?}", lhs)).is_ok() {
let mut rhs_buf = Buf::new();
if fmt::write(&mut rhs_buf, format_args!("{:?}", rhs)).is_ok() {
return anyhow!("{} ({} vs {})", msg, lhs_buf, rhs_buf);
let lhs_str = lhs_buf.as_str();
let rhs_str = rhs_buf.as_str();
// "{msg} ({lhs} vs {rhs})"
let len = msg.len() + 2 + lhs_str.len() + 4 + rhs_str.len() + 1;
let mut string = String::with_capacity(len);
string.push_str(msg);
string.push_str(" (");
string.push_str(lhs_str);
string.push_str(" vs ");
string.push_str(rhs_str);
string.push(')');
return Error::msg(string);
}
}
Error::msg(msg)
Expand Down