summaryrefslogtreecommitdiffstats
path: root/src/cmd/compile/internal/inline/inlheur/serialize.go
blob: d650626679e7874da8b2f64bfbaba46b5e01f023 (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
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package inlheur

import "strings"

func (funcProps *FuncProps) SerializeToString() string {
	if funcProps == nil {
		return ""
	}
	var sb strings.Builder
	writeUleb128(&sb, uint64(funcProps.Flags))
	writeUleb128(&sb, uint64(len(funcProps.ParamFlags)))
	for _, pf := range funcProps.ParamFlags {
		writeUleb128(&sb, uint64(pf))
	}
	writeUleb128(&sb, uint64(len(funcProps.ResultFlags)))
	for _, rf := range funcProps.ResultFlags {
		writeUleb128(&sb, uint64(rf))
	}
	return sb.String()
}

func DeserializeFromString(s string) *FuncProps {
	if len(s) == 0 {
		return nil
	}
	var funcProps FuncProps
	var v uint64
	sl := []byte(s)
	v, sl = readULEB128(sl)
	funcProps.Flags = FuncPropBits(v)
	v, sl = readULEB128(sl)
	funcProps.ParamFlags = make([]ParamPropBits, v)
	for i := range funcProps.ParamFlags {
		v, sl = readULEB128(sl)
		funcProps.ParamFlags[i] = ParamPropBits(v)
	}
	v, sl = readULEB128(sl)
	funcProps.ResultFlags = make([]ResultPropBits, v)
	for i := range funcProps.ResultFlags {
		v, sl = readULEB128(sl)
		funcProps.ResultFlags[i] = ResultPropBits(v)
	}
	return &funcProps
}

func readULEB128(sl []byte) (value uint64, rsl []byte) {
	var shift uint

	for {
		b := sl[0]
		sl = sl[1:]
		value |= (uint64(b&0x7F) << shift)
		if b&0x80 == 0 {
			break
		}
		shift += 7
	}
	return value, sl
}

func writeUleb128(sb *strings.Builder, v uint64) {
	if v < 128 {
		sb.WriteByte(uint8(v))
		return
	}
	more := true
	for more {
		c := uint8(v & 0x7f)
		v >>= 7
		more = v != 0
		if more {
			c |= 0x80
		}
		sb.WriteByte(c)
	}
}