-
Notifications
You must be signed in to change notification settings - Fork 14
/
header.go
72 lines (62 loc) · 1.59 KB
/
header.go
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
70
71
72
// Copyright 2019-2024 go-sccp authors. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be
// found in the LICENSE file.
package sccp
import (
"fmt"
"io"
)
// Header is a SCCP common header.
type Header struct {
Type MsgType
Payload []byte
}
// NewHeader creates a new Header.
func NewHeader(mtype MsgType, payload []byte) *Header {
return &Header{
Type: mtype,
Payload: payload,
}
}
// MarshalBinary returns the byte sequence generated from a Header instance.
func (h *Header) MarshalBinary() ([]byte, error) {
b := make([]byte, h.MarshalLen())
if err := h.MarshalTo(b); err != nil {
return nil, err
}
return b, nil
}
// MarshalTo puts the byte sequence in the byte array given as b.
func (h *Header) MarshalTo(b []byte) error {
b[0] = uint8(h.Type)
copy(b[1:h.MarshalLen()], h.Payload)
return nil
}
// ParseHeader decodes given byte sequence as a SCCP common header.
func ParseHeader(b []byte) (*Header, error) {
h := &Header{}
if err := h.UnmarshalBinary(b); err != nil {
return nil, err
}
return h, nil
}
// UnmarshalBinary sets the values retrieved from byte sequence in a SCCP common header.
func (h *Header) UnmarshalBinary(b []byte) error {
if len(b) < 2 {
return io.ErrUnexpectedEOF
}
h.Type = MsgType(b[0])
h.Payload = b[1:]
return nil
}
// MarshalLen returns the serial length.
func (h *Header) MarshalLen() int {
return 1 + len(h.Payload)
}
// String returns the SCCP common header values in human readable format.
func (h *Header) String() string {
return fmt.Sprintf("{Type: %d, Payload: %x}",
h.Type,
h.Payload,
)
}