aboutsummaryrefslogtreecommitdiff
path: root/nexgb/xgbgen/go_list.go
blob: a95ba71fbecd713a9a8191e9de569d052a671696 (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
package main

import (
	"fmt"
	"log"
)

// List fields
func (f *ListField) Define(c *Context) {
	c.Putln("%s []%s // size: %s",
		f.SrcName(), f.Type.SrcName(), f.Size())
}

func (f *ListField) Read(c *Context) {
	switch t := f.Type.(type) {
	case *Resource:
		length := f.LengthExpr.Reduce("v.", "")
		c.Putln("v.%s = make([]Id, %s)", f.SrcName(), length)
		c.Putln("for i := 0; i < %s; i++ {", length)
		ReadSimpleSingleField(c, fmt.Sprintf("v.%s[i]", f.SrcName()), t)
		c.Putln("}")
		c.Putln("b = pad(b)")
	case *Base:
		length := f.LengthExpr.Reduce("v.", "")
		c.Putln("v.%s = make([]%s, %s)", f.SrcName(), t.SrcName(), length)
		if t.SrcName() == "byte" {
			c.Putln("copy(v.%s[:%s], buf[b:])", f.SrcName(), length)
			c.Putln("b += pad(%s)", length)
		} else {
			c.Putln("for i := 0; i < %s; i++ {", length)
			ReadSimpleSingleField(c, fmt.Sprintf("v.%s[i]", f.SrcName()), t)
			c.Putln("}")
			c.Putln("b = pad(b)")
		}
	case *Union:
		c.Putln("v.%s = make([]%s, %s)",
			f.SrcName(), t.SrcName(), f.LengthExpr.Reduce("v.", ""))
		c.Putln("b += Read%sList(buf[b:], v.%s)", t.SrcName(), f.SrcName())
	case *Struct:
		c.Putln("v.%s = make([]%s, %s)",
			f.SrcName(), t.SrcName(), f.LengthExpr.Reduce("v.", ""))
		c.Putln("b += Read%sList(buf[b:], v.%s)", t.SrcName(), f.SrcName())
	default:
		log.Fatalf("Cannot read list field '%s' with %T type.",
			f.XmlName(), f.Type)
	}
}

func (f *ListField) Write(c *Context) {
	switch t := f.Type.(type) {
	case *Resource:
		length := f.LengthExpr.Reduce("v.", "")
		c.Putln("for i := 0; i < %s; i++", length)
		WriteSimpleSingleField(c, fmt.Sprintf("v.%s[i]", f.SrcName()), t)
		c.Putln("}")
		c.Putln("b = pad(b)")
	case *Base:
		length := f.LengthExpr.Reduce("v.", "")
		if t.SrcName() == "byte" {
			c.Putln("copy(buf[b:], v.%s[:%s])", f.SrcName(), length)
			c.Putln("b += pad(%s)", length)
		} else {
			c.Putln("for i := 0; i < %s; i++ {", length)
			WriteSimpleSingleField(c, fmt.Sprintf("v.%s[i]", f.SrcName()), t)
			c.Putln("}")
			c.Putln("b = pad(b)")
		}
	case *Union:
		c.Putln("b += %sListBytes(buf[b:], v.%s)", t.SrcName(), f.SrcName())
	case *Struct:
		c.Putln("b += %sListBytes(buf[b:], v.%s)", t.SrcName(), f.SrcName())
	default:
		log.Fatalf("Cannot read list field '%s' with %T type.",
			f.XmlName(), f.Type)
	}
}