mpls_linux.go 688 B

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