github.com/GeniusesGroup/libgo@v0.0.0-20220929090155-5ff932cb408e/ipv6/packet.go (about)

     1  /* For license and copyright information please see LEGAL file in repository */
     2  
     3  package ipv6
     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 checks packet for any bad situation
    14  // Always check packet before use any other packet methods otherwise panic may occur
    15  func (p Packet) CheckPacket() protocol.Error {
    16  	if len(p) < HeaderLen {
    17  		return ErrPacketTooShort
    18  	}
    19  	return nil
    20  }
    21  
    22  /*
    23  ********** Get Methods **********
    24   */
    25  func (p Packet) Version() uint8                  { return p[0] >> 4 }
    26  func (p Packet) TrafficClass() uint8             { return p[0]<<4 | p[1]>>4 }
    27  func (p Packet) FlowLabel() (fl [3]byte)         { copy(fl[:], p[1:]); fl[0] &= 0x0f; return }
    28  func (p Packet) PayloadLength() uint16           { return binary.BigEndian.Uint16(p[4:]) }
    29  func (p Packet) NextHeader() uint8               { return p[6] }
    30  func (p Packet) HopLimit() uint8                 { return p[7] }
    31  func (p Packet) SourceAddr() (srcAddr Addr)      { copy(srcAddr[:], p[8:]); return }
    32  func (p Packet) DestinationAddr() (desAddr Addr) { copy(desAddr[:], p[24:]); return }
    33  func (p Packet) Payload() []byte                 { return p[40:] }
    34  
    35  /*
    36  ********** Set Methods **********
    37   */
    38  func (p Packet) SetVersion(v uint8)              { p[0] = (v << 4) }
    39  func (p Packet) SetTrafficClass(tc uint8)        { p[0] |= (tc >> 4); p[1] = (tc << 4) }
    40  func (p Packet) SetFlowLabel(fl [3]byte)         { p[1] |= fl[0]; p[2] = fl[1]; p[3] = fl[2] }
    41  func (p Packet) SetPayloadLength(ln uint16)      { binary.BigEndian.SetUint16(p[4:], ln) }
    42  func (p Packet) SetNextHeader(nh uint8)          { p[6] = nh }
    43  func (p Packet) SetHopLimit(hl uint8)            { p[7] = hl }
    44  func (p Packet) SetSourceAddr(srcAddr Addr)      { copy(p[8:], srcAddr[:]) }
    45  func (p Packet) SetDestinationAddr(desAddr Addr) { copy(p[24:], desAddr[:]) }
    46  func (p Packet) SetPayload(payload []byte)       { copy(p[40:], payload) }