aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/jackc/pgx/v5/internal/nbconn/bufferqueue.go
blob: 4bf25481c5b00159de16c6dcf4fd6665278cebfd (plain) (blame)
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
package nbconn

import (
	"sync"
)

const minBufferQueueLen = 8

type bufferQueue struct {
	lock  sync.Mutex
	queue []*[]byte
	r, w  int
}

func (bq *bufferQueue) pushBack(buf *[]byte) {
	bq.lock.Lock()
	defer bq.lock.Unlock()

	if bq.w >= len(bq.queue) {
		bq.growQueue()
	}
	bq.queue[bq.w] = buf
	bq.w++
}

func (bq *bufferQueue) pushFront(buf *[]byte) {
	bq.lock.Lock()
	defer bq.lock.Unlock()

	if bq.w >= len(bq.queue) {
		bq.growQueue()
	}
	copy(bq.queue[bq.r+1:bq.w+1], bq.queue[bq.r:bq.w])
	bq.queue[bq.r] = buf
	bq.w++
}

func (bq *bufferQueue) popFront() *[]byte {
	bq.lock.Lock()
	defer bq.lock.Unlock()

	if bq.r == bq.w {
		return nil
	}

	buf := bq.queue[bq.r]
	bq.queue[bq.r] = nil // Clear reference so it can be garbage collected.
	bq.r++

	if bq.r == bq.w {
		bq.r = 0
		bq.w = 0
		if len(bq.queue) > minBufferQueueLen {
			bq.queue = make([]*[]byte, minBufferQueueLen)
		}
	}

	return buf
}

func (bq *bufferQueue) growQueue() {
	desiredLen := (len(bq.queue) + 1) * 3 / 2
	if desiredLen < minBufferQueueLen {
		desiredLen = minBufferQueueLen
	}

	newQueue := make([]*[]byte, desiredLen)
	copy(newQueue, bq.queue)
	bq.queue = newQueue
}