aboutsummaryrefslogtreecommitdiff
path: root/ber/obj.go
blob: 9b475c7cbf8fcc9c35bcdb6b4e0d72ac88cfcf4b (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
package ber

import (
	"bytes"
	"strconv"
	"strings"
)

type OID []int

func MarshalOID(obj OID) []byte {
	if len(obj) < 2 || obj[0] > 2 {
		return nil
	}
	if obj[0] < 2 && obj[1] > 39 {
		return nil
	}
	buf := bytes.NewBuffer(base128(obj[0]*40 + obj[1]))
	for _, o := range obj[2:] {
		buf.Write(base128(o))
	}
	return buf.Bytes()
}

func (o OID) Marshal() ([]byte, error) {
	return MarshalOID(o), nil
}

func UnmarshalOID(b []byte) (o OID) {
	if len(b) < 1 {
		return
	}
	v, n := debase128(b)
	if v < 80 {
		o = OID{v / 40, v % 40}
	} else {
		o = OID{2, v - 80}
	}

	for i := n; i < len(b); i += n {
		v, n = debase128(b[i:])
		o = append(o, v)
	}
	return
}

func (o OID) String() string {
	s := make([]string, len(o))
	for i, v := range o {
		s[i] = strconv.Itoa(v)
	}
	return strings.Join(s, ".")
}

func (o OID) Equal(a OID) bool {
	if len(o) != len(a) {
		return false
	}
	for i := 0; i < len(o); i++ {
		if o[i] != a[i] {
			return false
		}
	}
	return true
}