Skip to content

add marshal for one element in enum #111

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions xsdgen/xsdgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -870,6 +870,11 @@ func (cfg *Config) genSimpleType(t *xsd.SimpleType) ([]spec, error) {
if t.List {
return cfg.genSimpleListSpec(t)
}

if len(t.Restriction.Enum) == 1 {
return cfg.genEnumOneValue(t)
}

if len(t.Union) > 0 {
// We don't support unions because the code that needs
// to be generated to check which of the member types
Expand Down Expand Up @@ -1167,6 +1172,41 @@ func (cfg *Config) genSimpleListSpec(t *xsd.SimpleType) ([]spec, error) {
return []spec{s}, nil
}

// Generate a type declaration for a enum type with one element, along with marshal
// methods.
func (cfg *Config) genEnumOneValue(t *xsd.SimpleType) ([]spec, error) {
cfg.debugf("generating Go source for enum with one element %q", xsd.XMLName(t).Local)

if len(t.Restriction.Enum) != 1 {
return nil, nil
}

expr, err := cfg.expr(t.Base)
if err != nil {
return nil, err
}
s := spec{
doc: t.Doc,
name: cfg.public(t.Name),
expr: expr,
xsdType: t,
}
marshal, err := gen.Func("MarshalText").
Receiver("x *"+s.name).
Returns("[]byte", "error").
Body(`
return []byte("` + t.Restriction.Enum[0] + `"), nil
`).Decl()

if err != nil {
return nil, fmt.Errorf("MarshalText %s: %v", s.name, err)
}

s.methods = append(s.methods, marshal)

return []spec{s}, nil
}

// O(n²) is OK since you'll never see more than ~40 attributes...
// right?
func mergeAttributes(src, base *xsd.ComplexType) []xsd.Attribute {
Expand Down