osc-ir 0.1.0-alpha.1

Experimental protocol-agnostic Intermediate Representation for OSC data compatible with JSON/MessagePack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
//! # osc-ir
//!
//! ⚠️ **EXPERIMENTAL** ⚠️  
//! This crate is experimental and APIs may change significantly between versions.
//!
//! A protocol-agnostic Intermediate Representation (IR) for OSC-adjacent data structures,
//! designed to work seamlessly with JSON, MessagePack, and other serialization formats.
//!
//! ## Features
//!
//! - **OSC Version Support**: Configurable OSC 1.0 and OSC 1.1 support via feature flags
//! - **no_std Compatible**: Core functionality works without std (requires `alloc` feature for owned containers)
//! - **Bundle Support**: Full OSC Bundle implementation with nested bundle support  
//! - **Flexible Types**: Support for all OSC types including timestamps, binary data, and extensible types
//! - **Serde Integration**: Optional serde support for JSON/MessagePack serialization
//!
//! ## Basic Usage
//!
//! ```rust
//! use osc_ir::{IrValue, IrBundle, IrTimetag};
//!
//! // Create basic values
//! let message = IrValue::from("hello world");
//! let number = IrValue::from(42);
//! let boolean = IrValue::from(true);
//!
//! // Create arrays
//! let array = IrValue::from(vec![
//!     IrValue::from(1),
//!     IrValue::from(2), 
//!     IrValue::from(3)
//! ]);
//!
//! // Create bundles with timetags
//! # #[cfg(feature = "osc10")]
//! # {
//! let mut bundle = IrBundle::new(IrTimetag::from_ntp(12345));
//! bundle.add_message(message);
//! bundle.add_message(number);
//!
//! let bundle_value = IrValue::Bundle(bundle);
//! # }
//! ```

#![cfg_attr(not(test), no_std)]

extern crate alloc;
use alloc::{boxed::Box, string::String, vec::Vec};
use core::fmt;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// MessagePack-friendly timestamp; interoperable with JSON via RFC3339 if needed.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IrTimestamp {
    pub seconds: i64,
    pub nanos: u32,
}

/// OSC-compatible timetag for bundle scheduling.
/// A value of 1 indicates "immediately", larger values represent NTP-style timestamps.
/// Available with OSC 1.0+ support.
#[cfg(feature = "osc10")]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct IrTimetag {
    pub value: u64,
}

#[cfg(feature = "osc10")]
impl IrTimetag {
    /// Creates a timetag for immediate execution
    pub fn immediate() -> Self {
        Self { value: 1 }
    }

    /// Creates a timetag from an NTP-style timestamp
    pub fn from_ntp(ntp_time: u64) -> Self {
        Self { value: ntp_time }
    }

    /// Returns true if this timetag indicates immediate execution
    pub fn is_immediate(&self) -> bool {
        self.value == 1
    }
}

/// An element that can be contained within an OSC bundle.
/// Can be either a message (represented as an IrValue) or a nested bundle.
/// Available with OSC 1.0+ support.
#[cfg(feature = "osc10")]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq)]
pub enum IrBundleElement {
    /// A message or other data structure
    Message(IrValue),
    /// A nested bundle
    Bundle(IrBundle),
}

/// OSC Bundle structure supporting nested bundles with timetags.
/// Available with OSC 1.0+ support.
#[cfg(feature = "osc10")]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq)]
pub struct IrBundle {
    /// When this bundle should be executed
    pub timetag: IrTimetag,
    /// Elements contained in this bundle (messages or nested bundles)
    pub elements: Vec<IrBundleElement>,
}

#[cfg(feature = "osc10")]
impl IrBundle {
    /// Creates a new bundle with immediate execution
    pub fn immediate() -> Self {
        Self {
            timetag: IrTimetag::immediate(),
            elements: Vec::new(),
        }
    }

    /// Creates a new bundle with the specified timetag
    pub fn new(timetag: IrTimetag) -> Self {
        Self {
            timetag,
            elements: Vec::new(),
        }
    }

    /// Adds a message to this bundle
    pub fn add_message(&mut self, message: IrValue) {
        self.elements.push(IrBundleElement::Message(message));
    }

    /// Adds a nested bundle to this bundle
    pub fn add_bundle(&mut self, bundle: IrBundle) {
        self.elements.push(IrBundleElement::Bundle(bundle));
    }

    /// Adds an element to this bundle
    pub fn add_element(&mut self, element: IrBundleElement) {
        self.elements.push(element);
    }

    /// Returns true if this bundle is empty (has no elements)
    pub fn is_empty(&self) -> bool {
        self.elements.is_empty()
    }

    /// Returns the number of elements in this bundle
    pub fn len(&self) -> usize {
        self.elements.len()
    }

    /// Returns true if this bundle should be executed immediately
    pub fn is_immediate(&self) -> bool {
        self.timetag.is_immediate()
    }
}

#[cfg(feature = "osc10")]
impl IrBundleElement {
    /// Returns true if this element is a message
    pub fn is_message(&self) -> bool {
        matches!(self, IrBundleElement::Message(_))
    }

    /// Returns true if this element is a bundle
    pub fn is_bundle(&self) -> bool {
        matches!(self, IrBundleElement::Bundle(_))
    }

    /// Returns a reference to the message if this element is a message
    pub fn as_message(&self) -> Option<&IrValue> {
        match self {
            IrBundleElement::Message(msg) => Some(msg),
            _ => None,
        }
    }

    /// Returns a reference to the bundle if this element is a bundle
    pub fn as_bundle(&self) -> Option<&IrBundle> {
        match self {
            IrBundleElement::Bundle(bundle) => Some(bundle),
            _ => None,
        }
    }
}

/// Protocol-agnostic value space.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, PartialEq, Default)]
pub enum IrValue {
    #[default]
    Null,
    Bool(bool),
    Integer(i64),
    Float(f64),
    String(Box<str>),
    #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
    Binary(Vec<u8>),
    Array(Vec<IrValue>),
    /// Map keys are Strings for JSON compatibility.
    Map(Vec<(String, IrValue)>),
    Timestamp(IrTimestamp),
    /// MessagePack Ext type compatibility; also useful to carry OSC-specific tags.
    Ext {
        type_id: i8,
        #[cfg_attr(feature = "serde", serde(with = "serde_bytes"))]
        data: Vec<u8>,
    },
    /// OSC Bundle with timetag and nested elements
    /// Available with OSC 1.0+ support.
    #[cfg(feature = "osc10")]
    Bundle(IrBundle),
    /// OSC 1.1 Color type (RGBA)
    /// Available with OSC 1.1+ support.
    #[cfg(feature = "osc11")]
    Color {
        r: u8,
        g: u8,
        b: u8,
        a: u8,
    },
    /// OSC 1.1 MIDI message
    /// Available with OSC 1.1+ support.
    #[cfg(feature = "osc11")]
    Midi {
        port: u8,
        status: u8,
        data1: u8,
        data2: u8,
    },
}

impl fmt::Display for IrValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl IrValue {
    pub fn null() -> Self {
        IrValue::Null
    }

    pub fn is_null(&self) -> bool {
        matches!(self, IrValue::Null)
    }

    pub fn as_bool(&self) -> Option<bool> {
        match self {
            IrValue::Bool(v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_integer(&self) -> Option<i64> {
        match self {
            IrValue::Integer(v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_float(&self) -> Option<f64> {
        match self {
            IrValue::Float(v) => Some(*v),
            _ => None,
        }
    }

    pub fn as_str(&self) -> Option<&str> {
        match self {
            IrValue::String(v) => Some(v.as_ref()),
            _ => None,
        }
    }

    pub fn as_binary(&self) -> Option<&[u8]> {
        match self {
            IrValue::Binary(v) => Some(v.as_slice()),
            _ => None,
        }
    }

    pub fn as_array(&self) -> Option<&[IrValue]> {
        match self {
            IrValue::Array(v) => Some(v.as_slice()),
            _ => None,
        }
    }

    pub fn as_map(&self) -> Option<&[(String, IrValue)]> {
        match self {
            IrValue::Map(v) => Some(v.as_slice()),
            _ => None,
        }
    }

    pub fn as_timestamp(&self) -> Option<&IrTimestamp> {
        match self {
            IrValue::Timestamp(v) => Some(v),
            _ => None,
        }
    }

    pub fn as_ext(&self) -> Option<(i8, &[u8])> {
        match self {
            IrValue::Ext { type_id, data } => Some((*type_id, data.as_slice())),
            _ => None,
        }
    }

    #[cfg(feature = "osc10")]
    pub fn as_bundle(&self) -> Option<&IrBundle> {
        match self {
            IrValue::Bundle(bundle) => Some(bundle),
            _ => None,
        }
    }

    #[cfg(feature = "osc11")]
    pub fn as_color(&self) -> Option<(u8, u8, u8, u8)> {
        match self {
            IrValue::Color { r, g, b, a } => Some((*r, *g, *b, *a)),
            _ => None,
        }
    }

    #[cfg(feature = "osc11")]
    pub fn as_midi(&self) -> Option<(u8, u8, u8, u8)> {
        match self {
            IrValue::Midi { port, status, data1, data2 } => Some((*port, *status, *data1, *data2)),
            _ => None,
        }
    }
}

impl From<()> for IrValue {
    fn from(_: ()) -> Self {
        IrValue::Null
    }
}

impl From<bool> for IrValue {
    fn from(v: bool) -> Self {
        IrValue::Bool(v)
    }
}

impl From<i8> for IrValue {
    fn from(v: i8) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<i16> for IrValue {
    fn from(v: i16) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<i32> for IrValue {
    fn from(v: i32) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<i64> for IrValue {
    fn from(v: i64) -> Self {
        IrValue::Integer(v)
    }
}

impl From<isize> for IrValue {
    fn from(v: isize) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<u8> for IrValue {
    fn from(v: u8) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<u16> for IrValue {
    fn from(v: u16) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<u32> for IrValue {
    fn from(v: u32) -> Self {
        IrValue::Integer(v as i64)
    }
}

impl From<f32> for IrValue {
    fn from(v: f32) -> Self {
        IrValue::Float(v as f64)
    }
}

impl From<f64> for IrValue {
    fn from(v: f64) -> Self {
        IrValue::Float(v)
    }
}

impl From<String> for IrValue {
    fn from(v: String) -> Self {
        IrValue::String(v.into_boxed_str())
    }
}

impl From<Box<str>> for IrValue {
    fn from(v: Box<str>) -> Self {
        IrValue::String(v)
    }
}

impl From<&str> for IrValue {
    fn from(v: &str) -> Self {
        IrValue::String(v.into())
    }
}

impl From<Vec<u8>> for IrValue {
    fn from(v: Vec<u8>) -> Self {
        IrValue::Binary(v)
    }
}

impl From<&[u8]> for IrValue {
    fn from(v: &[u8]) -> Self {
        IrValue::Binary(v.to_vec())
    }
}

impl From<Vec<IrValue>> for IrValue {
    fn from(v: Vec<IrValue>) -> Self {
        IrValue::Array(v)
    }
}

impl From<Vec<(String, IrValue)>> for IrValue {
    fn from(v: Vec<(String, IrValue)>) -> Self {
        IrValue::Map(v)
    }
}

impl From<IrTimestamp> for IrValue {
    fn from(v: IrTimestamp) -> Self {
        IrValue::Timestamp(v)
    }
}

#[cfg(feature = "osc10")]
impl From<IrBundle> for IrValue {
    fn from(v: IrBundle) -> Self {
        IrValue::Bundle(v)
    }
}

#[cfg(feature = "osc10")]
impl From<IrTimetag> for IrBundle {
    fn from(timetag: IrTimetag) -> Self {
        IrBundle {
            timetag,
            elements: Vec::new(),
        }
    }
}

#[cfg(feature = "osc10")]
impl From<IrValue> for IrBundleElement {
    fn from(value: IrValue) -> Self {
        IrBundleElement::Message(value)
    }
}

#[cfg(feature = "osc10")]
impl From<IrBundle> for IrBundleElement {
    fn from(bundle: IrBundle) -> Self {
        IrBundleElement::Bundle(bundle)
    }
}

impl IrValue {
    /// Creates a new OSC 1.1 Color value
    #[cfg(feature = "osc11")]
    pub fn color(r: u8, g: u8, b: u8, a: u8) -> Self {
        IrValue::Color { r, g, b, a }
    }

    /// Creates a new OSC 1.1 MIDI message value
    #[cfg(feature = "osc11")]
    pub fn midi(port: u8, status: u8, data1: u8, data2: u8) -> Self {
        IrValue::Midi { port, status, data1, data2 }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn conversions_work() {
        assert_eq!(IrValue::from(true).as_bool(), Some(true));
        assert_eq!(IrValue::from(42_i32).as_integer(), Some(42));
        assert_eq!(IrValue::from(3.5_f32).as_float(), Some(3.5));
        assert_eq!(IrValue::from("hi").as_str(), Some("hi"));
        assert_eq!(IrValue::from(vec![1_u8, 2]).as_binary(), Some(&[1, 2][..]));
        let arr = IrValue::from(vec![IrValue::from(1_i32), IrValue::from(2_i32)]);
        assert_eq!(arr.as_array().unwrap().len(), 2);
        let ts = IrTimestamp {
            seconds: 1,
            nanos: 2,
        };
        assert_eq!(IrValue::from(ts).as_timestamp(), Some(&ts));
    }

    #[test]
    fn ext_and_default_helpers() {
        let ext = IrValue::Ext {
            type_id: 9,
            data: vec![0xAA, 0xBB],
        };
        assert_eq!(ext.as_ext(), Some((9, &[0xAA, 0xBB][..])));

        let default = IrValue::default();
        assert!(default.is_null());
        assert!(default.as_array().is_none());
    }

    #[test]
    #[cfg(feature = "osc10")]
    fn bundle_creation_and_nesting() {
        // Create an immediate bundle
        let mut bundle = IrBundle::immediate();
        assert!(bundle.is_immediate());
        assert!(bundle.is_empty());
        assert_eq!(bundle.len(), 0);

        // Add a message
        bundle.add_message(IrValue::from("hello"));
        assert!(!bundle.is_empty());
        assert_eq!(bundle.len(), 1);

        // Create a nested bundle
        let mut nested_bundle = IrBundle::new(IrTimetag::from_ntp(1000));
        assert!(!nested_bundle.is_immediate());
        nested_bundle.add_message(IrValue::from(42));
        nested_bundle.add_message(IrValue::from(true));

        // Add the nested bundle to the main bundle
        bundle.add_bundle(nested_bundle);
        assert_eq!(bundle.len(), 2);

        // Test element access
        assert!(bundle.elements[0].is_message());
        assert!(!bundle.elements[0].is_bundle());
        assert_eq!(bundle.elements[0].as_message().unwrap().as_str(), Some("hello"));

        assert!(!bundle.elements[1].is_message());
        assert!(bundle.elements[1].is_bundle());
        let nested = bundle.elements[1].as_bundle().unwrap();
        assert_eq!(nested.len(), 2);
        assert_eq!(nested.timetag.value, 1000);
    }

    #[test]
    #[cfg(feature = "osc10")]
    fn bundle_conversions() {
        // Test IrBundle -> IrValue conversion
        let bundle = IrBundle::immediate();
        let value = IrValue::from(bundle.clone());
        assert_eq!(value.as_bundle(), Some(&bundle));

        // Test IrValue -> IrBundleElement conversion
        let message = IrValue::from("test");
        let element = IrBundleElement::from(message.clone());
        assert!(element.is_message());
        assert_eq!(element.as_message(), Some(&message));

        // Test IrBundle -> IrBundleElement conversion
        let element = IrBundleElement::from(bundle.clone());
        assert!(element.is_bundle());
        assert_eq!(element.as_bundle(), Some(&bundle));
    }

    #[test]
    #[cfg(feature = "osc10")]
    fn timetag_functionality() {
        let immediate = IrTimetag::immediate();
        assert!(immediate.is_immediate());
        assert_eq!(immediate.value, 1);

        let ntp_time = IrTimetag::from_ntp(12345678);
        assert!(!ntp_time.is_immediate());
        assert_eq!(ntp_time.value, 12345678);
    }

    #[test]
    #[cfg(feature = "osc10")]
    fn complex_nested_bundle_structure() {
        // Create a complex nested structure
        let mut root_bundle = IrBundle::immediate();
        
        // Add some messages
        root_bundle.add_message(IrValue::from("root message 1"));
        root_bundle.add_message(IrValue::from(100));
        
        // Create first nested bundle
        let mut nested1 = IrBundle::new(IrTimetag::from_ntp(2000));
        nested1.add_message(IrValue::from("nested1 message"));
        
        // Create second nested bundle with its own nested bundle
        let mut nested2 = IrBundle::new(IrTimetag::from_ntp(3000));
        nested2.add_message(IrValue::from("nested2 message"));
        
        let mut deeply_nested = IrBundle::new(IrTimetag::from_ntp(4000));
    deeply_nested.add_message(IrValue::from("deeply nested message"));
    deeply_nested.add_message(IrValue::from(core::f64::consts::PI));
        
        nested2.add_bundle(deeply_nested);
        
        // Add nested bundles to root
        root_bundle.add_bundle(nested1);
        root_bundle.add_bundle(nested2);
        
        // Verify structure
        assert_eq!(root_bundle.len(), 4); // 2 messages + 2 bundles
        assert!(root_bundle.elements[0].is_message());
        assert!(root_bundle.elements[1].is_message());
        assert!(root_bundle.elements[2].is_bundle());
        assert!(root_bundle.elements[3].is_bundle());
        
        // Check the second nested bundle contains a bundle
        let nested2_ref = root_bundle.elements[3].as_bundle().unwrap();
        assert_eq!(nested2_ref.len(), 2); // 1 message + 1 bundle
        assert!(nested2_ref.elements[1].is_bundle());
        
        // Check deeply nested bundle
        let deeply_nested_ref = nested2_ref.elements[1].as_bundle().unwrap();
        assert_eq!(deeply_nested_ref.len(), 2);
        assert_eq!(deeply_nested_ref.timetag.value, 4000);
    }

    #[test]
    #[cfg(feature = "osc11")]
    fn osc_1_1_types() {
        // Test Color type
        let color = IrValue::color(255, 128, 64, 255);
        assert_eq!(color.as_color(), Some((255, 128, 64, 255)));
        
        // Test MIDI type
        let midi = IrValue::midi(0, 144, 60, 127); // Note on, middle C, velocity 127
        assert_eq!(midi.as_midi(), Some((0, 144, 60, 127)));
        
        // Test that non-matching types return None
        assert!(color.as_midi().is_none());
        assert!(midi.as_color().is_none());
        assert!(IrValue::from(42).as_color().is_none());
        assert!(IrValue::from("test").as_midi().is_none());
    }
}