pub struct PulseDecodeWriter<W> { /* private fields */ }
Expand description

Provides a decoder of TAPE T-state pulse intervals.

The timing of the pulses should match those produced by ZX Spectrum’s ROM loading routines.

After invoking PulseDecodeWriter::end or PulseDecodeWriter::new PulseDecodeWriter expects a data transfer which consists of:

  • lead pulses followed by
  • two synchronization pulses followed by
  • data pulses

Provide pulse iterators to PulseDecodeWriter::write_decoded_pulses method to write interpreted data to the underlying writer.

Best used with tap utilities.

Implementations§

Resets the state of the PulseDecodeWriter to Idle, discarding any partially received byte.

The information about the number of bytes written so far is lost.

Returns true if the state is PulseDecodeState::Idle.

Returns the underlying writer.

Returns a reference to the current state.

Returns a mutable reference to the inner writer.

Examples found in repository?
src/tap/write.rs (line 63)
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
    fn drop(&mut self) {
        if self.uncommitted != 0 {
            let chunk_head = self.writer.chunk_head.checked_add(LEN_PREFIX_SIZE).unwrap();
            let _ = self.writer.mpwr.get_mut().seek(SeekFrom::Start(chunk_head));
        }
    }
}

impl<'a, W: Write + Seek> Write for TapChunkWriteTran<'a, W> {
    /// Appends data to the current chunk.
    /// 
    /// Any number of writes should be followed by [TapChunkWriteTran::commit].
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let _: u16 = (self.uncommitted as usize).checked_add(buf.len()).unwrap()
                    .try_into().map_err(|e| Error::new(ErrorKind::WriteZero, e))?;
        let written = self.writer.mpwr.get_mut().write(buf)?;
        self.checksum ^= checksum(&buf[..written]);
        self.uncommitted += written as u16;
        Ok(written)
    }

    fn flush(&mut self) -> Result<()> {
        self.writer.flush()
    }
}

impl<'a, W> TapChunkWriteTran<'a, W>
    where W: Write + Seek
{
    /// Commits a *TAP* chunk.
    ///
    /// If `with_checksum` is `true` additionally writes a checksum byte of data written so far.
    ///
    /// Returns number of *TAP* chunks written including the call to `begin`.
    pub fn commit(mut self, with_checksum: bool) -> Result<usize> {
        let mut nchunks = self.nchunks;
        let mut uncommitted = self.uncommitted;
        if with_checksum {
            if let Some(size) = uncommitted.checked_add(1) {
                uncommitted = size;
                let checksum = self.checksum;
                self.write_all(slice::from_ref(&checksum))?;
            }
            else {
                return Err(Error::new(ErrorKind::WriteZero, "chunk is larger than the maximum allowed size"))
            }
        }
        if let Some(size) = NonZeroU32::new(uncommitted.into()) {
            self.writer.commit_chunk(size)?;
            nchunks += 1;
        }
        Ok(nchunks)
    }
}

impl<W> TapChunkWriter<W>
    where W: Write + Seek
{
    /// Returns a new instance of `TapChunkWriter` with the given writer on success.
    ///
    /// The stream cursor should be positioned where the next chunk will be written.
    ///
    /// This method does not write any data, but moves the stream cursor to make room for
    /// the next block's length indicator.
    pub fn try_new(wr: W) -> Result<Self> {
        let mut mpwr = PulseDecodeWriter::new(wr);
        let chunk_start = mpwr.get_mut().seek(SeekFrom::Current(LEN_PREFIX_SIZE as i64))?;
        let chunk_head = chunk_start.checked_sub(LEN_PREFIX_SIZE).unwrap();
        Ok(TapChunkWriter { chunk_head, mpwr })
    }
    /// Flushes the underlying writer, ensuring that all intermediately buffered
    /// contents reach their destination (invokes [Write::flush]).
    pub fn flush(&mut self) -> Result<()> {
        self.mpwr.get_mut().flush()
    }
    /// Forces pending pulse decode data transfer to [end][PulseDecodeWriter::end].
    ///
    /// Returns the number of *TAP* chunks written.
    pub fn end_pulse_chunk(&mut self) -> Result<usize> {
        if let Some(size) = self.mpwr.end()? {
            self.commit_chunk(size)?;
            Ok(1)
        }
        else {
            Ok(0)
        }
    }
    /// Writes a provided header as a *TAP* chunk.
    ///
    /// Flushes internal [mic pulse writer][PulseDecodeWriter::end] before proceeding with writing the header.
    ///
    /// Returns the number of *TAP* chunks written.
    pub fn write_header(&mut self, header: &Header) -> Result<usize> {
        self.write_chunk(header.to_tap_chunk())
    }
    /// Writes provided data as a *TAP* chunk.
    ///
    /// Flushes internal [mic pulse writer][PulseDecodeWriter::end] before proceeding with writing the data.
    ///
    /// Returns the number of *TAP* chunks written.
    pub fn write_chunk<D: AsRef<[u8]>>(&mut self, chunk: D) -> Result<usize> {
        let data = chunk.as_ref();
        let size = u16::try_from(data.len()).map_err(|_|
                    Error::new(ErrorKind::InvalidData, "TAP chunk too large."))?;
        let nchunks = self.end_pulse_chunk()?;
        let wr = self.mpwr.get_mut();
        let chunk_head = wr.seek(SeekFrom::Start(self.chunk_head))?;
        debug_assert_eq!(chunk_head, self.chunk_head);
        wr.write_all(&size.to_le_bytes())?;
        wr.write_all(data)?;
        let chunk_start = wr.seek(SeekFrom::Current(LEN_PREFIX_SIZE as i64))?;
        self.chunk_head = chunk_start.checked_sub(LEN_PREFIX_SIZE).unwrap();
        Ok(nchunks + 1)
    }
    /// Creates a transaction allowing for multiple data writes to the same *TAP* chunk.
    ///
    /// Flushes internal [mic pulse writer][PulseDecodeWriter::end].
    ///
    /// Returns a transaction holder, which can be used to write data to the current chunk.
    pub fn begin(&mut self) -> Result<TapChunkWriteTran<'_, W>> {
        let nchunks = self.end_pulse_chunk()?;
        Ok(TapChunkWriteTran { checksum: 0, nchunks, uncommitted: 0, writer: self })
    }
    /// Interprets pulse intervals from the provided iterator as bytes and writes them
    /// to the underlying writer as *TAP* chunks.
    ///
    /// See [PulseDecodeWriter].
    ///
    /// Returns the number of *TAP* chunks written.
    pub fn write_pulses_as_tap_chunks<I>(&mut self, mut iter: I) -> Result<usize>
        where I: Iterator<Item=NonZeroU32>
    {
        let mut chunks = 0;
        loop {
            match self.mpwr.write_decoded_pulses(iter.by_ref())? {
                None => return Ok(chunks),
                Some(size)  => {
                    chunks += 1;
                    self.commit_chunk(size)?;
                }
            }
        }
    }

    fn commit_chunk(&mut self, size: NonZeroU32) -> Result<()> {
        let size = u16::try_from(size.get()).map_err(|_|
                    Error::new(ErrorKind::InvalidData, "TAP chunk too large."))?;
        // println!("flush chunk: {} at {}", size, self.chunk_head);
        let wr = self.mpwr.get_mut();
        let chunk_head = wr.seek(SeekFrom::Start(self.chunk_head))?;
        debug_assert_eq!(chunk_head, self.chunk_head);
        wr.write_all(&size.to_le_bytes())?;
        self.chunk_head = chunk_head.checked_add(LEN_PREFIX_SIZE + size as u64).unwrap();
        let pos_cur = self.chunk_head.checked_add(LEN_PREFIX_SIZE).unwrap();
        let pos_next = wr.seek(SeekFrom::Start(pos_cur))?;
        debug_assert_eq!(pos_next, pos_cur);
        Ok(())
    }

Returns a shared reference to the inner writer.

Returns a number of bytes written during current data transfer if a data transfer is in progress.

Allows to manually assign state. Can be used to deserialize PulseDecodeWriter.

Creates a new PulseDecodeWriter from a given Writer.

Examples found in repository?
src/tap/write.rs (line 125)
124
125
126
127
128
129
    pub fn try_new(wr: W) -> Result<Self> {
        let mut mpwr = PulseDecodeWriter::new(wr);
        let chunk_start = mpwr.get_mut().seek(SeekFrom::Current(LEN_PREFIX_SIZE as i64))?;
        let chunk_head = chunk_start.checked_sub(LEN_PREFIX_SIZE).unwrap();
        Ok(TapChunkWriter { chunk_head, mpwr })
    }

Optionally writes a partially received data byte and ensures the state of PulseDecodeWriter is Idle.

After calling this method, regardless of the return value, the state is changed to PulseDecodeState::Idle.

Returns Ok(None) if there was no data written in the current transfer.

Returns Ok(Some(size)) if data has been written, providing the number of written bytes.

In the case of std::io::Error the information about the number of bytes written is lost.

Examples found in repository?
src/tap/write.rs (line 139)
138
139
140
141
142
143
144
145
146
    pub fn end_pulse_chunk(&mut self) -> Result<usize> {
        if let Some(size) = self.mpwr.end()? {
            self.commit_chunk(size)?;
            Ok(1)
        }
        else {
            Ok(0)
        }
    }
More examples
Hide additional examples
src/tap/pulse/decoding.rs (line 197)
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
    pub fn write_decoded_pulses<I>(&mut self, iter: I) -> Result<Option<NonZeroU32>>
        where I: Iterator<Item=NonZeroU32>
    {
        let mut iter = iter.peekable();
        if iter.peek().is_none() {
            return self.end(); // empty frame
        }

        for delta in iter {
            match self.state {
                PulseDecodeState::Idle => {
                    if let LEAD_PULSE_MIN..=LEAD_PULSE_MAX = delta.get() {
                        self.state = PulseDecodeState::Lead { counter: 1 };
                    }
                }
                PulseDecodeState::Lead { counter } => match delta.get() {
                    SYNC_PULSE1_MIN..=SYNC_PULSE1_MAX if counter >= MIN_LEAD_COUNT => {
                        self.state = PulseDecodeState::Sync1;
                    }
                    LEAD_PULSE_MIN..=LEAD_PULSE_MAX => {
                        self.state = PulseDecodeState::Lead { counter: counter.saturating_add(1) };
                    }
                    _ => { self.state = PulseDecodeState::Idle },
                }
                PulseDecodeState::Sync1 => match delta.get() {
                    SYNC_PULSE2_MIN..=SYNC_PULSE2_MAX => {
                        self.state = PulseDecodeState::Sync2;
                    }                    
                    _ => { self.state = PulseDecodeState::Idle },
                }
                PulseDecodeState::Sync2 => match delta.get() {
                    delta @ DATA_PULSE_MIN..=DATA_PULSE_MAX => {
                        let current = (delta > DATA_PULSE_THRESHOLD) as u8;
                        self.state = PulseDecodeState::Data { current, pulse: 1, written: 0 }
                    }
                    _ => { self.state = PulseDecodeState::Idle },
                }
                PulseDecodeState::Data { current, pulse, written } => match delta.get() {
                    delta @ DATA_PULSE_MIN..=DATA_PULSE_MAX => {
                        let bit = (delta > DATA_PULSE_THRESHOLD) as u8;
                        let current = if pulse & 1 == 1 {
                            if (current ^ bit) & 1 == 1 {
                                return self.end();
                            }
                            if pulse == 15 {
                                self.state = PulseDecodeState::Data { current: 0, pulse: 0, written: written + 1 };
                                self.write_byte(current)?;
                                continue;
                            }
                            current
                        }
                        else {
                            (current << 1) | bit
                        };
                        self.state = PulseDecodeState::Data { current, pulse: pulse + 1, written }
                    }
                    _ => return self.end()
                }
            }
        }
        Ok(None)
    }

Interprets pulse intervals from the provided pulse iterator as data bytes, writing them to the underlying writer.

The pulse iterator is expected to provide only a fragment of pulses needed for the complete transfer such as an iterator returned from MicOut::mic_out_pulse_iter. Providing an empty iterator is equivalent to calling PulseDecodeWriter::end thus ending the current transfer in progress if there is any.

Returns Ok(None) if there was no data or more pulses are being expected.

Returns Ok(Some(size)) if data block has been written, providing the number of written bytes. In this instance, there can still be some pulses left in the iterator, e.g. for the next incoming transfer.

In the case of std::io::Error the information about the number of bytes written is lost.

Examples found in repository?
src/tap/write.rs (line 194)
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    pub fn write_pulses_as_tap_chunks<I>(&mut self, mut iter: I) -> Result<usize>
        where I: Iterator<Item=NonZeroU32>
    {
        let mut chunks = 0;
        loop {
            match self.mpwr.write_decoded_pulses(iter.by_ref())? {
                None => return Ok(chunks),
                Some(size)  => {
                    chunks += 1;
                    self.commit_chunk(size)?;
                }
            }
        }
    }

Trait Implementations§

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Converts self into T using Into<T>. Read more
Causes self to use its Binary implementation when Debug-formatted.
Causes self to use its Display implementation when Debug-formatted. Read more
Causes self to use its LowerExp implementation when Debug-formatted. Read more
Causes self to use its LowerHex implementation when Debug-formatted. Read more
Causes self to use its Octal implementation when Debug-formatted.
Causes self to use its Pointer implementation when Debug-formatted. Read more
Causes self to use its UpperExp implementation when Debug-formatted. Read more
Causes self to use its UpperHex implementation when Debug-formatted. Read more
Formats each item in a sequence. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Convert to S a sample type from self.
Pipes by value. This is generally the method you want to use. Read more
Borrows self and passes that borrow into the pipe function. Read more
Mutably borrows self and passes that borrow into the pipe function. Read more
Borrows self, then passes self.borrow() into the pipe function. Read more
Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Borrows self, then passes self.as_ref() into the pipe function.
Mutably borrows self, then passes self.as_mut() into the pipe function. Read more
Borrows self, then passes self.deref() into the pipe function.
Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more
Immutable access to a value. Read more
Mutable access to a value. Read more
Immutable access to the Borrow<B> of a value. Read more
Mutable access to the BorrowMut<B> of a value. Read more
Immutable access to the AsRef<R> view of a value. Read more
Mutable access to the AsMut<R> view of a value. Read more
Immutable access to the Deref::Target of a value. Read more
Mutable access to the Deref::Target of a value. Read more
Calls .tap() only in debug builds, and is erased in release builds.
Calls .tap_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more
Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_ref() only in debug builds, and is erased in release builds. Read more
Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more
Calls .tap_deref() only in debug builds, and is erased in release builds. Read more
Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more
Attempts to convert self into T using TryInto<T>. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.