ParseLengthAndMagic checks if if the given byte array is longer or equal the uint32 in the first 4 bytes, and if the magic value in the second 4 bytes equals the supplied magic and returns the length, a slice of the bytes without length and magic or an error.
(bytes []byte, exptectedMagic uint32)
| 15 | //ParseLengthAndMagic checks if if the given byte array is longer or equal the uint32 in the first 4 bytes, and if the magic value in the second 4 bytes equals the supplied magic |
| 16 | // and returns the length, a slice of the bytes without length and magic or an error. |
| 17 | func ParseLengthAndMagic(bytes []byte, exptectedMagic uint32) (int, []byte, error) { |
| 18 | length := binary.LittleEndian.Uint32(bytes) |
| 19 | magic := binary.LittleEndian.Uint32(bytes[4:]) |
| 20 | if int(length) > len(bytes) { |
| 21 | return 0, bytes, fmt.Errorf("invalid length in header: %d but only received: %d bytes", length, len(bytes)) |
| 22 | } |
| 23 | if magic != exptectedMagic { |
| 24 | unknownMagic := string(bytes[4:8]) |
| 25 | return 0, nil, fmt.Errorf("unknown magic type:%s (0x%x), cannot parse value %s", unknownMagic, magic, hex.Dump(bytes)) |
| 26 | } |
| 27 | return int(length), bytes[8:], nil |
| 28 | } |
no outgoing calls
no test coverage detected