...

Source file src/go.formulabun.club/srb2kart/network/header.go

Documentation: go.formulabun.club/srb2kart/network

     1  package network
     2  
     3  import (
     4  	"encoding/binary"
     5  )
     6  
     7  type header struct {
     8  	Checksum   uint32
     9  	Ack        uint8
    10  	AckReturn  uint8
    11  	PacketType packettype_t
    12  	Reserved   uint8
    13  }
    14  
    15  type checksumCalculator struct {
    16  	checksum uint32
    17  	term     int
    18  }
    19  
    20  func newChecksumCalculator() *checksumCalculator {
    21  	return &checksumCalculator{0x1234567, 1}
    22  }
    23  
    24  func (c *checksumCalculator) Write(data []byte) (n int, err error) {
    25  	var skip = 0
    26  	// if term is the initial value, we skip the checksum of the header
    27  	if c.term == 1 {
    28  		skip = 4
    29  	}
    30  	for _, d := range data[skip:] {
    31  		c.checksum += uint32(d) * uint32(c.term)
    32  		c.term += 1
    33  	}
    34  	return len(data), nil
    35  }
    36  
    37  func (c *checksumCalculator) setChecksum(h *header, data any) {
    38  	err := binary.Write(c, binary.LittleEndian, h)
    39  	if err != nil {
    40  		panic(err)
    41  	}
    42  	err = binary.Write(c, binary.LittleEndian, data)
    43  	if err != nil {
    44  		panic(err)
    45  	}
    46  	h.Checksum = c.checksum
    47  }
    48  
    49  func makeHeader(packetType packettype_t, packetData any) header {
    50  	h := header{0, 0, 0, packetType, 0}
    51  	c := newChecksumCalculator()
    52  	c.setChecksum(&h, packetData)
    53  	return h
    54  }
    55  

View as plain text