It's possible to do it without allocation, and without any buffer, just by implementing core::fmt::Write
trait, as @Masklinn mentioned.
Here is sample implementation:
#![no_std]
use core::fmt::{Display, Formatter, Result, Write};
struct B {}
impl Display for B {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
write!(f, "A {} C", "B")
}
}
struct Comparator<'a> {
valid: bool,
to_compare: &'a str
}
impl<'a> Comparator<'a> {
fn new(s: &'a str) -> Self {
Self { valid: true, to_compare: s }
}
fn is_valid(self) -> bool {
self.valid && self.to_compare.is_empty()
}
}
impl<'a> Write for Comparator<'a> {
fn write_str(&mut self, s: &str) -> Result {
if s.eq(self.to_compare) {
self.valid = self.valid && true;
self.to_compare = "";
return Ok(());
}
if self.to_compare.starts_with(s) && self.to_compare.len() >= s.len() {
self.to_compare = &self.to_compare[s.len()..];
} else {
self.valid = false
}
Ok(())
}
}
#[test]
fn it_works() {
let mut cmp = Comparator::new("A B C");
let _ = write!(&mut cmp, "{}", B{});
assert!(cmp.is_valid());
}
#[test]
fn too_short() {
let mut cmp = Comparator::new("A B");
let _ = write!(&mut cmp, "{}", B{});
assert!(!cmp.is_valid());
}
#[test]
fn too_long() {
let mut cmp = Comparator::new("A B C D");
let _ = write!(&mut cmp, "{}", B{});
assert!(!cmp.is_valid());
}
EDIT: fixed bug in the code, was:
if self.to_compare.starts_with(s) && self.to_compare.len() >= s.len() {
self.to_compare = &self.to_compare[s.len()..];
self.valid = true
} else {
self.valid = false
}
fixed:
if self.to_compare.starts_with(s) && self.to_compare.len() >= s.len() {
self.to_compare = &self.to_compare[s.len()..];
} else {
self.valid = false
}