Skip to content
Myr

Merge pull request #197 from dtolnay/ensure

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Preallocate space for rendered ensure message

authored by David Tolnay · committed by GitHub · parents 6f3b70e, a574356 · Browse files · 1 file+24 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+24 added−14 removed

  • other:+24 added−14 removed

1 file+24 added−14 removed

modified:src/ensure.rs+24 added-14 removed
1use crate::{anyhow, Error};2use core::fmt::{self, Debug, Display, Write};1use crate::Error;2use alloc::string::String;3use core::fmt::{self, Debug, Write};4use core::mem::MaybeUninit;5use core::ptr;6use core::slice;7use core::str;
35 unmodified lines
43 bytes: [MaybeUninit::uninit(); 40],44 written: 0,45 }46 }4748 fn as_str(&self) -> &str {49 unsafe {50 str::from_utf8_unchecked(slice::from_raw_parts(51 self.bytes.as_ptr().cast::<u8>(),52 self.written,53 ))54 }55 }56}5758impl Write for Buf {59 fn write_str(&mut self, s: &str) -> fmt::Result {
17 unmodified lines
77 Ok(())78 }79}8071impl Display for Buf {72 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {73 formatter.write_str(unsafe {74 str::from_utf8_unchecked(slice::from_raw_parts(75 self.bytes.as_ptr().cast::<u8>(),76 self.written,77 ))78 })79 }80}8181fn render(msg: &'static str, lhs: &dyn Debug, rhs: &dyn Debug) -> Error {82 let mut lhs_buf = Buf::new();83 if fmt::write(&mut lhs_buf, format_args!("{:?}", lhs)).is_ok() {84 let mut rhs_buf = Buf::new();85 if fmt::write(&mut rhs_buf, format_args!("{:?}", rhs)).is_ok() {87 return anyhow!("{} ({} vs {})", msg, lhs_buf, rhs_buf);86 let lhs_str = lhs_buf.as_str();87 let rhs_str = rhs_buf.as_str();88 // "{msg} ({lhs} vs {rhs})"89 let len = msg.len() + 2 + lhs_str.len() + 4 + rhs_str.len() + 1;90 let mut string = String::with_capacity(len);91 string.push_str(msg);92 string.push_str(" (");93 string.push_str(lhs_str);94 string.push_str(" vs ");95 string.push_str(rhs_str);96 string.push(')');97 return Error::msg(string);98 }99 }100 Error::msg(msg)101}
443 unmodified lines