//
//  UDPPacket.swift
//  Tun
//
//  Created by 安礼成 on 2025/12/13.
//

import Foundation

struct UDPHeader {
    let sourcePort: UInt16
    let destinationPort: UInt16
    let length: UInt16
    let checksum: UInt16
}

struct UDPPacket {
    let header: UDPHeader
    let payload: Data
    
    init?(_ data: Data) {
        // UDP header 至少 8 字节
        guard data.count >= 8 else {
            return nil
        }
        
        let header = UDPHeader(sourcePort: UInt16(bytes: (data[0], data[1])),
                               destinationPort: UInt16(bytes: (data[2], data[3])),
                               length: UInt16(bytes: (data[4], data[5])),
                               checksum: UInt16(bytes: (data[6], data[7]))
        )
        // UDP payload = length - 8
        let payloadLength = Int(header.length) - 8
        
        self.header = header
        self.payload = data.subdata(in: 8..<(8 + payloadLength))
    }
}
