github.com/vishvananda/netlink@v1.3.0/nl/mpls_linux.go (about) 1 package nl 2 3 import "encoding/binary" 4 5 const ( 6 MPLS_LS_LABEL_SHIFT = 12 7 MPLS_LS_S_SHIFT = 8 8 ) 9 10 func EncodeMPLSStack(labels ...int) []byte { 11 b := make([]byte, 4*len(labels)) 12 for idx, label := range labels { 13 l := label << MPLS_LS_LABEL_SHIFT 14 if idx == len(labels)-1 { 15 l |= 1 << MPLS_LS_S_SHIFT 16 } 17 binary.BigEndian.PutUint32(b[idx*4:], uint32(l)) 18 } 19 return b 20 } 21 22 func DecodeMPLSStack(buf []byte) []int { 23 if len(buf)%4 != 0 { 24 return nil 25 } 26 stack := make([]int, 0, len(buf)/4) 27 for len(buf) > 0 { 28 l := binary.BigEndian.Uint32(buf[:4]) 29 buf = buf[4:] 30 stack = append(stack, int(l)>>MPLS_LS_LABEL_SHIFT) 31 if (l>>MPLS_LS_S_SHIFT)&1 > 0 { 32 break 33 } 34 } 35 return stack 36 }