summaryrefslogtreecommitdiffhomepage
path: root/dhcpv4/option_parameter_request_list.go
blob: 324832edbb665660734195d5bdedec3deda4c044 (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
59
60
61
62
63
64
65
66
67
68
69
package dhcpv4

import (
	"fmt"
	"strings"
)

// This option implements the parameter request list option
// https://tools.ietf.org/html/rfc2132

// OptParameterRequestList represents the parameter request list option.
type OptParameterRequestList struct {
	RequestedOpts []OptionCode
}

// ParseOptParameterRequestList returns a new OptParameterRequestList from a
// byte stream, or error if any.
func ParseOptParameterRequestList(data []byte) (*OptParameterRequestList, error) {
	// Should at least have code + length byte.
	if len(data) < 2 {
		return nil, ErrShortByteStream
	}
	code := OptionCode(data[0])
	if code != OptionParameterRequestList {
		return nil, fmt.Errorf("expected code %v, got %v", OptionParameterRequestList, code)
	}
	length := int(data[1])
	if len(data) < length+2 {
		return nil, ErrShortByteStream
	}
	var requestedOpts []OptionCode
	for _, opt := range data[2 : length+2] {
		requestedOpts = append(requestedOpts, OptionCode(opt))
	}
	return &OptParameterRequestList{RequestedOpts: requestedOpts}, nil
}

// Code returns the option code.
func (o *OptParameterRequestList) Code() OptionCode {
	return OptionParameterRequestList
}

// ToBytes returns a serialized stream of bytes for this option.
func (o *OptParameterRequestList) ToBytes() []byte {
	ret := []byte{byte(o.Code()), byte(o.Length())}
	for _, req := range o.RequestedOpts {
		ret = append(ret, byte(req))
	}
	return ret
}

// String returns a human-readable string for this option.
func (o *OptParameterRequestList) String() string {
	var optNames []string
	for _, ro := range o.RequestedOpts {
		if name, ok := OptionCodeToString[ro]; ok {
			optNames = append(optNames, name)
		} else {
			optNames = append(optNames, fmt.Sprintf("Unknown (%v)", ro))
		}
	}
	return fmt.Sprintf("Parameter Request List -> [%v]", strings.Join(optNames, ", "))
}

// Length returns the length of the data portion (excluding option code and byte
// for length, if any).
func (o *OptParameterRequestList) Length() int {
	return len(o.RequestedOpts)
}