package base

import (
	"bytes"
	"encoding/binary"
	"github.com/panjf2000/gnet"
	log "github.com/sirupsen/logrus"
)

type TcpCodec struct {
}

func (pc *TcpCodec) Encode(c gnet.Conn, buf []byte) (out []byte, err error) {
	rs := make([]byte, 4)
	binary.LittleEndian.PutUint32(rs, uint32(len(buf)))
	out = bytes.Join([][]byte{rs, buf}, []byte(""))
	return
}

func (pc *TcpCodec) Decode(c gnet.Conn) (out []byte, err error) {

	log.Info("收到了消息", c.Read())

	//	c.AsyncWrite(out)
	//读取前四个字节 size int, buf []byte
	rs, bs := c.ReadN(4)
	if rs != 4 {
		return
	}
	//
	ts := int(binary.LittleEndian.Uint32(bs)) + rs
	size, buf := c.ReadN(ts)
	if size != ts {
		return
	}

	c.ShiftN(size)
	out = buf[4:]
	return
}
