aboutsummaryrefslogtreecommitdiffstats
path: root/packet/command/move/move.go
blob: d52bb27ccb5084a30d09949853016bcbba4ae272 (plain) (blame)
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
73
74
75
76
77
78
79
package move

import (
	"slices"

	"github.com/osm/quake/common/buffer"
	"github.com/osm/quake/common/context"
	"github.com/osm/quake/common/crc"
	"github.com/osm/quake/packet/command/deltausercommand"
	"github.com/osm/quake/protocol"
)

type Command struct {
	Checksum byte
	Lossage  byte
	Null     *deltausercommand.Command
	Old      *deltausercommand.Command
	New      *deltausercommand.Command
}

func (cmd *Command) Bytes() []byte {
	buf := buffer.New()

	buf.PutByte(protocol.CLCMove)
	buf.PutByte(cmd.Checksum)
	buf.PutByte(cmd.Lossage)

	if cmd.Null != nil {
		buf.PutBytes(cmd.Null.Bytes())
	}

	if cmd.Old != nil {
		buf.PutBytes(cmd.Old.Bytes())
	}

	if cmd.New != nil {
		buf.PutBytes(cmd.New.Bytes())
	}

	return buf.Bytes()
}

func (cmd *Command) GetChecksum(sequence uint32) byte {
	b := slices.Concat(
		[]byte{cmd.Lossage},
		cmd.Null.Bytes(),
		cmd.Old.Bytes(),
		cmd.New.Bytes(),
	)

	return crc.Byte(b, int(sequence))
}

func Parse(ctx *context.Context, buf *buffer.Buffer) (*Command, error) {
	var err error
	var cmd Command

	if cmd.Checksum, err = buf.ReadByte(); err != nil {
		return nil, err
	}

	if cmd.Lossage, err = buf.ReadByte(); err != nil {
		return nil, err
	}

	if cmd.Null, err = deltausercommand.Parse(ctx, buf); err != nil {
		return nil, err
	}

	if cmd.Old, err = deltausercommand.Parse(ctx, buf); err != nil {
		return nil, err
	}

	if cmd.New, err = deltausercommand.Parse(ctx, buf); err != nil {
		return nil, err
	}

	return &cmd, nil
}