summaryrefslogtreecommitdiffhomepage
path: root/dhcpv4/bsdp/bsdp_option_generic.go
blob: 6a51e294eeeaf0e187a1d6393e6a3d09aa3349be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package bsdp

import (
	"fmt"

	"github.com/insomniacslk/dhcp/dhcpv4"
)

// OptGeneric is an option that only contains the option code and associated
// data. Every option that does not have a specific implementation will fall
// back to this option.
type OptGeneric struct {
	OptionCode dhcpv4.OptionCode
	Data       []byte
}

// ParseOptGeneric parses a bytestream and creates a new OptGeneric from it,
// or an error.
func ParseOptGeneric(data []byte) (*OptGeneric, error) {
	if len(data) == 0 {
		return nil, dhcpv4.ErrZeroLengthByteStream
	}
	var (
		length     int
		optionData []byte
	)
	code := dhcpv4.OptionCode(data[0])
	length = int(data[1])
	if len(data) < length+2 {
		return nil, fmt.Errorf("invalid data length: declared %v, actual %v", length, len(data))
	}
	optionData = data[2 : length+2]
	return &OptGeneric{OptionCode: code, Data: optionData}, nil
}

// Code returns the generic option code.
func (o OptGeneric) Code() dhcpv4.OptionCode {
	return o.OptionCode
}

// ToBytes returns a serialized generic option as a slice of bytes.
func (o OptGeneric) ToBytes() []byte {
	return append([]byte{byte(o.Code()), byte(o.Length())}, o.Data...)
}

// String returns a human-readable representation of a generic option.
func (o OptGeneric) String() string {
	code, ok := OptionCodeToString[o.Code()]
	if !ok {
		code = "Unknown"
	}
	return fmt.Sprintf("%v -> %v", code, o.Data)
}

// Length returns the number of bytes comprising the data section of the option.
func (o OptGeneric) Length() int {
	return len(o.Data)
}