package socket
import (
"context"
"github.com/tmc/go-iroh/netaddr"
)
type CustomDatagram struct {
Remote netaddr .CustomAddr
Local netaddr .CustomAddr
HasLocal bool
Data []byte
}
type Packet struct {
Remote netaddr .CustomAddr
Local netaddr .CustomAddr
HasLocal bool
Data []byte
Free func ()
}
type CustomTransport interface {
Serve (ctx context .Context , recv func (CustomDatagram ) bool )
Send (remote netaddr .CustomAddr , local *netaddr .CustomAddr , p []byte ) bool
}
type PacketTransport interface {
CustomTransport
ServePackets (ctx context .Context , recv func (Packet ) bool )
SendPacket (remote netaddr .CustomAddr , local *netaddr .CustomAddr , p []byte ) bool
}
type customTransport struct {
transport CustomTransport
recvCh chan <- recvBatch
}
func newCustomTransport(t CustomTransport , recvCh chan <- recvBatch ) *customTransport {
return &customTransport {transport : t , recvCh : recvCh }
}
func (t *customTransport ) Serve (ctx context .Context ) {
if p , ok := t .transport .(PacketTransport ); ok {
t .servePackets (ctx , p )
return
}
t .transport .Serve (ctx , func (d CustomDatagram ) bool {
data := make ([]byte , len (d .Data ))
copy (data , d .Data )
select {
case t .recvCh <- recvBatch {
data : data ,
info : RecvInfo {Remote : CustomAddr (d .Remote ), Local : d .Local , HasLocal : d .HasLocal },
}:
return true
case <- ctx .Done ():
return false
default :
return false
}
})
}
func (t *customTransport ) servePackets (ctx context .Context , p PacketTransport ) {
p .ServePackets (ctx , func (pkt Packet ) bool {
select {
case t .recvCh <- recvBatch {
data : pkt .Data ,
info : RecvInfo {Remote : CustomAddr (pkt .Remote ), Local : pkt .Local , HasLocal : pkt .HasLocal },
releaseFn : pkt .Free ,
}:
return true
case <- ctx .Done ():
if pkt .Free != nil {
pkt .Free ()
}
return false
default :
if pkt .Free != nil {
pkt .Free ()
}
return false
}
})
}
func (t *customTransport ) Send (remote netaddr .CustomAddr , local *netaddr .CustomAddr , p []byte ) bool {
if pt , ok := t .transport .(PacketTransport ); ok {
return pt .SendPacket (remote , local , p )
}
data := make ([]byte , len (p ))
copy (data , p )
return t .transport .Send (remote , local , data )
}
The pages are generated with Golds v0.8.4 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .