aboutsummaryrefslogtreecommitdiff
path: root/ber/unmarshal.go
blob: 350692bec50bbc77a8551bc7acd860ab21d57238 (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
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
package ber

func (s *state) unmarshalLen() int {
	b, _ := s.ReadByte()
	if b&0x80 == 0 {
		return int(b)
	}
	l := int(b) & 0x7f
	var n int
	for i, v := range s.Next(l) {
		n |= int(v) << uint((l-i-1)*8)
	}
	return n
}

func (s *state) unmarshalBase128() int {
	var i int
	for {
		b, err := s.ReadByte()
		if err != nil {
			return i
		}
		i = (i << 7) | int(b&0x7f)
		if b&0x80 == 0 {
			return i
		}
	}
}

func (s *state) unmarshalBool() bool {
	b := s.next()
	return b[0] != 0x00
}

func (s *state) unmarshalInt() int {
	b := s.next()
	neg := b[0]&0x80 != 0
	var i int
	for _, v := range b {
		if neg {
			v = ^v
		}
		i = (i << 8) | int(v)
	}
	if neg {
		i = ^i
	}
	return i
}

func (s *state) unmarshalString() string {
	return string(s.next())
}

func (s *state) unmarshalOID() OID {
	var o OID
	if s.Len() < 2 {
		return o
	}
	buf := s.subState()
	v := buf.unmarshalBase128()
	if v < 80 {
		o = OID{v / 40, v % 40}
	} else {
		o = OID{2, v - 80}
	}
	for buf.Len() > 0 {
		o = append(o, buf.unmarshalBase128())
	}
	return o
}

func (s *state) unmarshalBitString() BitString {
	b := s.next()
	pad := int(b[0])
	l := (len(b)-1)*8 - pad
	bs := make(BitString, l)
	for i := 0; i < l; i++ {
		x := 1 + i/8
		y := 7 - uint(i%8)
		bs[i] = b[x]&(1<<y) != 0
	}
	return bs
}

func (s *state) unmarshalClass() Header {
	b, _ := s.ReadByte()
	tag := Tag(b) & tagMask
	if tag == tagMask {
		tag = Tag(s.unmarshalBase128())
	}
	return Header{
		Class: Class(b) & classMask,
		Kind:  Kind(b) & kindMask,
		Tag:   tag,
	}
}