github.com/geniusesgroup/libgo@v0.0.0-20220713101832-828057a9d3d4/udp/packet.go (about)

     1  // For license and copyright information please see LEGAL file in repository
     2  
     3  package udp
     4  
     5  import (
     6  	"../binary"
     7  	"../protocol"
     8  )
     9  
    10  // Packet implement all methods to Get||Set data to a packet as a byte slice with 0-alloc
    11  type Packet []byte
    12  
    13  // CheckPacket will check packet for any bad situation.
    14  // Always check packet before use any other packet methods otherwise panic occur.
    15  func (p Packet) CheckPacket() protocol.Error {
    16  	var packetLen = len(p)
    17  	if packetLen < MinPacketLen {
    18  		return ErrPacketTooShort
    19  	}
    20  	if packetLen < int(p.Length()) {
    21  		return ErrPacketWrongLength
    22  	}
    23  	return nil
    24  }
    25  
    26  /*
    27  ********** Get Methods **********
    28   */
    29  func (p Packet) SourcePort() uint16      { return binary.BigEndian.Uint16(p[0:]) }
    30  func (p Packet) DestinationPort() uint16 { return binary.BigEndian.Uint16(p[2:]) }
    31  func (p Packet) Length() uint16          { return binary.BigEndian.Uint16(p[4:]) }
    32  func (p Packet) Checksum() uint16        { return binary.BigEndian.Uint16(p[6:]) }
    33  func (p Packet) Payload() []byte         { return p[8:] }
    34  
    35  /*
    36  ********** Set Methods **********
    37   */
    38  func (p Packet) SetSourcePort(port uint16)      { binary.BigEndian.PutUint16(p[0:], port) }
    39  func (p Packet) SetDestinationPort(port uint16) { binary.BigEndian.PutUint16(p[2:], port) }
    40  func (p Packet) SetLength(v uint16)             { binary.BigEndian.PutUint16(p[4:], v) }
    41  func (p Packet) SetChecksum(v uint16)           { binary.BigEndian.PutUint16(p[6:], v) }
    42  func (p Packet) SetPayload(payload []byte)      { copy(p[8:], payload) }