-
Notifications
You must be signed in to change notification settings - Fork 52
/
unwrapper.go
42 lines (35 loc) · 929 Bytes
/
unwrapper.go
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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package rfc8888
const (
maxSequenceNumberPlusOne = int64(65536)
breakpoint = 32768 // half of max uint16
)
type unwrapper struct {
init bool
lastUnwrapped int64
}
func isNewer(value, previous uint16) bool {
if value-previous == breakpoint {
return value > previous
}
return value != previous && (value-previous) < breakpoint
}
func (u *unwrapper) unwrap(i uint16) int64 {
if !u.init {
u.init = true
u.lastUnwrapped = int64(i)
return u.lastUnwrapped
}
lastWrapped := uint16(u.lastUnwrapped)
delta := int64(i - lastWrapped)
if isNewer(i, lastWrapped) {
if delta < 0 {
delta += maxSequenceNumberPlusOne
}
} else if delta > 0 && u.lastUnwrapped+delta-maxSequenceNumberPlusOne >= 0 {
delta -= maxSequenceNumberPlusOne
}
u.lastUnwrapped += delta
return u.lastUnwrapped
}