aboutsummaryrefslogtreecommitdiffstats
path: root/worker/imap/seqmap.go
blob: 093bbc52b50945268d043df6d85d24501aa3758c (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
package imap

import (
	"sync"
)

type SeqMap struct {
	lock sync.Mutex
	// map of IMAP sequence numbers to message UIDs
	m map[uint32]uint32
}

func (s *SeqMap) Size() int {
	s.lock.Lock()
	size := len(s.m)
	s.lock.Unlock()
	return size
}

func (s *SeqMap) Get(seqnum uint32) (uint32, bool) {
	s.lock.Lock()
	uid, found := s.m[seqnum]
	s.lock.Unlock()
	return uid, found
}

func (s *SeqMap) Put(seqnum, uid uint32) {
	s.lock.Lock()
	if s.m == nil {
		s.m = make(map[uint32]uint32)
	}
	s.m[seqnum] = uid
	s.lock.Unlock()
}

func (s *SeqMap) Pop(seqnum uint32) (uint32, bool) {
	s.lock.Lock()
	uid, found := s.m[seqnum]
	if found {
		m := make(map[uint32]uint32)
		for s, u := range s.m {
			if s > seqnum {
				// All sequence numbers greater than the removed one must be decremented by one
				// https://datatracker.ietf.org/doc/html/rfc3501#section-7.4.1
				m[s-1] = u
			} else if s < seqnum {
				m[s] = u
			}
		}
		s.m = m
	}
	s.lock.Unlock()
	return uid, found
}

func (s *SeqMap) Clear() {
	s.lock.Lock()
	s.m = make(map[uint32]uint32)
	s.lock.Unlock()
}