]> Sergey Matveev's repositories - btrtrc.git/blob - ltep.go
CI adjustments
[btrtrc.git] / ltep.go
1 package torrent
2
3 import (
4         "fmt"
5         "slices"
6
7         g "github.com/anacrolix/generics"
8         pp "github.com/anacrolix/torrent/peer_protocol"
9 )
10
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.
19         NumBuiltin int
20 }
21
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))
26                 if old.Ok {
27                         panic(fmt.Sprintf("extension %q already defined with id %v", name, old.Value))
28                 }
29         }
30         return
31 }
32
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) {
37         if id == 0 {
38                 err = fmt.Errorf("extension ID 0 is handshake")
39                 builtin = true
40                 return
41         }
42         protocolIndex := int(id - 1)
43         if protocolIndex >= len(me.Index) {
44                 err = fmt.Errorf("unexpected extended message ID: %v", id)
45                 return
46         }
47         builtin = protocolIndex < me.NumBuiltin
48         name = me.Index[protocolIndex]
49         return
50 }
51
52 func (me *LocalLtepProtocolMap) builtin() []pp.ExtensionName {
53         return me.Index[:me.NumBuiltin]
54 }
55
56 func (me *LocalLtepProtocolMap) user() []pp.ExtensionName {
57         return me.Index[me.NumBuiltin:]
58 }
59
60 func (me *LocalLtepProtocolMap) AddUserProtocol(name pp.ExtensionName) {
61         builtin := slices.DeleteFunc(me.builtin(), func(delName pp.ExtensionName) bool {
62                 return delName == name
63         })
64         user := slices.DeleteFunc(me.user(), func(delName pp.ExtensionName) bool {
65                 return delName == name
66         })
67         me.Index = append(append(builtin, user...), name)
68         me.NumBuiltin = len(builtin)
69 }