Struct spectrusty_formats::tap::pulse::PulseDecodeWriter
source · 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§
source§impl<W> PulseDecodeWriter<W>
impl<W> PulseDecodeWriter<W>
sourcepub fn reset(&mut self)
pub fn reset(&mut self)
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.
sourcepub fn is_idle(&self) -> bool
pub fn is_idle(&self) -> bool
Returns true
if the state is PulseDecodeState::Idle.
sourcepub fn into_inner(self) -> W
pub fn into_inner(self) -> W
Returns the underlying writer.
sourcepub fn state(&self) -> PulseDecodeState
pub fn state(&self) -> PulseDecodeState
Returns a reference to the current state.
sourcepub fn get_mut(&mut self) -> &mut W
pub fn get_mut(&mut self) -> &mut W
Returns a mutable reference to the inner writer.
Examples found in repository?
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(())
}
sourcepub fn data_size(&self) -> Option<NonZeroU32>
pub fn data_size(&self) -> Option<NonZeroU32>
Returns a number of bytes written during current data transfer if a data transfer is in progress.
sourcepub fn with_state(self, state: PulseDecodeState) -> Self
pub fn with_state(self, state: PulseDecodeState) -> Self
Allows to manually assign state
.
Can be used to deserialize PulseDecodeWriter.
source§impl<W: Write> PulseDecodeWriter<W>
impl<W: Write> PulseDecodeWriter<W>
sourcepub fn end(&mut self) -> Result<Option<NonZeroU32>>
pub fn end(&mut self) -> Result<Option<NonZeroU32>>
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?
More examples
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)
}
sourcepub fn write_decoded_pulses<I>(&mut self, iter: I) -> Result<Option<NonZeroU32>>where
I: Iterator<Item = NonZeroU32>,
pub fn write_decoded_pulses<I>(&mut self, iter: I) -> Result<Option<NonZeroU32>>where
I: Iterator<Item = NonZeroU32>,
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?
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§
Auto Trait Implementations§
impl<W> RefUnwindSafe for PulseDecodeWriter<W>where
W: RefUnwindSafe,
impl<W> Send for PulseDecodeWriter<W>where
W: Send,
impl<W> Sync for PulseDecodeWriter<W>where
W: Sync,
impl<W> Unpin for PulseDecodeWriter<W>where
W: Unpin,
impl<W> UnwindSafe for PulseDecodeWriter<W>where
W: UnwindSafe,
Blanket Implementations§
§impl<T> Conv for T
impl<T> Conv for T
§impl<T> FmtForward for T
impl<T> FmtForward for T
§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
§fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
fn fmt_list(self) -> FmtList<Self>where
&'a Self: for<'a> IntoIterator,
source§impl<S, T> IntoSample<S> for Twhere
S: FromSample<T>,
impl<S, T> IntoSample<S> for Twhere
S: FromSample<T>,
source§fn into_sample(self) -> S
fn into_sample(self) -> S
S
a sample type from self
.§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read more§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> Rwhere
Self: Borrow<B>,
B: 'a + ?Sized,
R: 'a,
§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R
) -> Rwhere
Self: BorrowMut<B>,
B: 'a + ?Sized,
R: 'a,
§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> Rwhere
Self: AsRef<U>,
U: 'a + ?Sized,
R: 'a,
self
, then passes self.as_ref()
into the pipe function.§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> Rwhere
Self: AsMut<U>,
U: 'a + ?Sized,
R: 'a,
§impl<T> Tap for T
impl<T> Tap for T
§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
Borrow<B>
of a value. Read more§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
BorrowMut<B>
of a value. Read more§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
AsRef<R>
view of a value. Read more§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
AsMut<R>
view of a value. Read more§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Selfwhere
Self: Deref<Target = T>,
T: ?Sized,
Deref::Target
of a value. Read more§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Selfwhere
Self: DerefMut<Target = T> + Deref,
T: ?Sized,
Deref::Target
of a value. Read more§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds. Read more§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Selfwhere
Self: Borrow<B>,
B: ?Sized,
.tap_borrow()
only in debug builds, and is erased in release
builds. Read more§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Selfwhere
Self: BorrowMut<B>,
B: ?Sized,
.tap_borrow_mut()
only in debug builds, and is erased in release
builds. Read more§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Selfwhere
Self: AsRef<R>,
R: ?Sized,
.tap_ref()
only in debug builds, and is erased in release
builds. Read more§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Selfwhere
Self: AsMut<R>,
R: ?Sized,
.tap_ref_mut()
only in debug builds, and is erased in release
builds. Read more