Skip to main content

parse_header/
parse_header.rs

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