aboutsummaryrefslogtreecommitdiff
path: root/ber/len.go
blob: 5df82882d38a6a1a740e4fbf78256a2d688be3e5 (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
package ber

import (
	"io"
)

func UnmarshalLen(r io.ByteReader) int {
	b, _ := r.ReadByte()
	if b&0x80 == 0 {
		return int(b)
	}
	n := int(b & 0x7f)
	var i int
	for k := 0; k <= n; k++ {
		b, _ := r.ReadByte()
		i |= int(b) << uint(k*8)
	}
	return i
}

func unmarshalLen(b []byte) (i, n int) {
	if b[0]&0x80 == 0 {
		return int(b[0]), 1
	}
	n = int(b[0] & 0x7f)
	for k := 0; k <= n; k++ {
		i |= int(b[k]) << uint((k-1)*8)
	}
	return i, n + 1
}

func lenLen(i int) (n int) {
	for ; i > 255; i >>= 8 {
		n++
	}
	return n + 1
}

func MarshalLen(w io.ByteWriter, i int) {
	if i < 0x80 {
		w.WriteByte(byte(i))
		return
	}
	n := lenLen(i)
	w.WriteByte(byte(n) | 0x80)
	for ; n > 0; n-- {
		w.WriteByte(byte(i) >> uint(n-1) * 8)
	}
	return
}