use moteus_protocol::query::QueryFormat;
#[derive(Debug, Clone)]
pub struct WithQuery<C> {
pub command: C,
pub format: QueryFormat,
}
pub trait CommandExt: Sized {
fn with_query(self, format: QueryFormat) -> WithQuery<Self> {
WithQuery {
command: self,
format,
}
}
}
impl<T> CommandExt for T {}
#[derive(Debug, Clone)]
pub enum MaybeQuery<C> {
Default(C),
Override(C, QueryFormat),
}
impl<C> MaybeQuery<C> {
pub fn command(&self) -> &C {
match self {
MaybeQuery::Default(c) => c,
MaybeQuery::Override(c, _) => c,
}
}
pub fn query_override(&self) -> Option<&QueryFormat> {
match self {
MaybeQuery::Default(_) => None,
MaybeQuery::Override(_, f) => Some(f),
}
}
pub fn into_parts(self) -> (C, Option<QueryFormat>) {
match self {
MaybeQuery::Default(c) => (c, None),
MaybeQuery::Override(c, f) => (c, Some(f)),
}
}
}
impl<C> From<C> for MaybeQuery<C> {
fn from(cmd: C) -> Self {
MaybeQuery::Default(cmd)
}
}
impl<C> From<WithQuery<C>> for MaybeQuery<C> {
fn from(wq: WithQuery<C>) -> Self {
MaybeQuery::Override(wq.command, wq.format)
}
}
#[cfg(test)]
mod tests {
use super::*;
use moteus_protocol::command::PositionCommand;
#[test]
fn test_with_query() {
let cmd = PositionCommand::new().position(0.5);
let with_query = cmd.with_query(QueryFormat::default());
assert!(with_query.command.position.is_some());
}
#[test]
fn test_maybe_query_from_command() {
let cmd = PositionCommand::new().position(0.5);
let maybe: MaybeQuery<PositionCommand> = cmd.into();
assert!(maybe.query_override().is_none());
}
#[test]
fn test_maybe_query_from_with_query() {
let cmd = PositionCommand::new()
.position(0.5)
.with_query(QueryFormat::comprehensive());
let maybe: MaybeQuery<PositionCommand> = cmd.into();
assert!(maybe.query_override().is_some());
}
#[test]
fn test_into_parts() {
let cmd = PositionCommand::new().position(0.5);
let maybe: MaybeQuery<PositionCommand> = cmd.into();
let (cmd, format) = maybe.into_parts();
assert!(cmd.position.is_some());
assert!(format.is_none());
}
}