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

func (s *state) unmarshalLen() int {
	b, _ := s.ReadByte()
	if b&0x80 == 0 {
		return int(b)
	}
	var n int
	for i, v := range s.Next(int(b)) {
		n |= int(v) << uint(i*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 {
	var bs BitString
	b := s.next()
	pad := int(b[0])
	l := (len(b)-1)*8 - pad
	for i := 0; i < l; i++ {
		x := 1 + i/8
		y := 7 - uint(i%8)
		bs = append(bs, b[x]&(1<<y) != 0)
	}
	return bs
}