Skip to main content

parse_header/
parse_header.rs

1#![allow(missing_docs)]
2/* examples/parse_header.rs */
3
4// Demonstrates parsing a QUIC Initial packet header without any crypto
5// dependency. This example works with all feature configurations including
6// `--no-default-features`.
7
8fn main() {
9	// A minimal QUIC v1 Initial packet (truncated payload).
10	// In practice this would come from a UDP socket.
11	let packet: Vec<u8> = build_sample_initial();
12
13	match quic_parser::parse_initial(&packet) {
14		Ok(header) => {
15			println!("QUIC Initial packet parsed successfully");
16			println!("  version:      {:#010x}", header.version);
17			println!("  dcid:         {}", hex(header.dcid));
18			println!("  scid:         {}", hex(header.scid));
19			println!("  token length: {}", header.token.len());
20			println!("  payload size: {} bytes", header.payload.len());
21		}
22		Err(e) => {
23			eprintln!("parse error: {e}");
24		}
25	}
26
27	// Peek at the DCID without a full parse.
28	if let Some(dcid) = quic_parser::peek_long_header_dcid(&packet) {
29		println!("  peeked dcid:  {}", hex(dcid));
30	}
31}
32
33fn hex(bytes: &[u8]) -> String {
34	bytes.iter().map(|b| format!("{b:02x}")).collect()
35}
36
37fn build_sample_initial() -> Vec<u8> {
38	let mut pkt = Vec::new();
39
40	// First byte: long header (0x80) | fixed bit (0x40) | Initial type (0x00)
41	// Lower 4 bits are reserved / packet number length (protected).
42	pkt.push(0xc0);
43
44	// Version: QUIC v1
45	pkt.extend_from_slice(&0x0000_0001u32.to_be_bytes());
46
47	// DCID length + DCID (8 bytes)
48	let dcid = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
49	pkt.push(dcid.len() as u8);
50	pkt.extend_from_slice(&dcid);
51
52	// SCID length + SCID (0 bytes)
53	pkt.push(0x00);
54
55	// Token length (varint 0)
56	pkt.push(0x00);
57
58	// Payload length (varint): 24 bytes of dummy payload.
59	let payload_len: u8 = 24;
60	pkt.push(payload_len);
61
62	// Dummy encrypted payload (not decryptable, just for header parsing).
63	pkt.extend_from_slice(&vec![0xAA; payload_len as usize]);
64
65	pkt
66}