7 g "github.com/anacrolix/generics"
8 pp "github.com/anacrolix/torrent/peer_protocol"
11 type LocalLtepProtocolMap struct {
12 // 1-based mapping from extension number to extension name (subtract one from the extension ID
13 // to find the corresponding protocol name). The first LocalLtepProtocolBuiltinCount of these
14 // are use builtin handlers. If you want to handle builtin protocols yourself, you would move
15 // them above the threshold. You can disable them by removing them entirely, and add your own.
16 // These changes should be done in the PeerConnAdded callback.
17 Index []pp.ExtensionName
18 // How many of the protocols are using the builtin handlers.
22 func (me *LocalLtepProtocolMap) toSupportedExtensionDict() (m map[pp.ExtensionName]pp.ExtensionNumber) {
23 g.MakeMapWithCap(&m, len(me.Index))
24 for i, name := range me.Index {
25 old := g.MapInsert(m, name, pp.ExtensionNumber(i+1))
27 panic(fmt.Sprintf("extension %q already defined with id %v", name, old.Value))
33 // Returns the local extension name for the given ID. If builtin is true, the implementation intends
34 // to handle it itself. For incoming messages with extension ID 0, the message is a handshake, and
35 // should be treated specially.
36 func (me *LocalLtepProtocolMap) LookupId(id pp.ExtensionNumber) (name pp.ExtensionName, builtin bool, err error) {
38 err = fmt.Errorf("extension ID 0 is handshake")
42 protocolIndex := int(id - 1)
43 if protocolIndex >= len(me.Index) {
44 err = fmt.Errorf("unexpected extended message ID: %v", id)
47 builtin = protocolIndex < me.NumBuiltin
48 name = me.Index[protocolIndex]
52 func (me *LocalLtepProtocolMap) builtin() []pp.ExtensionName {
53 return me.Index[:me.NumBuiltin]
56 func (me *LocalLtepProtocolMap) user() []pp.ExtensionName {
57 return me.Index[me.NumBuiltin:]
60 func (me *LocalLtepProtocolMap) AddUserProtocol(name pp.ExtensionName) {
61 builtin := slices.DeleteFunc(me.builtin(), func(delName pp.ExtensionName) bool {
62 return delName == name
64 user := slices.DeleteFunc(me.user(), func(delName pp.ExtensionName) bool {
65 return delName == name
67 me.Index = append(append(builtin, user...), name)
68 me.NumBuiltin = len(builtin)