Skip to content

Instantly share code, notes, and snippets.

@matthewjberger
Created January 20, 2023 19: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 matthewjberger/f6261158557054a6f8e050e20204fe85 to your computer and use it in GitHub Desktop.
Save matthewjberger/f6261158557054a6f8e050e20204fe85 to your computer and use it in GitHub Desktop.
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