midi_toolkit/sequence/event/
delta.rs1use std::{
2 io::Write,
3 ops::{Deref, DerefMut},
4};
5
6use crate::{
7 events::{
8 encode_var_length_value, BatchTempo, CastEventDelta, MIDIDelta, MIDIEvent, MIDIEventEnum,
9 SerializeEvent, SerializeEventWithDelta,
10 },
11 io::MIDIWriteError,
12 num::{MIDINum, MIDINumInto},
13};
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct Delta<D: MIDINum, E> {
17 pub delta: D,
18 pub event: E,
19}
20
21impl<D: MIDINum, E> MIDIDelta<D> for Delta<D, E> {
22 #[inline(always)]
23 fn delta(&self) -> D {
24 self.delta
25 }
26
27 #[inline(always)]
28 fn delta_mut(&mut self) -> &mut D {
29 &mut self.delta
30 }
31}
32
33impl<D: MIDINum + MIDINumInto<ND>, ND: MIDINum, E> CastEventDelta<ND> for Delta<D, E> {
34 type Output = Delta<ND, E>;
35
36 #[inline(always)]
37 fn cast_delta(self) -> Self::Output {
38 Delta {
39 delta: self.delta.midi_num_into(),
40 event: self.event,
41 }
42 }
43}
44
45impl<D: MIDINum, E> Delta<D, E> {
46 #[inline(always)]
47 pub fn new(delta: D, event: E) -> Self {
48 Self { delta, event }
49 }
50}
51
52impl<D: MIDINum, E> Deref for Delta<D, E> {
53 type Target = E;
54
55 fn deref(&self) -> &Self::Target {
56 &self.event
57 }
58}
59
60impl<D: MIDINum, E> DerefMut for Delta<D, E> {
61 fn deref_mut(&mut self) -> &mut Self::Target {
62 &mut self.event
63 }
64}
65
66impl<D: MIDINum, E: MIDIEventEnum> MIDIEvent for Delta<D, E> {
67 fn key(&self) -> Option<u8> {
68 self.event.key()
69 }
70
71 fn key_mut(&mut self) -> Option<&mut u8> {
72 self.event.key_mut()
73 }
74
75 fn channel(&self) -> Option<u8> {
76 self.event.channel()
77 }
78
79 fn channel_mut(&mut self) -> Option<&mut u8> {
80 self.event.channel_mut()
81 }
82
83 fn as_u32(&self) -> Option<u32> {
84 self.event.as_u32()
85 }
86}
87
88impl<D: MIDINum, E: MIDIEventEnum> MIDIEventEnum for Delta<D, E> {
89 #[inline(always)]
90 fn as_event(&self) -> &crate::events::Event {
91 self.event.as_event()
92 }
93
94 #[inline(always)]
95 fn as_event_mut(&mut self) -> &mut crate::events::Event {
96 self.event.as_event_mut()
97 }
98}
99
100impl<D: MIDINum, E: BatchTempo> BatchTempo for Delta<D, E> {
101 fn inner_tempo(&self) -> Option<u32> {
102 self.event.inner_tempo()
103 }
104
105 fn without_tempo(self) -> Option<Self> {
106 let delta = self.delta;
107 self.event
108 .without_tempo()
109 .map(|event| Self::new(delta, event))
110 }
111}
112
113impl<D: MIDINum, E: SerializeEvent> SerializeEvent for Delta<D, E> {
114 fn serialize_event<T: Write>(&self, buf: &mut T) -> Result<usize, MIDIWriteError> {
115 self.event.serialize_event(buf)
116 }
117}
118
119impl<E: SerializeEvent> SerializeEventWithDelta for Delta<u64, E> {
120 fn serialize_delta<T: Write>(&self, buf: &mut T) -> Result<usize, MIDIWriteError> {
121 let vec = encode_var_length_value(self.delta);
122 buf.write_all(&vec)?;
123 Ok(vec.len())
124 }
125}