use crate::juce_var::{marker, Value};
pub const fn bool_pair(a: bool, b: bool) -> [u8; 6] {
let byte_a = if a {
marker::BOOL_TRUE
} else {
marker::BOOL_FALSE
};
let byte_b = if b {
marker::BOOL_TRUE
} else {
marker::BOOL_FALSE
};
[0x01, 0x01, byte_a, 0x01, 0x01, byte_b]
}
pub const PRESS_BYTES: [u8; 6] = bool_pair(true, true);
pub const RELEASE_BYTES: [u8; 6] = bool_pair(false, false);
pub fn press_value() -> Value {
Value::Binary(PRESS_BYTES.to_vec())
}
pub fn release_value() -> Value {
Value::Binary(RELEASE_BYTES.to_vec())
}
pub fn decode_bool_pair(bytes: &[u8]) -> Option<(bool, bool)> {
if bytes.len() != 6 {
return None;
}
if bytes[0] != 0x01 || bytes[1] != 0x01 || bytes[3] != 0x01 || bytes[4] != 0x01 {
return None;
}
let a = match bytes[2] {
marker::BOOL_TRUE => true,
marker::BOOL_FALSE => false,
_ => return None,
};
let b = match bytes[5] {
marker::BOOL_TRUE => true,
marker::BOOL_FALSE => false,
_ => return None,
};
Some((a, b))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TriggerPhase {
Press,
Release,
}
pub type TriggerOrigin = TriggerPhase;
pub fn decode_phase(value: &Value) -> Option<TriggerPhase> {
let bytes = match value {
Value::Binary(b) => b,
_ => return None,
};
let (a, _b) = decode_bool_pair(bytes)?;
if a {
Some(TriggerPhase::Press)
} else {
Some(TriggerPhase::Release)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bool_pair_encoding() {
assert_eq!(PRESS_BYTES, [0x01, 0x01, 0x02, 0x01, 0x01, 0x02]);
assert_eq!(RELEASE_BYTES, [0x01, 0x01, 0x03, 0x01, 0x01, 0x03]);
}
#[test]
fn bool_pair_round_trips() {
assert_eq!(decode_bool_pair(&PRESS_BYTES), Some((true, true)));
assert_eq!(decode_bool_pair(&RELEASE_BYTES), Some((false, false)));
assert_eq!(
decode_bool_pair(&bool_pair(true, false)),
Some((true, false))
);
assert_eq!(
decode_bool_pair(&bool_pair(false, true)),
Some((false, true))
);
}
#[test]
fn decode_phase_semantics() {
assert_eq!(decode_phase(&press_value()), Some(TriggerPhase::Press));
assert_eq!(decode_phase(&release_value()), Some(TriggerPhase::Release));
assert_eq!(decode_phase(&Value::Binary(vec![0x01, 0x01, 0x02])), None);
assert_eq!(decode_phase(&Value::Bool(true)), None);
}
}