github.com/anacrolix/torrent@v1.61.0/metainfo/nodes.go (about)

     1  package metainfo
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"strconv"
     7  
     8  	"github.com/anacrolix/torrent/bencode"
     9  )
    10  
    11  type Node string
    12  
    13  var _ bencode.Unmarshaler = (*Node)(nil)
    14  
    15  func (n *Node) UnmarshalBencode(b []byte) (err error) {
    16  	var iface interface{}
    17  	err = bencode.Unmarshal(b, &iface)
    18  	if err != nil {
    19  		return
    20  	}
    21  	switch v := iface.(type) {
    22  	case string:
    23  		*n = Node(v)
    24  	case []interface{}:
    25  		func() {
    26  			defer func() {
    27  				r := recover()
    28  				if r != nil {
    29  					err = r.(error)
    30  				}
    31  			}()
    32  			*n = Node(net.JoinHostPort(v[0].(string), strconv.FormatInt(v[1].(int64), 10)))
    33  		}()
    34  	default:
    35  		err = fmt.Errorf("unsupported type: %T", iface)
    36  	}
    37  	return
    38  }