1package pgproto3
2
3import (
4	"bytes"
5	"encoding/json"
6
7	"github.com/jackc/pgx/pgio"
8)
9
10type Close struct {
11	ObjectType byte // 'S' = prepared statement, 'P' = portal
12	Name       string
13}
14
15func (*Close) Frontend() {}
16
17func (dst *Close) Decode(src []byte) error {
18	if len(src) < 2 {
19		return &invalidMessageFormatErr{messageType: "Close"}
20	}
21
22	dst.ObjectType = src[0]
23	rp := 1
24
25	idx := bytes.IndexByte(src[rp:], 0)
26	if idx != len(src[rp:])-1 {
27		return &invalidMessageFormatErr{messageType: "Close"}
28	}
29
30	dst.Name = string(src[rp : len(src)-1])
31
32	return nil
33}
34
35func (src *Close) Encode(dst []byte) []byte {
36	dst = append(dst, 'C')
37	sp := len(dst)
38	dst = pgio.AppendInt32(dst, -1)
39
40	dst = append(dst, src.ObjectType)
41	dst = append(dst, src.Name...)
42	dst = append(dst, 0)
43
44	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
45
46	return dst
47}
48
49func (src *Close) MarshalJSON() ([]byte, error) {
50	return json.Marshal(struct {
51		Type       string
52		ObjectType string
53		Name       string
54	}{
55		Type:       "Close",
56		ObjectType: string(src.ObjectType),
57		Name:       src.Name,
58	})
59}
60