pub struct ReadEncPulseIter<R> { /* private fields */ }
Expand description

Encodes data read from an underlying reader as TAPE T-state pulse intervals via an Iterator interface.

The timing of the pulses matches those expected by ZX Spectrum’s ROM loading routines.

After invoking ReadEncPulseIter::reset or ReadEncPulseIter::new the first byte is read and checked to determine the duration of the LEAD PULSE signal. If it’s less than 128 the number of generated lead pulses is LEAD_PULSES_HEAD. Otherwise, it’s LEAD_PULSES_DATA.

After the lead pulses, two synchronization pulses are being emitted following by data pulses for each byte read including the initial flag byte.

This iterator may be used to feed pulses to the EAR IN buffer of the ZX Spectrum emulator (e.g. via EarIn::feed_ear_in) or to produce sound with a help of Bandwidth-Limited Pulse Buffer.

Best used with tap utilities.

Implementations§

Returns a reference to the current state.

Returns a flag byte.

Returns an error from the underlying reader if there was one.

Examples found in repository?
src/tap/read.rs (line 470)
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
    fn next(&mut self) -> Option<Self::Item> {
        match self.ep_iter.next() {
            pulse @ Some(_) => pulse,
            None if self.auto_next => {
                if self.ep_iter.err().is_some() ||
                        self.ep_iter.get_mut().next_chunk().is_err() {
                    return None;
                }
                self.ep_iter.reset();
                if self.ep_iter.is_done() {
                    None
                }
                else {
                    Some(PAUSE_PULSE_LENGTH)
                }
            }
            None => None
        }
    }

Returns true if there are no more pulses to emit or there was an error while bytes were read.

Examples found in repository?
src/tap/read.rs (line 414)
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
    pub fn is_done(&self) -> bool {
        self.ep_iter.is_done()
    }
}

impl<R: Read + Seek> TapChunkRead for TapChunkPulseIter<R> {
    fn chunk_no(&self) -> u32 {
        self.ep_iter.get_ref().chunk_no()
    }

    fn chunk_limit(&self) -> u16 {
        self.ep_iter.get_ref().chunk_limit()
    }

    /// Invokes underlying [TapChunkReader::rewind] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::rewind].
    fn rewind(&mut self) {
        self.ep_iter.get_mut().rewind();
        self.ep_iter.reset();
    }

    /// Invokes underlying [TapChunkReader::next_chunk] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::next_chunk].
    fn next_chunk(&mut self) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().next_chunk()?;
        self.ep_iter.reset();
        Ok(res)
    }

    /// Invokes underlying [TapChunkReader::skip_chunks] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::skip_chunks].
    fn skip_chunks(&mut self, skip: u32) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().skip_chunks(skip)?;
        self.ep_iter.reset();
        Ok(res)        
    }
}

impl<R> AsRef<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_ref(&self) -> &TapChunkReader<R> {
        self.ep_iter.get_ref()
    }
}

impl<R> AsMut<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_mut(&mut self) -> &mut TapChunkReader<R> {
        self.ep_iter.get_mut()
    }
}

impl<R: Read + Seek> Iterator for TapChunkPulseIter<R> {
    type Item = NonZeroU32;

    fn next(&mut self) -> Option<Self::Item> {
        match self.ep_iter.next() {
            pulse @ Some(_) => pulse,
            None if self.auto_next => {
                if self.ep_iter.err().is_some() ||
                        self.ep_iter.get_mut().next_chunk().is_err() {
                    return None;
                }
                self.ep_iter.reset();
                if self.ep_iter.is_done() {
                    None
                }
                else {
                    Some(PAUSE_PULSE_LENGTH)
                }
            }
            None => None
        }
    }

Returns a mutable reference to the inner reader.

Examples found in repository?
src/tap/read.rs (line 430)
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
    fn rewind(&mut self) {
        self.ep_iter.get_mut().rewind();
        self.ep_iter.reset();
    }

    /// Invokes underlying [TapChunkReader::next_chunk] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::next_chunk].
    fn next_chunk(&mut self) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().next_chunk()?;
        self.ep_iter.reset();
        Ok(res)
    }

    /// Invokes underlying [TapChunkReader::skip_chunks] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::skip_chunks].
    fn skip_chunks(&mut self, skip: u32) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().skip_chunks(skip)?;
        self.ep_iter.reset();
        Ok(res)        
    }
}

impl<R> AsRef<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_ref(&self) -> &TapChunkReader<R> {
        self.ep_iter.get_ref()
    }
}

impl<R> AsMut<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_mut(&mut self) -> &mut TapChunkReader<R> {
        self.ep_iter.get_mut()
    }
}

impl<R: Read + Seek> Iterator for TapChunkPulseIter<R> {
    type Item = NonZeroU32;

    fn next(&mut self) -> Option<Self::Item> {
        match self.ep_iter.next() {
            pulse @ Some(_) => pulse,
            None if self.auto_next => {
                if self.ep_iter.err().is_some() ||
                        self.ep_iter.get_mut().next_chunk().is_err() {
                    return None;
                }
                self.ep_iter.reset();
                if self.ep_iter.is_done() {
                    None
                }
                else {
                    Some(PAUSE_PULSE_LENGTH)
                }
            }
            None => None
        }
    }

Returns a shared reference to the inner reader.

Examples found in repository?
src/tap/read.rs (line 420)
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
    fn chunk_no(&self) -> u32 {
        self.ep_iter.get_ref().chunk_no()
    }

    fn chunk_limit(&self) -> u16 {
        self.ep_iter.get_ref().chunk_limit()
    }

    /// Invokes underlying [TapChunkReader::rewind] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::rewind].
    fn rewind(&mut self) {
        self.ep_iter.get_mut().rewind();
        self.ep_iter.reset();
    }

    /// Invokes underlying [TapChunkReader::next_chunk] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::next_chunk].
    fn next_chunk(&mut self) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().next_chunk()?;
        self.ep_iter.reset();
        Ok(res)
    }

    /// Invokes underlying [TapChunkReader::skip_chunks] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::skip_chunks].
    fn skip_chunks(&mut self, skip: u32) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().skip_chunks(skip)?;
        self.ep_iter.reset();
        Ok(res)        
    }
}

impl<R> AsRef<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_ref(&self) -> &TapChunkReader<R> {
        self.ep_iter.get_ref()
    }

Returns the underlying reader.

Allows to manually assign a state and a flag. Can be used to deserialize ReadEncPulseIter.

Creates a new ReadEncPulseIter from a given Reader.

Examples found in repository?
src/tap/read.rs (line 380)
379
380
381
    fn from(rd: TapChunkReader<R>) -> Self {
        TapChunkPulseIter::from(ReadEncPulseIter::new(rd))
    }
More examples
Hide additional examples
src/tap.rs (line 258)
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
pub fn read_tap_pulse_iter<T, R>(rd: T) -> TapChunkPulseIter<R>
    where R: Read + Seek, T: Into<TapChunkReader<R>>
{
    let ep_iter = ReadEncPulseIter::new(rd.into());
    TapChunkPulseIter::from(ep_iter)
}

/// Creates an instance of [TapChunkWriter] from the given writer on success.
pub fn write_tap<W>(wr: W) -> Result<TapChunkWriter<W>>
    where W: Write + Seek
{
    TapChunkWriter::try_new(wr)
}

/// The *TAP* block type of the next chunk following a [Header].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum BlockType {
    Program     = 0,
    NumberArray = 1,
    CharArray   = 2,
    Code        = 3
}

/// Represents the *TAP* header block.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
    /// Length of the data block excluding a block flag and checksum byte.
    pub length: u16,
    /// The type of the file this header represents.
    pub block_type: BlockType,
    /// A name of the file.
    pub name: [u8;10],
    /// Additional header data.
    pub par1: [u8;2],
    /// Additional header data.
    pub par2: [u8;2]
}

/// The *TAP* chunk meta-data.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TapChunkInfo {
    /// Represents a proper header block.
    Head(Header),
    /// Represents a data block.
    Data {
        /// The length of data excluding a block flag and checksum byte.
        length: u16,
        /// Checksum of the data, should be 0. Otherwise this block won't load properly.
        checksum: u8
    },
    /// Represents an unkown block.
    Unknown {
        /// The size of the whole block including the block flag.
        size: u16,
        /// The first byte of the block (a block flag).
        flag: u8
    },
    /// Represents an empty block.
    Empty
}

/// The *TAP* chunk.
///
/// Provides helper methods to interpret the underlying bytes as one of the *TAP* blocks.
/// This should usually be a [Header] or a data block.
///
/// Anything that implements `AsRef<[u8]>` can be used as `T` (e.g. `&[u8]` or `Vec<u8>`).
///
/// Instances of [TapChunk] can be created using [From]/[Into] interface or via [TapChunkIter].
#[derive(Clone, Copy, Debug)]
pub struct TapChunk<T> {
    data: T
}

/// Implements an iterator of [TapChunk] objects over the array of bytes.
#[derive(Clone, Debug)]
pub struct TapChunkIter<'a> {
    position: usize,
    data: &'a[u8]
}

#[inline(always)]
pub(super) fn array_name(c: u8) -> char {
    (c & 0b0001_1111 | 0b0100_0000).into()
}

#[inline(always)]
pub(super) fn char_array_var(n: char) -> u8 {
    if !n.is_ascii_alphabetic() {
        panic!("Only ascii alphabetic characters are allowed!");
    }
    let c = n as u8;
    c & 0b0001_1111 | 0b1100_0000
}

#[inline(always)]
pub(super) fn number_array_var(n: char) -> u8 {
    if !n.is_ascii_alphabetic() {
        panic!("Only ascii alphabetic characters are allowed!");
    }
    let c = n as u8;
    c & 0b0001_1111 | 0b1000_0000
}

impl fmt::Display for BlockType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", 
            match self {
                BlockType::Program => "Program",
                BlockType::NumberArray => "Number array",
                BlockType::CharArray => "Character array",
                BlockType::Code => "Bytes",
            })
    }
}

impl fmt::Display for TapChunkInfo {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TapChunkInfo::Head(header) => {
                write!(f, "{}: \"{}\"", header.block_type, header.name_str().trim_end())?;
                match header.block_type {
                    BlockType::Program => {
                        if header.start() < 10000 {
                            write!(f, " LINE {}", header.start())?;
                        }
                        if header.vars() != header.length {
                            write!(f, " PROG {} VARS {}",
                                header.vars(), header.length - header.vars())?;
                        }
                        Ok(())
                    }
                    BlockType::NumberArray => {
                        write!(f, " DATA {}()", header.array_name())
                    }
                    BlockType::CharArray => {
                        write!(f, " DATA {}$()", header.array_name())
                    }
                    BlockType::Code => {
                        write!(f, " CODE {},{}", header.start(), header.length)
                    }
                }
            }
            TapChunkInfo::Data {length, ..} => {
                write!(f, "(data {})", length)
            }
            TapChunkInfo::Unknown {size, ..} => {
                write!(f, "(unkown {})", size)
            }
            TapChunkInfo::Empty => {
                write!(f, "(empty)")
            }            
        }
    }
}

impl<T> fmt::Display for TapChunk<T> where T: AsRef<[u8]> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.info() {
            Ok(info) => info.fmt(f),
            Err(e) => write!(f, "{}", e)
        }
    }
}

impl Default for BlockType {
    fn default() -> Self {
        BlockType::Code
    }
}

impl From<BlockType> for u8 {
    #[inline]
    fn from(block_type: BlockType) -> u8 {
        block_type as u8
    }
}

impl TryFrom<u8> for BlockType {
    type Error = Error;

    #[inline]
    fn try_from(block_type: u8) -> Result<Self> {
        match block_type {
            0 => Ok(BlockType::Program),
            1 => Ok(BlockType::NumberArray),
            2 => Ok(BlockType::CharArray),
            3 => Ok(BlockType::Code),
            _ => Err(Error::new(ErrorKind::InvalidData, "Unknown TAP type."))
        }
    }    
}

impl Default for Header {
    fn default() -> Self {
        let length = 0;
        let block_type = BlockType::Code;
        let name = [b' ';10];
        let par1 = 0u16.to_le_bytes();
        let par2 = 0x8000u16.to_le_bytes();
        Header { length, block_type, name, par1, par2 }
    }
}

impl Header {
    /// Creates a `Code` header.
    pub fn new_code(length: u16) -> Self {
        let block_type = BlockType::Code;
        let name = [b' ';10];
        let par1 = 0u16.to_le_bytes();
        let par2 = 0x8000u16.to_le_bytes();
        Header { length, block_type, name, par1, par2 }
    }
    /// Creates a `Program` header.
    pub fn new_program(length: u16) -> Self {
        let block_type = BlockType::Program;
        let name = [b' ';10];
        let par1 = 0x8000u16.to_le_bytes();
        let par2 = length.to_le_bytes();
        Header { length, block_type, name, par1, par2 }
    }
    /// Creates a `NumberArray` header.
    pub fn new_number_array(length: u16) -> Self {
        let block_type = BlockType::NumberArray;
        let name = [b' ';10];
        let par1 = [0, number_array_var('A')];
        let par2 = 0x8000u16.to_le_bytes();
        Header { length, block_type, name, par1, par2 }
    }
    /// Creates a `CharArray` header.
    pub fn new_char_array(length: u16) -> Self {
        let block_type = BlockType::CharArray;
        let name = [b' ';10];
        let par1 = [0, char_array_var('A')];
        let par2 = 0x8000u16.to_le_bytes();
        Header { length, block_type, name, par1, par2 }
    }
    /// Changes `name`, builder style.
    pub fn with_name<S: AsRef<[u8]>>(mut self, name: S) -> Self {
        let name = name.as_ref();
        let bname = &name[0..name.len().max(10)];
        self.name[0..bname.len()].copy_from_slice(bname);
        for p in self.name[bname.len()..].iter_mut() {
            *p = b' ';
        }
        self
    }
    /// Changes `start`, builder style.
    ///
    /// # Panics
    /// Panics if self is not a `Code` nor a `Program` header.
    pub fn with_start(mut self, start: u16) -> Self {
        if let BlockType::Code|BlockType::Program = self.block_type {
            self.par1 = start.to_le_bytes();            
            self
        }
        else {
            panic!("Can't set start for an array header");
        }
    }
    /// Changes `vars`, builder style.
    ///
    /// # Panics
    /// Panics if self is not a `Program` header or if given `vars` exceeds `length`.
    pub fn with_vars(mut self, vars: u16) -> Self {
        if let BlockType::Program = self.block_type {
            if vars <= self.length {
                self.par2 = vars.to_le_bytes();            
                self
            }
            else {
                panic!("Can't set vars larger than length");
            }
        }
        else {
            panic!("Can't set vars: not a program header");
        }
    }
    /// Changes array name, builder style.
    ///
    /// # Panics
    /// Panics if self is not an array header or if given character is not ASCII alphabetic.
    pub fn with_array_name(mut self, n: char) -> Self {
        self.par1[1] = match self.block_type {
            BlockType::CharArray => char_array_var(n),
            BlockType::NumberArray => number_array_var(n),
            _ => panic!("Can't set array name: not an array header")
        };
        self
    }
    /// Returns a header name as a string.
    #[inline]
    pub fn name_str(&self) -> Cow<'_, str> {
        String::from_utf8_lossy(&self.name)
    }

    /// Returns a starting address.
    /// Depending of the type of this header it may be either a starting address of [BlockType::Code]
    /// or starting line of [BlockType::Program].
    #[inline]
    pub fn start(&self) -> u16 {
        u16::from_le_bytes(self.par1)
    }

    /// Returns an offset to `VARS`. Only valid for headers with [BlockType::Program].
    #[inline]
    pub fn vars(&self) -> u16 {
        u16::from_le_bytes(self.par2)
    }

    /// Returns an array variable name.
    ///
    /// Only valid for headers with [BlockType::CharArray] or [BlockType::NumberArray].
    #[inline]
    pub fn array_name(&self) -> char {
        array_name(self.par1[1])
    }

    /// Returns a tap chunk created from self.
    pub fn to_tap_chunk(&self) -> TapChunk<[u8;HEADER_SIZE]> {
        let mut buffer = <[u8;HEADER_SIZE]>::default();
        buffer[0] = HEAD_BLOCK_FLAG;
        buffer[1] = self.block_type.into();
        buffer[2..12].copy_from_slice(&self.name);
        buffer[12..14].copy_from_slice(&self.length.to_le_bytes());
        buffer[14..16].copy_from_slice(&self.par1);
        buffer[16..18].copy_from_slice(&self.par2);
        buffer[18] = checksum(buffer[0..18].iter());
        TapChunk::from(buffer)
    }
}

impl TryFrom<&'_[u8]> for Header {
    type Error = Error;
    fn try_from(header: &[u8]) -> Result<Self> {
        if header.len() != HEADER_SIZE - 2 {
            return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP header: invalid length"));
        }
        let block_type = BlockType::try_from(header[0])?;
        let mut name: [u8; 10] = Default::default();
        name.copy_from_slice(&header[1..11]);
        let mut length: [u8; 2] = Default::default();
        length.copy_from_slice(&header[11..13]);
        let length = u16::from_le_bytes(length);
        let mut par1: [u8; 2] = Default::default();
        par1.copy_from_slice(&header[13..15]);
        let mut par2: [u8; 2] = Default::default();
        par2.copy_from_slice(&header[15..17]);
        Ok(Header { length, block_type, name, par1, par2 })
    }
}

impl TapChunkInfo {
    /// Returns size in bytes of this chunk.
    pub fn tap_chunk_size(&self) -> usize {
        match self {
            TapChunkInfo::Head(_) => HEADER_SIZE,
            &TapChunkInfo::Data {length, ..} => length as usize + 2,
            &TapChunkInfo::Unknown {size, ..} => size as usize,
            TapChunkInfo::Empty => 0
        }
    }
}

impl TryFrom<&'_[u8]> for TapChunkInfo {
    type Error = Error;

    #[inline]
    fn try_from(bytes: &[u8]) -> Result<Self> {
        let size = match bytes.len() {
            0 => {
                return Ok(TapChunkInfo::Empty);
            }
            1 => {
                return Ok(TapChunkInfo::Unknown { size: 1, flag: bytes[0] })
            }
            size if size > u16::max_value().into() => {
                return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: too large"));
            }
            size => size
        };
        match bytes.first() {
            Some(&HEAD_BLOCK_FLAG) if size == HEADER_SIZE && checksum(bytes) == 0 => {
                Header::try_from(&bytes[1..HEADER_SIZE-1])
                .map(TapChunkInfo::Head)
                .or(Ok(TapChunkInfo::Unknown { size: size as u16, flag: HEAD_BLOCK_FLAG }))
            }
            Some(&DATA_BLOCK_FLAG) => {
                let checksum = checksum(bytes);
                Ok(TapChunkInfo::Data{ length: size as u16 - 2, checksum })
            }
            Some(&flag) => {
                Ok(TapChunkInfo::Unknown { size: size as u16, flag })
            }
            _ => unreachable!()
        }
    }    
}

impl<T> From<T> for TapChunk<T> where T: AsRef<[u8]> {
    fn from(data: T) -> Self {
        TapChunk { data }
    }
}

impl<T> AsRef<[u8]> for TapChunk<T> where T: AsRef<[u8]> {
    #[inline(always)]
    fn as_ref(&self) -> &[u8] {
        self.data.as_ref()
    }
}

impl<T> AsMut<[u8]> for TapChunk<T> where T: AsMut<[u8]> {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut [u8] {
        self.data.as_mut()
    }
}

impl<T> TapChunk<T> {
    /// Returns the underlying bytes container.
    pub fn into_inner(self) -> T {
        self.data
    }
}

impl<T> TapChunk<T> where T: AsRef<[u8]> {
    /// Attempts to create an instance of [TapChunkInfo] from underlying data.
    pub fn info(&self) -> Result<TapChunkInfo> {
        TapChunkInfo::try_from(self.data.as_ref())
    }

    /// Calculates bit-xor checksum of underlying data.
    pub fn checksum(&self) -> u8 {
        checksum(self.data.as_ref())
    }

    /// Checks if this *TAP* chunk is a [Header] block.
    pub fn is_head(&self) -> bool {
        matches!(self.data.as_ref().get(0..2),
                 Some(&[HEAD_BLOCK_FLAG, t]) if t & 3 == t)
    }

    /// Checks if this *TAP* chunk is a data block.
    pub fn is_data(&self) -> bool {
        matches!(self.data.as_ref().first(), Some(&DATA_BLOCK_FLAG))
    }

    /// Checks if this *TAP* chunk is a valid data or [Header] block.
    pub fn is_valid(&self) -> bool {
        self.validate().is_ok()
    }

    /// Validates if this *TAP* chunk is a valid data or [Header] block returning `self` on success.
    pub fn validated(self) -> Result<Self> {
        self.validate().map(|_| self)
    }

    /// Validates if this *TAP* chunk is a valid data or [Header] block.
    pub fn validate(&self) -> Result<()> {
        let data = self.data.as_ref();
        match data.get(0..2) {
            Some(&[HEAD_BLOCK_FLAG, t]) if t & 3 == t => {
                if data.len() != HEADER_SIZE {
                    return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP header: invalid length"));
                }
            }
            Some(&[DATA_BLOCK_FLAG, _]) => {}
            _ => return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: Invalid block head byte"))
        }
        if checksum(data) != 0 {
            return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: Invalid checksum"))
        }
        Ok(())
    }

    /// Returns a name if the block is a [Header]
    pub fn name(&self) -> Option<Cow<'_,str>> {
        if self.is_head() {
            Some(String::from_utf8_lossy(&self.data.as_ref()[2..12]))
        }
        else {
            None
        }
    }

    /// Returns a reference to the underlying data block only if the underlying bytes represents the data block.
    ///
    /// The provided reference does not include block flag and checksum bytes.
    pub fn data(&self) -> Option<&[u8]> {
        let data = self.data.as_ref();
        if self.is_data() {
            Some(&data[1..data.len()-1])
        }
        else {
            None
        }
    }

    /// Returns a length in bytes of the next chunk's data block only if the underlying bytes represents
    /// the [Header] block.
    ///
    /// The provided length does not include block flag and checksum bytes.
    pub fn data_block_len(&self) -> Option<u16> {
        if self.is_head() {
            if let [lo, hi] = self.data.as_ref()[12..14] {
                return Some(u16::from_le_bytes([lo, hi]))
            }
        }
        None
    }
    /// Returns a starting address only if the underlying bytes represents the [Header] block.
    ///
    /// Depending of the type of this header it may be either a starting address of [BlockType::Code]
    /// or starting line of [BlockType::Program].
    pub fn start(&self) -> Option<u16> {
        if self.is_head() {
            if let [lo, hi] = self.data.as_ref()[14..16] {
                return Some(u16::from_le_bytes([lo, hi]))
            }
        }
        None
    }

    /// Returns an offset to `VARS` only if the underlying bytes represents the [Header] block.
    ///
    /// Only valid for headers with [BlockType::Program].
    pub fn vars(&self) -> Option<u16> {
        if self.is_head() {
            if let [lo, hi] = self.data.as_ref()[16..18] {
                return Some(u16::from_le_bytes([lo, hi]))
            }
        }
        None
    }

    /// Returns an array variable name only if the underlying bytes represents the [Header] block.
    ///
    /// Only valid for headers with [BlockType::CharArray] or [BlockType::NumberArray].
    pub fn array_name(&self) -> Option<char> {
        if self.is_head() {
            return Some(array_name(self.data.as_ref()[15]))
        }
        None
    }

    /// Returns a next chunk's data type only if the underlying bytes represents the [Header] block.
    pub fn block_type(&self) -> Option<BlockType> {
        if self.is_head() {
            return BlockType::try_from(self.data.as_ref()[1]).ok()
        }
        None
    }

    /// Returns a pulse interval iterator referencing this *TAP* chunk.
    pub fn as_pulse_iter(&self) -> ReadEncPulseIter<Cursor<&[u8]>> {
        ReadEncPulseIter::new(Cursor::new(self.as_ref()))
    }

    /// Converts this *TAP* chunk into a pulse interval iterator owning this chunk's data.
    pub fn into_pulse_iter(self) -> ReadEncPulseIter<Cursor<T>> {
        ReadEncPulseIter::new(Cursor::new(self.into_inner()))
    }

Resets the state of the iterator.

The next byte read from the inner reader is interpreted as a flag byte to determine the number of lead pulses. In this instance the state becomes PulseIterState::Lead.

If there are no more bytes to be read the state becomes PulseIterState::Done.

In case of an error while reading from the underlying reader the state becomes PulseIterState::Error.

Examples found in repository?
src/tap/read.rs (line 431)
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
    fn rewind(&mut self) {
        self.ep_iter.get_mut().rewind();
        self.ep_iter.reset();
    }

    /// Invokes underlying [TapChunkReader::next_chunk] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::next_chunk].
    fn next_chunk(&mut self) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().next_chunk()?;
        self.ep_iter.reset();
        Ok(res)
    }

    /// Invokes underlying [TapChunkReader::skip_chunks] and [resets][ReadEncPulseIter::reset] the internal
    /// pulse iterator. Returns the result from [TapChunkReader::skip_chunks].
    fn skip_chunks(&mut self, skip: u32) -> Result<Option<u16>> {
        let res = self.ep_iter.get_mut().skip_chunks(skip)?;
        self.ep_iter.reset();
        Ok(res)        
    }
}

impl<R> AsRef<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_ref(&self) -> &TapChunkReader<R> {
        self.ep_iter.get_ref()
    }
}

impl<R> AsMut<TapChunkReader<R>> for TapChunkPulseIter<R> {
    fn as_mut(&mut self) -> &mut TapChunkReader<R> {
        self.ep_iter.get_mut()
    }
}

impl<R: Read + Seek> Iterator for TapChunkPulseIter<R> {
    type Item = NonZeroU32;

    fn next(&mut self) -> Option<Self::Item> {
        match self.ep_iter.next() {
            pulse @ Some(_) => pulse,
            None if self.auto_next => {
                if self.ep_iter.err().is_some() ||
                        self.ep_iter.get_mut().next_chunk().is_err() {
                    return None;
                }
                self.ep_iter.reset();
                if self.ep_iter.is_done() {
                    None
                }
                else {
                    Some(PAUSE_PULSE_LENGTH)
                }
            }
            None => None
        }
    }
More examples
Hide additional examples
src/tap/pulse/encoding.rs (line 135)
133
134
135
136
137
    pub fn new(rd: R) -> Self {
        let mut epi = ReadEncPulseIter { rd, state: PulseIterState::Done, flag: 0 };
        epi.reset();
        epi
    }

Attempts to set the state of the iterator as PulseIterState::Data from the next byte.

The next byte read from the inner reader is interpreted as a data byte. In this instance, the state becomes PulseIterState::Data.

If there are no more bytes to be read the state becomes PulseIterState::Done.

In case of an error while reading from the underlying reader the state becomes PulseIterState::Error.

Trait Implementations§

Formats the value using the given formatter. Read more
Converts to this type from the input type.
The type of the elements being iterated over.
Advances the iterator and returns the next value. Read more
🔬This is a nightly-only experimental API. (iter_next_chunk)
Advances the iterator and returns an array containing the next N values. Read more
Returns the bounds on the remaining length of the iterator. Read more
Consumes the iterator, counting the number of iterations and returning it. Read more
Consumes the iterator, returning the last element. Read more
🔬This is a nightly-only experimental API. (iter_advance_by)
Advances the iterator by n elements. Read more
Returns the nth element of the iterator. Read more
Creates an iterator starting at the same point, but stepping by the given amount at each iteration. Read more
Takes two iterators and creates a new iterator over both in sequence. Read more
‘Zips up’ two iterators into a single iterator of pairs. Read more
🔬This is a nightly-only experimental API. (iter_intersperse)
Creates a new iterator which places an item generated by separator between adjacent items of the original iterator. Read more
Takes a closure and creates an iterator which calls that closure on each element. Read more
Calls a closure on each element of an iterator. Read more
Creates an iterator which uses a closure to determine if an element should be yielded. Read more
Creates an iterator that both filters and maps. Read more
Creates an iterator which gives the current iteration count as well as the next value. Read more
Creates an iterator which can use the peek and peek_mut methods to look at the next element of the iterator without consuming it. See their documentation for more information. Read more
Creates an iterator that skips elements based on a predicate. Read more
Creates an iterator that yields elements based on a predicate. Read more
Creates an iterator that both yields elements based on a predicate and maps. Read more
Creates an iterator that skips the first n elements. Read more
Creates an iterator that yields the first n elements, or fewer if the underlying iterator ends sooner. Read more
An iterator adapter similar to fold that holds internal state and produces a new iterator. Read more
Creates an iterator that works like map, but flattens nested structure. Read more
Creates an iterator which ends after the first None. Read more
Does something with each element of an iterator, passing the value on. Read more
Borrows an iterator, rather than consuming it. Read more
Transforms an iterator into a collection. Read more
🔬This is a nightly-only experimental API. (iter_collect_into)
Collects all the items from an iterator into a collection. Read more
Consumes an iterator, creating two collections from it. Read more
🔬This is a nightly-only experimental API. (iter_is_partitioned)
Checks if the elements of this iterator are partitioned according to the given predicate, such that all those that return true precede all those that return false. Read more
An iterator method that applies a function as long as it returns successfully, producing a single, final value. Read more
An iterator method that applies a fallible function to each item in the iterator, stopping at the first error and returning that error. Read more
Folds every element into an accumulator by applying an operation, returning the final result. Read more
Reduces the elements to a single one, by repeatedly applying a reducing operation. Read more
🔬This is a nightly-only experimental API. (iterator_try_reduce)
Reduces the elements to a single one by repeatedly applying a reducing operation. If the closure returns a failure, the failure is propagated back to the caller immediately. Read more
Tests if every element of the iterator matches a predicate. Read more
Tests if any element of the iterator matches a predicate. Read more
Searches for an element of an iterator that satisfies a predicate. Read more
Applies function to the elements of iterator and returns the first non-none result. Read more
🔬This is a nightly-only experimental API. (try_find)
Applies function to the elements of iterator and returns the first true result or the first error. Read more
Searches for an element in an iterator, returning its index. Read more
Returns the element that gives the maximum value from the specified function. Read more
Returns the element that gives the maximum value with respect to the specified comparison function. Read more
Returns the element that gives the minimum value from the specified function. Read more
Returns the element that gives the minimum value with respect to the specified comparison function. Read more
Converts an iterator of pairs into a pair of containers. Read more
Creates an iterator which copies all of its elements. Read more
Creates an iterator which clones all of its elements. Read more
🔬This is a nightly-only experimental API. (iter_array_chunks)
Returns an iterator over N elements of the iterator at a time. Read more
Sums the elements of an iterator. Read more
Iterates over the entire iterator, multiplying all the elements Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more
Lexicographically compares the elements of this Iterator with those of another. Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Lexicographically compares the elements of this Iterator with those of another with respect to the specified comparison function. Read more
Determines if the elements of this Iterator are equal to those of another. Read more
🔬This is a nightly-only experimental API. (iter_order_by)
Determines if the elements of this Iterator are equal to those of another with respect to the specified equality function. Read more
Determines if the elements of this Iterator are unequal to those of another. Read more
Determines if the elements of this Iterator are lexicographically less than those of another. Read more
Determines if the elements of this Iterator are lexicographically less or equal to those of another. Read more
Determines if the elements of this Iterator are lexicographically greater than those of another. Read more
Determines if the elements of this Iterator are lexicographically greater than or equal to those of another. Read more
🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given comparator function. Read more
🔬This is a nightly-only experimental API. (is_sorted)
Checks if the elements of this iterator are sorted using the given key extraction function. 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.

The type of the elements being iterated over.
Which kind of iterator are we turning this into?
Creates an iterator from a value. Read more
Convert to S a sample type from self.
Choose one element at random from the iterator. Read more
Choose one element at random from the iterator. Read more
Collects values at random from the iterator into a supplied buffer until that buffer is filled. Read more
Collects amount values at random from the iterator into a vector. Read more
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.