Skip to content

Instantly share code, notes, and snippets.

@CryZe
Last active May 23, 2022 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CryZe/bada85a56c40b586e9a7c5487a25de33 to your computer and use it in GitHub Desktop.
Save CryZe/bada85a56c40b586e9a7c5487a25de33 to your computer and use it in GitHub Desktop.
pub trait PopulateString {
fn populate(self, buf: &mut String);
fn as_str(&self) -> &str;
fn into_string(self) -> String {
let mut buf = String::new();
self.populate(&mut buf);
buf
}
}
impl PopulateString for String {
fn populate(self, buf: &mut String) {
*buf = self;
}
fn as_str(&self) -> &str {
self
}
}
impl PopulateString for &str {
fn populate(self, buf: &mut String) {
buf.clear();
buf.push_str(self);
}
fn as_str(&self) -> &str {
self
}
}
impl PopulateString for alloc::borrow::Cow<'_, str> {
fn populate(self, buf: &mut String) {
match self {
alloc::borrow::Cow::Borrowed(s) => s.populate(buf),
alloc::borrow::Cow::Owned(s) => s.populate(buf),
}
}
fn as_str(&self) -> &str {
self
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment