Implemented package specific structs
This commit is contained in:
36
src/types/ByName.go
Normal file
36
src/types/ByName.go
Normal file
@ -0,0 +1,36 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ByName returns the type with the given name or `nil` if it doesn't exist.
|
||||
func ByName(name string, pkg string, structs map[string]*Struct) Type {
|
||||
if strings.HasPrefix(name, "*") {
|
||||
to := strings.TrimPrefix(name, "*")
|
||||
return &Pointer{To: ByName(to, pkg, structs)}
|
||||
}
|
||||
|
||||
switch name {
|
||||
case "Int":
|
||||
return Int
|
||||
case "Int64":
|
||||
return Int64
|
||||
case "Int32":
|
||||
return Int32
|
||||
case "Int16":
|
||||
return Int16
|
||||
case "Int8":
|
||||
return Int8
|
||||
case "Float":
|
||||
return Float
|
||||
case "Float64":
|
||||
return Float64
|
||||
case "Float32":
|
||||
return Float32
|
||||
case "Pointer":
|
||||
return PointerAny
|
||||
}
|
||||
|
||||
return structs[pkg+"."+name]
|
||||
}
|
@ -2,14 +2,20 @@ package types
|
||||
|
||||
// Struct is a structure in memory whose regions are addressable with named fields.
|
||||
type Struct struct {
|
||||
name string
|
||||
fields []*Field
|
||||
size int
|
||||
Package string
|
||||
UniqueName string
|
||||
name string
|
||||
fields []*Field
|
||||
size int
|
||||
}
|
||||
|
||||
// NewStruct creates a new struct.
|
||||
func NewStruct(name string) *Struct {
|
||||
return &Struct{name: name}
|
||||
func NewStruct(pkg string, name string) *Struct {
|
||||
return &Struct{
|
||||
Package: pkg,
|
||||
UniqueName: pkg + "." + name,
|
||||
name: name,
|
||||
}
|
||||
}
|
||||
|
||||
// AddField adds a new field to the end of the struct.
|
||||
@ -39,11 +45,11 @@ func (s *Struct) Size() int {
|
||||
}
|
||||
|
||||
// Update updates the offsets and structure size.
|
||||
func (s *Struct) Update(types map[string]Type) {
|
||||
func (s *Struct) Update(allTypes map[string]*Struct) {
|
||||
s.size = 0
|
||||
|
||||
for _, field := range s.fields {
|
||||
field.Type = types[field.TypeName]
|
||||
field.Type = ByName(field.TypeName, s.Package, allTypes)
|
||||
field.Offset = s.size
|
||||
s.size += field.Type.Size()
|
||||
}
|
||||
|
@ -24,12 +24,12 @@ func TestSize(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStruct(t *testing.T) {
|
||||
s := types.NewStruct("Test")
|
||||
s := types.NewStruct("main", "Test")
|
||||
assert.Equal(t, s.Name(), "Test")
|
||||
assert.Equal(t, s.Size(), 0)
|
||||
field := &types.Field{Name: "TestField", TypeName: "Int8"}
|
||||
s.AddField(field)
|
||||
s.Update(map[string]types.Type{"Int8": types.Int8})
|
||||
s.Update(nil)
|
||||
assert.Equal(t, s.Size(), 1)
|
||||
assert.Equal(t, s.FieldByName("TestField"), field)
|
||||
assert.Nil(t, s.FieldByName("does-not-exist"))
|
||||
|
Reference in New Issue
Block a user