gen.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2019 The GoPacket Authors. All rights reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the LICENSE file in the root of the source
  5. // tree.
  6. // +build ignore
  7. // This file generates LayersDecoder function for DecodingLayerContainer
  8. // go run gen.go | gofmt > layers_decoder.go
  9. package main
  10. import (
  11. "fmt"
  12. "os"
  13. "time"
  14. )
  15. const headerFmt = `// Copyright 2019 The GoPacket Authors. All rights reserved.
  16. package gopacket
  17. // Created by gen.go, don't edit manually
  18. // Generated at %s
  19. // LayersDecoder returns DecodingLayerFunc for specified
  20. // DecodingLayerContainer, LayerType value to start decoding with and
  21. // some DecodeFeedback.
  22. func LayersDecoder(dl DecodingLayerContainer, first LayerType, df DecodeFeedback) DecodingLayerFunc {
  23. firstDec, ok := dl.Decoder(first)
  24. if !ok {
  25. return func([]byte, *[]LayerType) (LayerType, error) {
  26. return first, nil
  27. }
  28. }
  29. `
  30. var funcBody = `return func(data []byte, decoded *[]LayerType) (LayerType, error) {
  31. *decoded = (*decoded)[:0] // Truncated decoded layers.
  32. typ := first
  33. decoder := firstDec
  34. for {
  35. if err := decoder.DecodeFromBytes(data, df); err != nil {
  36. return LayerTypeZero, err
  37. }
  38. *decoded = append(*decoded, typ)
  39. typ = decoder.NextLayerType()
  40. if data = decoder.LayerPayload(); len(data) == 0 {
  41. break
  42. }
  43. if decoder, ok = dlc.Decoder(typ); !ok {
  44. return typ, nil
  45. }
  46. }
  47. return LayerTypeZero, nil
  48. }`
  49. func main() {
  50. fmt.Fprintf(os.Stderr, "Writing results to stdout\n")
  51. types := []string{
  52. "DecodingLayerSparse",
  53. "DecodingLayerArray",
  54. "DecodingLayerMap",
  55. }
  56. fmt.Printf(headerFmt, time.Now())
  57. for _, t := range types {
  58. fmt.Printf("if dlc, ok := dl.(%s); ok {", t)
  59. fmt.Println(funcBody)
  60. fmt.Println("}")
  61. }
  62. fmt.Println("dlc := dl")
  63. fmt.Println(funcBody)
  64. fmt.Println("}")
  65. }