Created
January 20, 2023 19:25
-
-
Save matthewjberger/f6261158557054a6f8e050e20204fe85 to your computer and use it in GitHub Desktop.
Builder pattern for formatting strings from data: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6caf3a78d75d8ecbfec6a277b57829ab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn main() { | |
let topic = TopicBuilder::new("lift", "report") | |
.with_subdevices(&["motor"]) | |
.build(); | |
println!("Topic: {:#?}", &topic); | |
} | |
#[derive(Debug)] | |
pub struct Topic { | |
display: String, | |
metadata: TopicMetadata, | |
} | |
impl std::fmt::Display for Topic { | |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | |
write!(f, "{}", self.display) | |
} | |
} | |
impl PartialEq for Topic { | |
fn eq(&self, other: &Self) -> bool { | |
self.metadata == other.metadata | |
} | |
} | |
#[derive(Default, Debug, PartialEq, Clone)] | |
struct TopicMetadata { | |
name: String, | |
action: String, | |
subdevices: Vec<String>, | |
subposition: Option<String>, | |
} | |
#[derive(Debug)] | |
pub struct TopicBuilder { | |
metadata: TopicMetadata, | |
} | |
impl TopicBuilder { | |
pub fn new(name: &str, action: &str) -> Self { | |
Self { | |
metadata: TopicMetadata { | |
name: name.to_string(), | |
action: action.to_string(), | |
..Default::default() | |
}, | |
} | |
} | |
pub fn with_subdevices(mut self, subdevices: &[&str]) -> Self { | |
let subdevices: Vec<String> = subdevices.into_iter().map(|x| x.to_string()).collect(); | |
self.metadata.subdevices.extend_from_slice(&subdevices); | |
self | |
} | |
pub fn build(self) -> Topic { | |
let Self { metadata } = self; | |
let mut sections = vec![metadata.name.to_string()]; | |
for device in &metadata.subdevices { | |
sections.push(device.to_string()); | |
} | |
if let Some(ref subposition) = metadata.subposition { | |
sections.push(subposition.to_string()); | |
} | |
sections.push(metadata.action.to_string()); | |
let display = sections.join("/"); | |
Topic { display, metadata } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment