summaryrefslogtreecommitdiffhomepage
path: root/src/index.go
blob: 917851056c358a4c8cf0ebea3d0fb0420964dc67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main

import (
	"crypto/rand"
	"sync"
)

/* Index=0 is reserved for unset indecies
 *
 * TODO: Rethink map[id] -> peer VS map[id] -> handshake and handshake <ref> peer
 *
 */

type IndexTableEntry struct {
	peer      *Peer
	handshake *Handshake
	keyPair   *KeyPair
}

type IndexTable struct {
	mutex sync.RWMutex
	table map[uint32]IndexTableEntry
}

func randUint32() (uint32, error) {
	var buff [4]byte
	_, err := rand.Read(buff[:])
	id := uint32(buff[0])
	id <<= 8
	id |= uint32(buff[1])
	id <<= 8
	id |= uint32(buff[2])
	id <<= 8
	id |= uint32(buff[3])
	return id, err
}

func (table *IndexTable) Init() {
	table.mutex.Lock()
	table.table = make(map[uint32]IndexTableEntry)
	table.mutex.Unlock()
}

func (table *IndexTable) ClearIndex(index uint32) {
	if index == 0 {
		return
	}
	table.mutex.Lock()
	delete(table.table, index)
	table.mutex.Unlock()
}

func (table *IndexTable) Insert(key uint32, value IndexTableEntry) {
	table.mutex.Lock()
	table.table[key] = value
	table.mutex.Unlock()
}

func (table *IndexTable) NewIndex(peer *Peer) (uint32, error) {
	for {
		// generate random index

		index, err := randUint32()
		if err != nil {
			return index, err
		}
		if index == 0 {
			continue
		}

		// check if index used

		table.mutex.RLock()
		_, ok := table.table[index]
		if ok {
			continue
		}
		table.mutex.RUnlock()

		// replace index

		table.mutex.Lock()
		_, found := table.table[index]
		if found {
			table.mutex.Unlock()
			continue
		}
		table.table[index] = IndexTableEntry{
			peer:      peer,
			handshake: &peer.handshake,
			keyPair:   nil,
		}
		table.mutex.Unlock()
		return index, nil
	}
}

func (table *IndexTable) Lookup(id uint32) IndexTableEntry {
	table.mutex.RLock()
	defer table.mutex.RUnlock()
	return table.table[id]
}