midi2 0.11.1

Ergonomic, versatile, strong types wrapping MIDI 2.0 message data.
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
//! Generic backing buffers for messages wrapper types.
//!
//! All messages in midi2 are backed by a generic buffer type.
//!
//! ```rust
//! use midi2::prelude::*;
//!
//! let buffer = [
//!     0x3E16_0001,
//!     0x0203_0405,
//!     0x3E26_0607,
//!     0x0809_0A0B,
//!     0x3E26_0C0D,
//!     0x0E0F_1011,
//!     0x3E26_1213,
//!     0x1415_1617,
//!     0x3E26_1819,
//!     0x1A1B_1C1D,
//!     0x3E26_1E1F,
//!     0x2021_2223,
//!     0x3E26_2425,
//!     0x2627_2829,
//!     0x3E26_2A2B,
//!     0x2C2D_2E2F,
//!     0x3E32_3031,
//!     0x0000_0000,
//! ];
//!
//! // A message can be backed with a borrowed slice of data.
//! let message: UmpMessage<&[u32]> = UmpMessage::try_from(&buffer[..]).expect("Valid data");
//!
//! // Or a vector
//! let vector_backed: UmpMessage<Vec<u32>> = message.rebuffer_into();
//!
//! // Or a fixed size array
//! let arr_backed: UmpMessage<[u32; 18]> = vector_backed
//!     .try_rebuffer_into()
//!     .expect("Buffer large enough");
//!
//! // (Or indeed a custom buffer, if you implement the right traits!)
//! ```
//! A buffer can be any data type which returns a slice of `u32` or `u8`.
//!
//! The buffer traits are already implemented for some typical standard rust types:
//! * `&[U] where U: Unit`
//! * `&mut [U] where U: Unit`
//! * `[U; SIZE] where U: Unit`
//! * `Vec<U> where U: Unit` (with the `std` feature enabled)
//!
//! The api of the message wrapper changes depending on the traits of the
//! backing buffer.
//!
//! For example `&[U]` implements [Buffer]
//! but doesn't implement [BufferMut] so messages
//! backed by a `&[U]` are imutable.
//!
//! ```compile_fail,E0277
//! use midi2::{
//!     prelude::*,
//!     channel_voice1::NoteOn,
//! };
//!
//! let mut message: NoteOn<&[u32]> = NoteOn::try_from(&[0x2D9E_753D][..]).expect("Valid data");
//!
//! // the immutable api is available
//! assert_eq!(message.note_number(), u7::default());
//!
//! // error[E0277]: the trait bound `&[u32]: BufferMut` is not satisfied
//! message.set_note_number(u7::new(0x60));
//! ```
//!
//! `[U: SIZE]` buffers implement [BufferMut], but only
//! [BufferTryResize] so any methods which require
//! a resize are aivaible only in the fallible form.
//!
//! ```rust
//! use midi2::prelude::*;
//!
//! let mut message = sysex8::Sysex8::<[u32; 64]>::new();
//! assert_eq!(message.try_set_payload(0..20), Ok(()));
//! ```
//! `Vec<U>` implements [BufferMut] and [BufferResize].
//! Messages backed with with such buffers have the most powerful api.
//!
//! ```rust
//! use midi2::prelude::*;
//!
//! let mut message = sysex8::Sysex8::<Vec<u32>>::new();
//! message.set_payload(0..20); // "cannot" fail
//! ```
//!
//! ## Implementing Custom Buffers
//!
//! Using the traits from this module it is entirely
//! possible to create a custom backing buffer.
//!
//! One potential fancy use case might be to create a non-allocating
//! resizable buffer which uses an arena allocator.

use crate::error::BufferOverflow;

/// The generic unit type contained within [Buffer] slices.
///
/// This is a sealed trait.
/// It's only implemented for [u8] and [u32].
///
/// A [Buffer] with `U = u8` is a [Bytes] buffer.
///
/// A [Buffer] with `U = u32` is a [Ump] buffer.
#[allow(private_bounds)]
pub trait Unit: Copy + UnitPrivate {
    fn zero() -> Self;
}

impl Unit for u8 {
    fn zero() -> Self {
        0x0
    }
}

impl Unit for u32 {
    fn zero() -> Self {
        0x0
    }
}

/// Generic data representation for MIDI message wrapper types.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait Buffer {
    type Unit: Unit;
    fn buffer(&self) -> &[Self::Unit];
}

/// Buffer types which own mutable data.
pub trait BufferMut: Buffer {
    fn buffer_mut(&mut self) -> &mut [<Self as Buffer>::Unit];
}

/// Buffer types which are default constructible.
///
/// For more info see the [buffer module docs](crate::buffer).
// N.B. This is needed because core::default::Default
// is not implemented for arrays which are generic over size
pub trait BufferDefault {
    fn default() -> Self;
}

/// Buffer types which can support arbitrary resizing.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait BufferResize {
    fn resize(&mut self, size: usize);
}

/// Buffer types which can resize, but with a chance of failure.
///
/// Note: This trait is also implemented by buffers of a fixed size.
/// In this case `try_resize` should return Ok whenever
/// the requested size is less than or equal to the fixed
/// size of the buffer and an Err otherwise.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait BufferTryResize {
    fn try_resize(&mut self, size: usize) -> Result<(), BufferOverflow>;
}

/// Allow messages to convert between different backing buffers.
///
/// If a buffer `A` implements [`FromBuffer<B>`] then messages backed by `A`
/// can created from messages backed by `B` with the
/// [`RebufferFrom`](crate::RebufferFrom) trait.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait FromBuffer<T>: Sized {
    fn from_buffer(value: T) -> Self;
}

/// Allow messages to convert between different backing buffers.
///
/// If a buffer `A` implements `IntoBuffer<B>` then messages backed by `A`
/// can be converted into messages backed by `B` with the
/// [`RebufferInto`](crate::RebufferInto) trait.
///
/// Note that one should implement [`FromBuffer`]
/// and automatically get [`IntoBuffer`] for free from the blanket implementation
/// (similarly to [core::convert::Into]).
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait IntoBuffer<T>: Sized {
    fn into_buffer(self) -> T;
}

impl<T, U> IntoBuffer<U> for T
where
    U: FromBuffer<T>,
{
    fn into_buffer(self) -> U {
        U::from_buffer(self)
    }
}

/// Allow messages to convert between different backing buffers with the possibility
/// of overflow.
///
/// If a buffer `A` implements [`TryFromBuffer<B>`] then messages backed by `A`
/// can created from messages backed by `B` with the
/// [`TryRebufferFrom`](crate::TryRebufferFrom) trait.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait TryFromBuffer<T>: Sized {
    fn try_from_buffer(value: T) -> Result<Self, crate::error::BufferOverflow>;
}

/// Allow messages to convert between different backing buffers with the possibility
/// of overflow.
///
/// If a buffer `A` implements `TryIntoBuffer<B>` then messages backed by `A`
/// can be converted into messages backed by `B` with the
/// [`TryRebufferInto`](crate::TryRebufferInto) trait.
///
/// Note that one should implement [`TryFromBuffer`]
/// and automatically get [`TryIntoBuffer`] for free from the blanket implementation
/// (similarly to [core::convert::Into]).
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait TryIntoBuffer<T>: Sized {
    fn try_into_buffer(self) -> Result<T, crate::error::BufferOverflow>;
}

impl<T, U> TryIntoBuffer<U> for T
where
    U: TryFromBuffer<T>,
{
    fn try_into_buffer(self) -> Result<U, crate::error::BufferOverflow> {
        U::try_from_buffer(self)
    }
}

/// Buffers with `Self::Unit = u32`.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait Ump: Buffer<Unit = u32> {}

impl<B: Buffer<Unit = u32>> Ump for B {}

/// Buffers with `Self::Unit = u8`.
///
/// For more info see the [buffer module docs](crate::buffer).
pub trait Bytes: Buffer<Unit = u8> {}

impl<B: Buffer<Unit = u8>> Bytes for B {}

impl<U: Unit> Buffer for &[U] {
    type Unit = U;
    fn buffer(&self) -> &[Self::Unit] {
        self
    }
}

impl<U: Unit> Buffer for &mut [U] {
    type Unit = U;
    fn buffer(&self) -> &[Self::Unit] {
        self
    }
}

impl<U: Unit> BufferMut for &mut [U] {
    fn buffer_mut(&mut self) -> &mut [<Self as Buffer>::Unit] {
        self
    }
}

impl<const SIZE: usize, U: Unit> Buffer for [U; SIZE] {
    type Unit = U;
    fn buffer(&self) -> &[Self::Unit] {
        &self[..]
    }
}

impl<const SIZE: usize, U: Unit> BufferMut for [U; SIZE] {
    fn buffer_mut(&mut self) -> &mut [<Self as Buffer>::Unit] {
        &mut self[..]
    }
}

impl<const SIZE: usize, U: Unit> BufferDefault for [U; SIZE] {
    fn default() -> Self {
        [U::zero(); SIZE]
    }
}

impl<const SIZE: usize, U: Unit> BufferTryResize for [U; SIZE] {
    fn try_resize(&mut self, size: usize) -> Result<(), BufferOverflow> {
        if size > self.len() {
            Err(BufferOverflow)
        } else {
            Ok(())
        }
    }
}

impl<U: Unit> BufferTryResize for &mut [U] {
    fn try_resize(&mut self, size: usize) -> Result<(), BufferOverflow> {
        if size > self.len() {
            Err(BufferOverflow)
        } else {
            Ok(())
        }
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> Buffer for std::vec::Vec<U> {
    type Unit = U;
    fn buffer(&self) -> &[Self::Unit] {
        self
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> BufferMut for std::vec::Vec<U> {
    fn buffer_mut(&mut self) -> &mut [<Self as Buffer>::Unit] {
        self
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> BufferResize for std::vec::Vec<U> {
    fn resize(&mut self, size: usize) {
        self.resize(size, U::zero());
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> BufferDefault for std::vec::Vec<U> {
    fn default() -> Self {
        Default::default()
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> Buffer for &mut std::vec::Vec<U> {
    type Unit = U;
    fn buffer(&self) -> &[Self::Unit] {
        self
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> BufferMut for &mut std::vec::Vec<U> {
    fn buffer_mut(&mut self) -> &mut [<Self as Buffer>::Unit] {
        self
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> BufferResize for &mut std::vec::Vec<U> {
    fn resize(&mut self, size: usize) {
        std::vec::Vec::resize(*self, size, U::zero());
    }
}

//
// conversion
//

impl<const SIZE: usize, U: Unit> TryFromBuffer<&[U]> for [U; SIZE] {
    fn try_from_buffer(value: &[U]) -> Result<Self, crate::error::BufferOverflow> {
        if value.len() > SIZE {
            return Err(crate::error::BufferOverflow);
        }
        let mut buffer = [U::zero(); SIZE];
        buffer[..value.len()].copy_from_slice(value);
        Ok(buffer)
    }
}

impl<const SIZE: usize, U: Unit> TryFromBuffer<&mut [U]> for [U; SIZE] {
    fn try_from_buffer(value: &mut [U]) -> Result<Self, crate::error::BufferOverflow> {
        if value.len() > SIZE {
            return Err(crate::error::BufferOverflow);
        }
        let mut buffer = [U::zero(); SIZE];
        buffer[..value.len()].copy_from_slice(value);
        Ok(buffer)
    }
}

#[cfg(any(feature = "std", test))]
impl<const SIZE: usize, U: Unit> TryFromBuffer<std::vec::Vec<U>> for [U; SIZE] {
    fn try_from_buffer(value: std::vec::Vec<U>) -> Result<Self, crate::error::BufferOverflow> {
        if value.len() > SIZE {
            return Err(crate::error::BufferOverflow);
        }
        let mut buffer = [U::zero(); SIZE];
        buffer[..value.len()].copy_from_slice(&value[..]);
        Ok(buffer)
    }
}

impl<'a, U: Unit> FromBuffer<&'a mut [U]> for &'a [U] {
    fn from_buffer(value: &'a mut [U]) -> Self {
        value
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit, const SIZE: usize> FromBuffer<[U; SIZE]> for std::vec::Vec<U> {
    fn from_buffer(value: [U; SIZE]) -> Self {
        value.to_vec()
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> FromBuffer<&[U]> for std::vec::Vec<U> {
    fn from_buffer(value: &[U]) -> Self {
        value.to_vec()
    }
}

#[cfg(any(feature = "std", test))]
impl<U: Unit> FromBuffer<&mut [U]> for std::vec::Vec<U> {
    fn from_buffer(value: &mut [U]) -> Self {
        value.to_vec()
    }
}

//
// private
//

pub(crate) const UNIT_ID_U8: u8 = 0;
pub(crate) const UNIT_ID_U32: u8 = 1;

pub(crate) trait UnitPrivate: Copy {
    const UNIT_ID: u8;
    fn specialise_buffer_u8(buffer: &[Self]) -> &[u8];
    fn specialise_buffer_u8_mut(buffer: &mut [Self]) -> &mut [u8];

    fn specialise_buffer_u32(buffer: &[Self]) -> &[u32];
    fn specialise_buffer_u32_mut(buffer: &mut [Self]) -> &mut [u32];
}

impl UnitPrivate for u8 {
    const UNIT_ID: u8 = 0;
    fn specialise_buffer_u8(buffer: &[Self]) -> &[u8] {
        buffer
    }
    fn specialise_buffer_u8_mut(buffer: &mut [Self]) -> &mut [u8] {
        buffer
    }
    fn specialise_buffer_u32(_: &[Self]) -> &[u32] {
        unreachable!()
    }
    fn specialise_buffer_u32_mut(_: &mut [Self]) -> &mut [u32] {
        unreachable!()
    }
}

impl UnitPrivate for u32 {
    const UNIT_ID: u8 = 1;
    fn specialise_buffer_u8(_: &[Self]) -> &[u8] {
        unreachable!()
    }
    fn specialise_buffer_u8_mut(_: &mut [Self]) -> &mut [u8] {
        unreachable!()
    }
    fn specialise_buffer_u32(buffer: &[Self]) -> &[u32] {
        buffer
    }
    fn specialise_buffer_u32_mut(buffer: &mut [Self]) -> &mut [u32] {
        buffer
    }
}

pub(crate) trait SpecialiseU32<B: Buffer> {
    fn specialise_u32(&self) -> &[u32];
    fn specialise_u32_mut(&mut self) -> &mut [u32]
    where
        B: BufferMut;
}

impl<B: Buffer> SpecialiseU32<B> for B {
    fn specialise_u32(&self) -> &[u32] {
        match B::Unit::UNIT_ID {
            UNIT_ID_U32 => <B::Unit as UnitPrivate>::specialise_buffer_u32(self.buffer()),
            _ => unreachable!(),
        }
    }
    fn specialise_u32_mut(&mut self) -> &mut [u32]
    where
        B: BufferMut,
    {
        match B::Unit::UNIT_ID {
            UNIT_ID_U32 => <B::Unit as UnitPrivate>::specialise_buffer_u32_mut(self.buffer_mut()),
            _ => unreachable!(),
        }
    }
}

pub(crate) trait SpecialiseU8<B: Buffer> {
    fn specialise_u8(&self) -> &[u8];
    fn specialise_u8_mut(&mut self) -> &mut [u8]
    where
        B: BufferMut;
}

impl<B: Buffer> SpecialiseU8<B> for B {
    fn specialise_u8(&self) -> &[u8] {
        match B::Unit::UNIT_ID {
            UNIT_ID_U8 => <B::Unit as UnitPrivate>::specialise_buffer_u8(self.buffer()),
            _ => unreachable!(),
        }
    }
    fn specialise_u8_mut(&mut self) -> &mut [u8]
    where
        B: BufferMut,
    {
        match B::Unit::UNIT_ID {
            UNIT_ID_U8 => <B::Unit as UnitPrivate>::specialise_buffer_u8_mut(self.buffer_mut()),
            _ => unreachable!(),
        }
    }
}