1use std::net::Ipv4Addr;
9use std::ops::RangeInclusive;
10
11use crate::nic::Iface;
12use bytes::Buf;
13use thiserror::Error;
14use tracing::debug;
15
16pub const PAYLOAD_TYPE_IMAGE: u16 = 0x0001;
21
22pub const PAYLOAD_TYPE_EXTENDED_CHUNK: u16 = 0x4000;
24
25pub const PAYLOAD_TYPE_CHUNK_DATA: u16 = 0x0004;
31
32pub const PAYLOAD_TYPE_EXTENDED_CHUNK_DATA: u16 = 0x0005;
41
42const PAYLOAD_TYPE_MASK: u16 = 0x3FFF;
44
45pub fn is_image_payload(payload_type: u16) -> bool {
48 matches!(
49 payload_type & PAYLOAD_TYPE_MASK,
50 PAYLOAD_TYPE_IMAGE | PAYLOAD_TYPE_EXTENDED_CHUNK_DATA
51 )
52}
53
54pub fn is_chunk_data_payload(payload_type: u16) -> bool {
56 payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_CHUNK_DATA
57}
58
59pub fn has_extended_chunks(payload_type: u16) -> bool {
62 payload_type & PAYLOAD_TYPE_EXTENDED_CHUNK != 0
63 || payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_EXTENDED_CHUNK_DATA
64}
65
66pub const GVSP_HEADER_SIZE: usize = 8;
68
69pub const GVSP_EXTENDED_HEADER_SIZE: usize = 20;
71
72const EXTENDED_ID_FLAG: u8 = 0x80;
74
75const FORMAT_LEADER: u8 = 0x01;
77const FORMAT_TRAILER: u8 = 0x02;
79const FORMAT_PAYLOAD: u8 = 0x03;
81
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub enum StreamDest {
85 Unicast {
87 dst_ip: Ipv4Addr,
89 dst_port: u16,
91 },
92 Multicast {
94 group: Ipv4Addr,
96 port: u16,
98 loopback: bool,
100 ttl: u32,
102 },
103}
104
105impl StreamDest {
106 pub fn port(&self) -> u16 {
108 match self {
109 StreamDest::Unicast { dst_port, .. } => *dst_port,
110 StreamDest::Multicast { port, .. } => *port,
111 }
112 }
113
114 pub fn addr(&self) -> Ipv4Addr {
116 match self {
117 StreamDest::Unicast { dst_ip, .. } => *dst_ip,
118 StreamDest::Multicast { group, .. } => *group,
119 }
120 }
121
122 pub fn is_multicast(&self) -> bool {
124 matches!(self, StreamDest::Multicast { .. })
125 }
126}
127
128#[derive(Debug, Clone)]
130pub struct StreamConfig {
131 pub dest: StreamDest,
133 pub iface: Iface,
135 pub packet_size: Option<u32>,
137 pub packet_delay: Option<u32>,
139 pub source_filter: Option<Ipv4Addr>,
142}
143
144#[derive(Debug, Error)]
146#[non_exhaustive]
147pub enum GvspError {
148 #[error("unsupported packet type: {0}")]
149 Unsupported(&'static str),
151 #[error("invalid packet: {0}")]
152 Invalid(&'static str),
154}
155
156const CHUNK_TAG_LEN: usize = 8;
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct ChunkRaw<'a> {
162 pub id: u32,
164 pub offset: usize,
166 pub data: &'a [u8],
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
172#[non_exhaustive]
173pub enum ChunkError {
174 #[error(
176 "{remaining} bytes remain at offset 0 of the chunk data, too few for an \
177 8-byte chunk tag"
178 )]
179 TruncatedTag {
180 remaining: usize,
182 },
183 #[error(
185 "chunk {id:#010x} tagged at offset {tag_offset} claims {length} bytes of data, \
186 more than the {tag_offset} before it"
187 )]
188 LengthPastStart {
189 id: u32,
191 tag_offset: usize,
193 length: u32,
195 },
196}
197
198pub fn parse_chunks(payload: &[u8]) -> Result<Vec<ChunkRaw<'_>>, ChunkError> {
218 let mut chunks = Vec::new();
219 let mut end = payload.len();
220 while end > 0 {
221 let tag_offset = end
222 .checked_sub(CHUNK_TAG_LEN)
223 .ok_or(ChunkError::TruncatedTag { remaining: end })?;
224 let tag = &payload[tag_offset..end];
225 let id = u32::from_be_bytes([tag[0], tag[1], tag[2], tag[3]]);
226 let length = u32::from_be_bytes([tag[4], tag[5], tag[6], tag[7]]);
227 let start = tag_offset
228 .checked_sub(length as usize)
229 .ok_or(ChunkError::LengthPastStart {
230 id,
231 tag_offset,
232 length,
233 })?;
234 chunks.push(ChunkRaw {
235 id,
236 offset: start,
237 data: &payload[start..tag_offset],
238 });
239 end = start;
240 }
241 chunks.reverse();
242 Ok(chunks)
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
260pub struct GvspHeader {
261 pub status: u16,
265 pub block_id: u64,
267 pub packet_id: u32,
269 pub extended_ids: bool,
271 pub header_len: usize,
273}
274
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub struct ImageLeader {
278 pub pixel_format: u32,
280 pub width: u32,
282 pub height: u32,
284 pub offset_x: u32,
286 pub offset_y: u32,
288 pub padding_x: u16,
290 pub padding_y: u16,
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
296pub struct GvspLeader {
297 pub payload_type: u16,
299 pub timestamp: u64,
301 pub image: Option<ImageLeader>,
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq)]
308pub struct GvspTrailer {
309 pub payload_type: u16,
311 pub size_y: u32,
314 pub chunk_payload_length: Option<u32>,
317 pub chunk_layout_id: Option<u32>,
321}
322
323#[derive(Debug, Clone, Copy, PartialEq, Eq)]
325#[non_exhaustive]
326pub enum GvspContent<'a> {
327 Leader(GvspLeader),
329 Payload(&'a [u8]),
331 Trailer(GvspTrailer),
333 Unsupported {
338 packet_format: u8,
340 },
341}
342
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
345pub struct GvspPacketRef<'a> {
346 pub header: GvspHeader,
348 pub content: GvspContent<'a>,
350}
351
352pub fn parse_packet_ref(datagram: &[u8]) -> Result<GvspPacketRef<'_>, GvspError> {
357 let header = parse_header(datagram)?;
358 let packet_format = datagram[4] & 0x0F;
359 let body = &datagram[header.header_len..];
360 let content = match packet_format {
361 FORMAT_LEADER => GvspContent::Leader(parse_leader(body)?),
362 FORMAT_PAYLOAD => GvspContent::Payload(body),
363 FORMAT_TRAILER => GvspContent::Trailer(parse_trailer(header.block_id, body)?),
364 other => GvspContent::Unsupported {
365 packet_format: other,
366 },
367 };
368 Ok(GvspPacketRef { header, content })
369}
370
371pub fn parse_header(datagram: &[u8]) -> Result<GvspHeader, GvspError> {
377 if datagram.len() < GVSP_HEADER_SIZE {
378 return Err(GvspError::Invalid("GVSP header truncated"));
379 }
380 let status = u16::from_be_bytes([datagram[0], datagram[1]]);
381 let format_byte = datagram[4];
382 let extended_ids = format_byte & EXTENDED_ID_FLAG != 0;
383
384 let header = if extended_ids {
385 if datagram.len() < GVSP_EXTENDED_HEADER_SIZE {
386 return Err(GvspError::Invalid("extended GVSP header truncated"));
387 }
388 let mut block = [0u8; 8];
389 block.copy_from_slice(&datagram[8..16]);
390 GvspHeader {
391 status,
392 block_id: u64::from_be_bytes(block),
393 packet_id: u32::from_be_bytes([datagram[16], datagram[17], datagram[18], datagram[19]]),
394 extended_ids,
395 header_len: GVSP_EXTENDED_HEADER_SIZE,
396 }
397 } else {
398 GvspHeader {
399 status,
400 block_id: u64::from(u16::from_be_bytes([datagram[2], datagram[3]])),
401 packet_id: u32::from_be_bytes([0, datagram[5], datagram[6], datagram[7]]),
402 extended_ids,
403 header_len: GVSP_HEADER_SIZE,
404 }
405 };
406 Ok(header)
407}
408
409fn parse_leader(body: &[u8]) -> Result<GvspLeader, GvspError> {
427 if body.len() < 12 {
428 return Err(GvspError::Invalid("leader payload truncated"));
429 }
430 let mut cursor = body;
431 let _reserved = cursor.get_u16();
432 let payload_type = cursor.get_u16();
433 let timestamp = cursor.get_u64();
434 let image = if is_image_payload(payload_type) {
435 if cursor.len() < 12 {
436 return Err(GvspError::Invalid("image leader truncated"));
437 }
438 let pixel_format = cursor.get_u32();
439 let width = cursor.get_u32();
440 let height = cursor.get_u32();
441 let (offset_x, offset_y) = if cursor.len() >= 8 {
442 (cursor.get_u32(), cursor.get_u32())
443 } else {
444 (0, 0)
445 };
446 let (padding_x, padding_y) = if cursor.len() >= 4 {
447 (cursor.get_u16(), cursor.get_u16())
448 } else {
449 (0, 0)
450 };
451 Some(ImageLeader {
452 pixel_format,
453 width,
454 height,
455 offset_x,
456 offset_y,
457 padding_x,
458 padding_y,
459 })
460 } else {
461 None
462 };
463 Ok(GvspLeader {
464 payload_type,
465 timestamp,
466 image,
467 })
468}
469
470fn parse_trailer(block_id: u64, body: &[u8]) -> Result<GvspTrailer, GvspError> {
492 if body.len() < 2 {
493 return Err(GvspError::Invalid("trailer truncated"));
494 }
495 if body.len() < 8 {
499 debug!(
500 block_id,
501 len = body.len(),
502 "trailer payload shorter than the specified 8 bytes"
503 );
504 return Ok(GvspTrailer {
505 payload_type: 0,
506 size_y: 0,
507 chunk_payload_length: None,
508 chunk_layout_id: None,
509 });
510 }
511 let mut cursor = &body[2..];
512 let payload_type = cursor.get_u16();
513 if payload_type & PAYLOAD_TYPE_MASK == PAYLOAD_TYPE_EXTENDED_CHUNK_DATA && cursor.len() >= 12 {
514 let length = cursor.get_u32();
516 let size_y = cursor.get_u32();
517 return Ok(GvspTrailer {
518 payload_type,
519 size_y,
520 chunk_payload_length: Some(length),
521 chunk_layout_id: Some(cursor.get_u32()),
522 });
523 }
524 let size_y = cursor.get_u32();
525 let (chunk_payload_length, chunk_layout_id) =
526 if has_extended_chunks(payload_type) && cursor.len() >= 8 {
527 (Some(cursor.get_u32()), Some(cursor.get_u32()))
528 } else {
529 (None, None)
530 };
531 Ok(GvspTrailer {
532 payload_type,
533 size_y,
534 chunk_payload_length,
535 chunk_layout_id,
536 })
537}
538
539#[derive(Debug, Clone, Default)]
544pub struct PacketBitmap {
545 words: Vec<u64>,
546 received: usize,
547 total: usize,
548}
549
550impl PacketBitmap {
551 pub fn new(total: usize) -> Self {
553 let words = total.div_ceil(64);
554 Self {
555 words: vec![0; words],
556 received: 0,
557 total,
558 }
559 }
560
561 pub fn reset(&mut self, total: usize) {
563 self.words.clear();
564 self.words.resize(total.div_ceil(64), 0);
565 self.received = 0;
566 self.total = total;
567 }
568
569 pub fn grow(&mut self, total: usize) {
571 if total > self.total {
572 self.words.resize(total.div_ceil(64), 0);
573 self.total = total;
574 }
575 }
576
577 pub fn len(&self) -> usize {
579 self.total
580 }
581
582 pub fn is_empty(&self) -> bool {
584 self.total == 0
585 }
586
587 pub fn received(&self) -> usize {
589 self.received
590 }
591
592 fn mask_for(&self, packet_id: usize) -> (usize, u64) {
593 let word = packet_id / 64;
594 let bit = packet_id % 64;
595 (word, 1u64 << bit)
596 }
597
598 pub fn contains(&self, packet_id: usize) -> bool {
600 if packet_id >= self.total {
601 return false;
602 }
603 let (word, mask) = self.mask_for(packet_id);
604 self.words[word] & mask != 0
605 }
606
607 pub fn set(&mut self, packet_id: usize) -> bool {
610 if packet_id >= self.total {
611 return false;
612 }
613 let (word, mask) = self.mask_for(packet_id);
614 let entry = &mut self.words[word];
615 if *entry & mask == 0 {
616 *entry |= mask;
617 self.received += 1;
618 true
619 } else {
620 false
621 }
622 }
623
624 pub fn clear(&mut self, packet_id: usize) -> bool {
626 if !self.contains(packet_id) {
627 return false;
628 }
629 let (word, mask) = self.mask_for(packet_id);
630 self.words[word] &= !mask;
631 self.received -= 1;
632 true
633 }
634
635 pub fn first_n_complete(&self, count: usize) -> bool {
637 if count > self.total {
638 return false;
639 }
640 let full = count / 64;
641 if self.words[..full].iter().any(|w| *w != u64::MAX) {
642 return false;
643 }
644 let rest = count % 64;
645 rest == 0 || self.words[full] & ((1u64 << rest) - 1) == (1u64 << rest) - 1
646 }
647
648 pub fn is_complete(&self) -> bool {
650 self.received == self.total
651 }
652
653 pub fn missing_ranges(&self) -> Vec<RangeInclusive<u32>> {
655 let mut ranges = Vec::new();
656 let mut current: Option<(u32, u32)> = None;
657 for idx in 0..self.total {
658 let (word, mask) = self.mask_for(idx);
659 let present = (self.words[word] & mask) != 0;
660 match (present, current) {
661 (false, None) => current = Some((idx as u32, idx as u32)),
662 (false, Some((start, _))) => current = Some((start, idx as u32)),
663 (true, Some((start, end))) => {
664 ranges.push(start..=end);
665 current = None;
666 }
667 _ => {}
668 }
669 }
670 if let Some((start, end)) = current {
671 ranges.push(start..=end);
672 }
673 ranges
674 }
675}
676
677#[cfg(test)]
678mod tests {
679 use super::*;
680
681 #[test]
685 fn lucid_evt30_capture_uses_an_image_leader() {
686 #[rustfmt::skip]
687 const LEADER: [u8; 56] = [
688 0x00, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x42, 0x2d, 0x66, 0xd4, 0x39, 0xc8, 0x81, 0x10, 0x0e, 0x30, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xfa, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ];
704
705 let packet = parse_packet_ref(&LEADER).expect("parse captured LUCID leader");
706 let GvspContent::Leader(leader) = packet.content else {
707 panic!("expected leader");
708 };
709 let image = leader.image.expect("an IMAGE leader has image fields");
710
711 assert_eq!(packet.header.block_id, 1);
712 assert_eq!(packet.header.packet_id, 0);
713 assert_eq!(packet.header.header_len, GVSP_EXTENDED_HEADER_SIZE);
714 assert_eq!(leader.payload_type, PAYLOAD_TYPE_IMAGE);
715 assert_eq!(leader.timestamp, 0x0000_422d_66d4_39c8);
716 assert_eq!(image.pixel_format, 0x8110_0e30);
717 assert_eq!((image.width, image.height), (1, 64_000));
718 }
719
720 #[test]
722 fn lucid_evt30_capture_trailer_reports_payload_bytes() {
723 #[rustfmt::skip]
724 const TRAILER: [u8; 28] = [
725 0x00, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x38, ];
735
736 let packet = parse_packet_ref(&TRAILER).expect("parse captured LUCID trailer");
737 let GvspContent::Trailer(trailer) = packet.content else {
738 panic!("expected trailer");
739 };
740
741 assert_eq!(packet.header.block_id, 1);
742 assert_eq!(packet.header.packet_id, 2);
743 assert_eq!(packet.header.status, 0);
744 assert_eq!(trailer.payload_type, PAYLOAD_TYPE_IMAGE);
745 assert_eq!(trailer.size_y, 824);
746 assert_eq!(trailer.chunk_payload_length, None);
747 }
748
749 #[test]
757 fn a_gige_vision_1_extended_chunk_block_is_an_image_with_chunks() {
758 #[rustfmt::skip]
759 const LEADER: [u8; 44] = [
760 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00,
761 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x2e, 0xf1, 0xc1, 0x84, 0xe8, 0x01, 0x08, 0x00, 0x01, 0x00, 0x00, 0x05, 0x0c, 0x00, 0x00, 0x03, 0xc4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
768 0x00, 0x00, 0x00, 0x00,
769 ];
770 #[rustfmt::skip]
771 const TRAILER: [u8; 24] = [
772 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x03, 0x54,
773 0x00, 0x00, 0x00, 0x05, 0x00, 0x13, 0x01, 0x68, 0x00, 0x00, 0x03, 0xc4, 0x00, 0x00, 0x00, 0x01, ];
779 let GvspContent::Leader(leader) = parse_packet_ref(&LEADER).expect("leader").content else {
780 panic!("expected a leader");
781 };
782 let image = leader.image.expect("an image leader");
783 assert_eq!(
784 (image.pixel_format, image.width, image.height),
785 (0x0108_0001, 1292, 964)
786 );
787 assert!(is_image_payload(leader.payload_type));
788 assert!(has_extended_chunks(leader.payload_type));
789
790 let GvspContent::Trailer(trailer) = parse_packet_ref(&TRAILER).expect("trailer").content
791 else {
792 panic!("expected a trailer");
793 };
794 assert_eq!(trailer.payload_type, PAYLOAD_TYPE_EXTENDED_CHUNK_DATA);
795 assert_eq!(trailer.size_y, 964);
796 assert_eq!(trailer.chunk_payload_length, Some(1_245_544));
797 assert_eq!(trailer.chunk_layout_id, Some(1));
798 }
799
800 fn golden_leader(payload_type: u16) -> Vec<u8> {
804 let mut pkt = vec![0x00, 0x00, 0x00, 0x07, 0x01, 0x00, 0x00, 0x00];
805 pkt.extend_from_slice(&0u16.to_be_bytes());
806 pkt.extend_from_slice(&payload_type.to_be_bytes());
807 pkt.extend_from_slice(&0x0102_0304_0506_0708u64.to_be_bytes());
808 pkt.extend_from_slice(&0x0108_0001u32.to_be_bytes());
809 pkt.extend_from_slice(&640u32.to_be_bytes());
810 pkt.extend_from_slice(&480u32.to_be_bytes());
811 pkt.extend_from_slice(&[0u8; 12]);
812 pkt
813 }
814
815 #[test]
818 fn leader_keeps_the_extended_chunk_bit() {
819 let pkt = golden_leader(0x4001);
820 let GvspContent::Leader(leader) = parse_packet_ref(&pkt).expect("parse leader").content
821 else {
822 panic!("expected a leader");
823 };
824 assert_eq!(leader.payload_type, 0x4001);
825 }
826
827 fn golden_trailer(status: u16, payload_type: u16, size_y: u32, extra: &[u8]) -> Vec<u8> {
834 let mut pkt = Vec::new();
835 pkt.extend_from_slice(&status.to_be_bytes());
836 pkt.extend_from_slice(&0x0007u16.to_be_bytes()); pkt.push(0x02); pkt.extend_from_slice(&[0x00, 0x00, 0x42]); pkt.extend_from_slice(&0u16.to_be_bytes()); pkt.extend_from_slice(&payload_type.to_be_bytes());
841 pkt.extend_from_slice(&size_y.to_be_bytes());
842 pkt.extend_from_slice(extra);
843 pkt
844 }
845
846 #[test]
851 fn a_plain_image_trailer_has_no_chunk_fields() {
852 let pkt = golden_trailer(0, PAYLOAD_TYPE_IMAGE, 1536, &[]);
853 assert_eq!(pkt.len(), 16, "8-byte header + 8-byte trailer payload");
854
855 let packet = parse_packet_ref(&pkt).expect("parse trailer");
856 let GvspContent::Trailer(trailer) = packet.content else {
857 panic!("expected a trailer");
858 };
859
860 assert_eq!(packet.header.block_id, 0x0007);
861 assert_eq!(packet.header.packet_id, 0x42);
862 assert_eq!(packet.header.status, 0);
863 assert_eq!(trailer.payload_type, 0x0001);
864 assert_eq!(trailer.size_y, 1536);
865 assert_eq!(trailer.chunk_payload_length, None);
866 assert_eq!(trailer.chunk_layout_id, None);
867 }
868
869 #[test]
875 fn an_extended_chunk_trailer_reports_length_and_layout_id() {
876 let mut extra = Vec::new();
877 extra.extend_from_slice(&0x0004_B044u32.to_be_bytes()); extra.extend_from_slice(&0xC0DE_0001u32.to_be_bytes()); let pkt = golden_trailer(0, 0x4001, 480, &extra);
880 let GvspContent::Trailer(trailer) = parse_packet_ref(&pkt).expect("parse trailer").content
881 else {
882 panic!("expected a trailer");
883 };
884 assert_eq!(trailer.payload_type, 0x4001);
885 assert_eq!(trailer.size_y, 480);
886 assert_eq!(trailer.chunk_payload_length, Some(0x0004_B044));
887 assert_eq!(trailer.chunk_layout_id, Some(0xC0DE_0001));
888 }
889
890 #[test]
894 fn trailer_status_comes_from_the_packet_header() {
895 let pkt = golden_trailer(0x8004, PAYLOAD_TYPE_IMAGE, 0, &[]);
898 let packet = parse_packet_ref(&pkt).expect("parse trailer");
899 assert!(matches!(packet.content, GvspContent::Trailer(_)));
900 assert_eq!(packet.header.status, 0x8004);
901 }
902
903 #[test]
904 fn bitmap_missing_ranges_coalesce() {
905 let mut bitmap = PacketBitmap::new(10);
906 for &idx in &[0usize, 1, 5, 6, 9] {
907 bitmap.set(idx);
908 }
909 let ranges = bitmap.missing_ranges();
910 assert_eq!(ranges.len(), 2);
911 assert_eq!(ranges[0], 2..=4);
912 assert_eq!(ranges[1], 7..=8);
913 }
914
915 #[test]
916 fn bitmap_reset_and_grow_keep_their_promises() {
917 let mut bitmap = PacketBitmap::new(70);
918 assert!(bitmap.set(0) && bitmap.set(69));
919 bitmap.grow(130);
920 assert!(bitmap.contains(69), "growing keeps what was set");
921 assert_eq!(bitmap.len(), 130);
922 bitmap.reset(3);
923 assert_eq!((bitmap.len(), bitmap.received()), (3, 0));
924 assert!(!bitmap.contains(0));
925 }
926
927 #[test]
928 fn first_n_complete_checks_a_prefix() {
929 let mut bitmap = PacketBitmap::new(130);
930 for idx in 0..128 {
931 bitmap.set(idx);
932 }
933 assert!(bitmap.first_n_complete(64));
934 assert!(bitmap.first_n_complete(128));
935 assert!(!bitmap.first_n_complete(129));
936 assert!(
937 !bitmap.first_n_complete(131),
938 "beyond the bitmap is never complete"
939 );
940 assert!(bitmap.first_n_complete(0));
941 }
942
943 #[test]
946 fn extended_payload_data_starts_after_the_20_byte_header() {
947 #[rustfmt::skip]
948 let pkt = [
949 0x00, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00,
950 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0xAA, 0xBB, 0xCC,
953 ];
954 let packet = parse_packet_ref(&pkt).expect("parse");
955 assert_eq!(packet.header.block_id, 0x0000_0001_0000_0002);
956 assert_eq!(packet.header.packet_id, 0x0001_0000);
957 assert_eq!(packet.header.header_len, 20);
958 assert!(packet.header.extended_ids);
959 assert_eq!(packet.content, GvspContent::Payload(&[0xAA, 0xBB, 0xCC]));
960 }
961
962 #[test]
965 fn a_non_image_leader_is_typed_not_refused() {
966 let file = golden_leader(0x0003);
967 let packet = parse_packet_ref(&file).expect("a file leader parses");
968 let GvspContent::Leader(leader) = packet.content else {
969 panic!("expected a leader");
970 };
971 assert_eq!(leader.payload_type, 0x0003);
972 assert_eq!(leader.image, None);
973
974 let chunked = golden_leader(0x4001);
975 let packet = parse_packet_ref(&chunked).expect("parse");
976 let GvspContent::Leader(leader) = packet.content else {
977 panic!("expected a leader");
978 };
979 assert!(is_image_payload(leader.payload_type));
980 assert!(has_extended_chunks(leader.payload_type));
981 let image = leader.image.expect("an image leader has image fields");
982 assert_eq!((image.width, image.height), (640, 480));
983 assert_eq!(leader.timestamp, 0x0102_0304_0506_0708);
984 }
985
986 #[test]
989 fn other_packet_formats_are_unsupported_values() {
990 let pkt = [0x00, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x05, 0x00];
991 let packet = parse_packet_ref(&pkt).expect("parse");
992 assert_eq!(
993 packet.content,
994 GvspContent::Unsupported {
995 packet_format: 0x07
996 }
997 );
998 assert_eq!(packet.header.packet_id, 5);
999 }
1000
1001 #[test]
1002 fn a_truncated_extended_header_is_invalid() {
1003 let pkt = [0x00, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00];
1004 assert!(matches!(parse_packet_ref(&pkt), Err(GvspError::Invalid(_))));
1005 }
1006
1007 #[test]
1011 fn a_bare_header_parses_on_its_own() {
1012 let bare = [0x80, 0x0C, 0x00, 0x09, 0x02, 0x00, 0x00, 0x05];
1013 let header = parse_header(&bare).expect("header");
1014 assert_eq!(
1015 crate::GigeStatus::from_raw(header.status),
1016 crate::GigeStatus::PacketUnavailable
1017 );
1018 assert_eq!((header.block_id, header.packet_id), (9, 5));
1019 assert!(parse_packet_ref(&bare).is_err());
1020 }
1021}