1package pgproto3
2
3import (
4	"bytes"
5	"encoding/binary"
6	"encoding/json"
7
8	"github.com/jackc/pgx/pgio"
9)
10
11type CopyInResponse struct {
12	OverallFormat     byte
13	ColumnFormatCodes []uint16
14}
15
16func (*CopyInResponse) Backend() {}
17
18func (dst *CopyInResponse) Decode(src []byte) error {
19	buf := bytes.NewBuffer(src)
20
21	if buf.Len() < 3 {
22		return &invalidMessageFormatErr{messageType: "CopyInResponse"}
23	}
24
25	overallFormat := buf.Next(1)[0]
26
27	columnCount := int(binary.BigEndian.Uint16(buf.Next(2)))
28	if buf.Len() != columnCount*2 {
29		return &invalidMessageFormatErr{messageType: "CopyInResponse"}
30	}
31
32	columnFormatCodes := make([]uint16, columnCount)
33	for i := 0; i < columnCount; i++ {
34		columnFormatCodes[i] = binary.BigEndian.Uint16(buf.Next(2))
35	}
36
37	*dst = CopyInResponse{OverallFormat: overallFormat, ColumnFormatCodes: columnFormatCodes}
38
39	return nil
40}
41
42func (src *CopyInResponse) Encode(dst []byte) []byte {
43	dst = append(dst, 'G')
44	sp := len(dst)
45	dst = pgio.AppendInt32(dst, -1)
46
47	dst = pgio.AppendUint16(dst, uint16(len(src.ColumnFormatCodes)))
48	for _, fc := range src.ColumnFormatCodes {
49		dst = pgio.AppendUint16(dst, fc)
50	}
51
52	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
53
54	return dst
55}
56
57func (src *CopyInResponse) MarshalJSON() ([]byte, error) {
58	return json.Marshal(struct {
59		Type              string
60		ColumnFormatCodes []uint16
61	}{
62		Type:              "CopyInResponse",
63		ColumnFormatCodes: src.ColumnFormatCodes,
64	})
65}
66