1package pgproto3
2
3import (
4	"bytes"
5	"encoding/binary"
6	"encoding/json"
7
8	"github.com/jackc/pgx/pgio"
9)
10
11type ParameterDescription struct {
12	ParameterOIDs []uint32
13}
14
15func (*ParameterDescription) Backend() {}
16
17func (dst *ParameterDescription) Decode(src []byte) error {
18	buf := bytes.NewBuffer(src)
19
20	if buf.Len() < 2 {
21		return &invalidMessageFormatErr{messageType: "ParameterDescription"}
22	}
23
24	// Reported parameter count will be incorrect when number of args is greater than uint16
25	buf.Next(2)
26	// Instead infer parameter count by remaining size of message
27	parameterCount := buf.Len() / 4
28
29	*dst = ParameterDescription{ParameterOIDs: make([]uint32, parameterCount)}
30
31	for i := 0; i < parameterCount; i++ {
32		dst.ParameterOIDs[i] = binary.BigEndian.Uint32(buf.Next(4))
33	}
34
35	return nil
36}
37
38func (src *ParameterDescription) Encode(dst []byte) []byte {
39	dst = append(dst, 't')
40	sp := len(dst)
41	dst = pgio.AppendInt32(dst, -1)
42
43	dst = pgio.AppendUint16(dst, uint16(len(src.ParameterOIDs)))
44	for _, oid := range src.ParameterOIDs {
45		dst = pgio.AppendUint32(dst, oid)
46	}
47
48	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
49
50	return dst
51}
52
53func (src *ParameterDescription) MarshalJSON() ([]byte, error) {
54	return json.Marshal(struct {
55		Type          string
56		ParameterOIDs []uint32
57	}{
58		Type:          "ParameterDescription",
59		ParameterOIDs: src.ParameterOIDs,
60	})
61}
62