Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement std::fmt::Display for all OSC types #53

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ std = []
byteorder = {version = "1", default-features = false}
clippy = {version = "^0", optional = true}
nom = {version = "7", default-features = false, features = ["alloc"]}
time = { version = "0.3.9", default-features = false, features = ["formatting"] }

[dev-dependencies]
hex = {version = "0.4"}
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ extern crate std as alloc;
extern crate byteorder;
extern crate nom;

#[cfg(feature = "std")]
extern crate time;

/// Crate specific error types.
mod errors;
/// OSC data types, see [OSC 1.0 specification](https://opensoundcontrol.stanford.edu/spec-1_0.html) for details.
Expand Down
124 changes: 124 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use std::{
time::{Duration, SystemTime, UNIX_EPOCH},
};

#[cfg(feature = "std")]
use time::{format_description::well_known::Iso8601, OffsetDateTime};

use crate::alloc::{
string::{String, ToString},
vec::Vec,
Expand Down Expand Up @@ -102,6 +105,15 @@ impl From<OscTime> for SystemTime {
}
}

#[cfg(feature = "std")]
impl Display for OscTime {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let time: OffsetDateTime = SystemTime::from(*self).into();
let formatted = time.format(&Iso8601::DEFAULT).map_err(|_| fmt::Error)?;
f.write_str(&formatted)
}
}

impl From<(u32, u32)> for OscTime {
fn from(time: (u32, u32)) -> OscTime {
let (seconds, fractional) = time;
Expand Down Expand Up @@ -206,6 +218,44 @@ impl From<(u32, u32)> for OscType {
}
}

#[cfg(feature = "std")]
impl Display for OscType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OscType::Int(v) => write!(f, "(i) {v}"),
OscType::Float(v) => write!(f, "(f) {v}"),
OscType::String(v) => write!(f, "(s) {v}"),
OscType::Blob(v) => {
f.write_str("(b)")?;
if v.is_empty() {
return Ok(());
}

f.write_str(" 0x")?;
write_hex(f, v)
}
OscType::Time(v) => write!(f, "(t) {v}"),
OscType::Long(v) => write!(f, "(h) {v}"),
OscType::Double(v) => write!(f, "(d) {v}"),
OscType::Char(v) => write!(f, "(c) {v}"),
OscType::Color(v) => write!(f, "(r) {v}", ),
OscType::Midi(v) => write!(f, "(m) {v}", ),
OscType::Bool(v) => f.write_str(if *v { "(T)" } else { "(F)" }),
OscType::Array(v) => write!(f, "{v}"),
OscType::Nil => f.write_str("(N)"),
OscType::Inf => f.write_str("(I)"),
}
}
}

#[cfg(feature = "std")]
fn write_hex(f: &mut dyn fmt::Write, v: &Vec<u8>) -> fmt::Result {
for octet in v {
write!(f, "{:02X}", octet)?;
}
Ok(())
}

#[cfg(feature = "std")]
impl TryFrom<SystemTime> for OscType {
type Error = OscTimeError;
Expand Down Expand Up @@ -238,6 +288,17 @@ pub struct OscMidiMessage {
pub data2: u8,
}

#[cfg(feature = "std")]
impl Display for OscMidiMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{{port:{}, status:0x{:02X}, data:0x{:02X}{:02X}}}",
self.port, self.status, self.data1, self.data2,
)
}
}

/// An *osc packet* can contain an *osc message* or a bundle of nested messages
/// which is called *osc bundle*.
#[derive(Clone, Debug, PartialEq)]
Expand All @@ -246,6 +307,16 @@ pub enum OscPacket {
Bundle(OscBundle),
}

#[cfg(feature = "std")]
impl Display for OscPacket {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OscPacket::Message(m) => m.fmt(f),
OscPacket::Bundle(b) => b.fmt(f),
}
}
}

/// An OSC message consists of an address and
/// zero or more arguments. The address should
/// specify an element of your Instrument (or whatever
Expand All @@ -258,6 +329,19 @@ pub struct OscMessage {
pub args: Vec<OscType>,
}

#[cfg(feature = "std")]
impl Display for OscMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let args = self
.args
.iter()
.map(OscType::to_string)
.collect::<Vec<String>>()
.join(", ");
write!(f, "{}, {}", self.addr, args)
}
}

/// An OSC bundle contains zero or more OSC packets
/// and a time tag. The contained packets *should* be
/// applied at the given time tag.
Expand All @@ -267,6 +351,19 @@ pub struct OscBundle {
pub content: Vec<OscPacket>,
}

#[cfg(feature = "std")]
impl Display for OscBundle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let content = self
.content
.iter()
.map(OscPacket::to_string)
.collect::<Vec<String>>()
.join("; ");
write!(f, "#bundle {} {{ {} }}", self.timetag, content)
}
}

/// An RGBA color.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OscColor {
Expand All @@ -276,6 +373,20 @@ pub struct OscColor {
pub alpha: u8,
}

#[cfg(feature = "std")]
impl Display for OscColor {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{{{r},{g},{b},{a}}}",
r = self.red,
g = self.green,
b = self.blue,
a = self.alpha
)
}
}

/// An OscArray color.
#[derive(Clone, Debug, PartialEq)]
pub struct OscArray {
Expand All @@ -290,6 +401,19 @@ impl<T: Into<OscType>> FromIterator<T> for OscArray {
}
}

#[cfg(feature = "std")]
impl Display for OscArray {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let items = self
.content
.iter()
.map(OscType::to_string)
.collect::<Vec<String>>()
.join(",");
write!(f, "[{items}]")
}
}

pub type Result<T> = result::Result<T, errors::OscError>;

impl From<String> for OscMessage {
Expand Down
Loading