// Copyright (C) 2016-2021  Nexedi SA and Contributors.
//                          Kirill Smelkov <kirr@nexedi.com>
//
// This program is free software: you can Use, Study, Modify and Redistribute
// it under the terms of the GNU General Public License version 3, or (at your
// option) any later version, as published by the Free Software Foundation.
//
// You can also Link and Combine this program with other software covered by
// the terms of any of the Free Software licenses or any of the Open Source
// Initiative approved licenses and Convey the resulting work. Corresponding
// source of such a combination shall include the source code for all other
// software used.
//
// This program is distributed WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
// See COPYING file for full licensing terms.
// See https://www.nexedi.com/licensing for rationale and options.

package neonet
// packets and packet buffers management

import (
	"fmt"
	"reflect"
	"sync"
	"unsafe"

	"lab.nexedi.com/kirr/go123/xbytes"

	"lab.nexedi.com/kirr/neo/go/neo/proto"
)

// pktBuf is a buffer with full raw packet (header + payload).
//
// Allocate pktBuf via pktAlloc() and free via pktBuf.Free().
type pktBuf struct {
	data []byte // whole packet data including all headers
}

// HeaderN returns pointer to packet header in 'N'-encoding.
func (pkt *pktBuf) HeaderN() *proto.PktHeaderN {
	// NOTE no need to check len(.data) < PktHeaderN:
	// .data is always allocated with cap >= PktHeaderLenN.
	return (*proto.PktHeaderN)(unsafe.Pointer(&pkt.data[0]))
}

// PayloadN returns []byte representing packet payload in 'N'-encoding.
func (pkt *pktBuf) PayloadN() []byte {
	return pkt.data[proto.PktHeaderLenN:]
}

// ---- pktBuf freelist ----

// pktBufPool is sync.Pool<pktBuf>.
var pktBufPool = sync.Pool{New: func() interface{} {
	return &pktBuf{data: make([]byte, 0, 4096)}
}}

// pktAlloc allocates pktBuf with len=n.
func pktAlloc(n int) *pktBuf {
	// make sure cap >= PktHeaderLenN.
	// see HeaderN for why
	l := n
	if l < proto.PktHeaderLenN {
		l = proto.PktHeaderLenN
	}
	pkt := pktBufPool.Get().(*pktBuf)
	pkt.data = xbytes.Realloc(pkt.data, l)[:n]
	return pkt
}

// Free marks pkt as no longer needed.
func (pkt *pktBuf) Free() {
	pktBufPool.Put(pkt)
}


// ---- pktBuf dump ----

// pktString dumps a packet in human-readable form.
func pktString(e proto.Encoding, pkt *pktBuf) string {
	connID, msgCode, payload, err := pktDecodeHead(e, pkt)
	if err != nil {
		return fmt.Sprintf("(%s) % x", err, pkt.data)
	}

	s := fmt.Sprintf(".%d", connID)

	msgType := proto.MsgType(msgCode)
	if msgType == nil {
		s += fmt.Sprintf(" ? (%d) [%d]: % x", msgCode, len(payload), payload)
		return s
	}

	// XXX dup wrt Conn.Recv
	msg := reflect.New(msgType).Interface().(proto.Msg)
	n, err := e.MsgDecode(msg, payload)
	if err != nil {
		s += fmt.Sprintf(" (%s) %v; [%d]: % x", msgType.Name(), err, len(payload), payload)
	} else {
		s += fmt.Sprintf(" %s %v", msgType.Name(), msg) // XXX or %+v better?

		if n < len(payload) {
			tail := payload[n:]
			s += fmt.Sprintf(" ;  [%d]tail: % x", len(tail), tail)
		}
	}

	return s
}
