This repository has been archived by the owner on Nov 22, 2018. It is now read-only.
/
bitmap.go
103 lines (86 loc) · 1.82 KB
/
bitmap.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
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
103
// Copyright (c) 2011 CZ.NIC z.s.p.o. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// blame: jnml, labs.nic.cz
package rr
import (
"fmt"
"sort"
"strings"
)
// TypesEnccode encodes types into bitmap bits (RFC 4034/4.1.2).
func TypesEncode(types []Type) (bits []byte) {
if len(types) == 0 {
return
}
m := map[int]bool{}
for _, typ := range types {
m[int(typ)] = true
}
v := make([]int, len(m))
i := 0
for typ := range m {
v[i] = typ
i++
}
sort.Ints(v)
first, next := 0, 0
var blockbits [32]byte
for first < len(v) {
window := v[first] >> 8
for next = first + 1; next < len(v); next++ {
if v[next]>>8 != window {
break
}
}
block := v[first:next]
for i := range blockbits[:] {
blockbits[i] = 0
}
for _, typ := range block {
blockbits[(typ&0xFF)>>3] |= (0x80 >> uint(typ&7))
}
last := 31
for ; blockbits[last] == 0; last-- {
}
bits = append(bits, byte(window), byte(last+1))
bits = append(bits, blockbits[:last+1]...)
first = next
}
return
}
// TypesDecode decodes RR Type bitmap bits (RFC 4034/4.1.2).
func TypesDecode(bits []byte) (types []Type, err error) {
p := 0
for p < len(bits) {
window := int(bits[p]) << 8
p++
length := int(bits[p])
p++
next := p + length
if next > len(bits) {
return nil, fmt.Errorf("bitmap decode - buffer underflow")
}
bitmap := bits[p:next]
p = next
for ibyte, octet := range bitmap {
if octet != 0 {
for ibit := 0; ibit < 8; ibit++ {
if octet&0x80 != 0 {
x := window | (ibyte << 3) | ibit
types = append(types, Type(x))
}
octet <<= 1
}
}
}
}
return
}
func TypesString(types []Type) string {
a := []string{}
for _, typ := range types {
a = append(a, typ.String())
}
return strings.Join(a, " ")
}