Created
April 30, 2019 03:02
-
-
Save crhntr/33fc77b4a145b5884e8bf9d6effd0847 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
type Element struct { | |
Name string | |
Attributes []Attribute | |
} | |
type Attribute string | |
func (attr Attribute) IsVoid() bool { | |
_, val, qu, _ := attr.split() | |
return val == "" && qu == "" | |
} | |
func (attr Attribute) split() (string, string, string, error) { | |
i := 0 | |
for ; i < len(attr); i++ { | |
if attr[i] == '=' { | |
break | |
} | |
} | |
if i == len(attr) { | |
return string(attr[:i]), "", "", nil | |
} | |
if len(attr[i+1:]) < 2 { | |
return string(attr[:i]), "", "", errors.New("attribute quoting is incorrect") | |
} | |
if (attr[i+1] != '"' && attr[len(attr)-1] != '"') && (attr[i+1] != '\'' && attr[len(attr)-1] != '\'') { | |
if strings.ContainsAny(string(attr), " \t") { | |
return string(attr[:i]), string(attr[i+1:]), "", errors.New("unquoted attribute value must not contain a spaces") | |
} | |
return string(attr[:i]), string(attr[i+1:]), "", nil | |
} | |
return string(attr[:i]), string(attr[i+2 : len(attr)-1]), string(attr[len(attr)-1:]), nil | |
} | |
/* | |
import "testing" | |
func TestAttribute_split(t *testing.T) { | |
if name, val, qu, err := Attribute(`foo="bar"`).split(); name != "foo" || val != "bar" || qu != "\"" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo='bar'`).split(); name != "foo" || val != "bar" || qu != "'" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo`).split(); name != "foo" || val != "" || qu != "" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo=""`).split(); name != "foo" || val != "" || qu != "\"" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo=''`).split(); name != "foo" || val != "" || qu != "'" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo=bar`).split(); name != "foo" || val != "bar" || qu != "" || err != nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if name, val, qu, err := Attribute(`foo=bar baz`).split(); name != "foo" || val != "bar baz" || qu != "" || err == nil { | |
t.Errorf("%q %q %q", name, val, qu) | |
} | |
if _, _, _, err := Attribute(`foo="`).split(); err == nil { | |
t.Errorf("should error") | |
} | |
if _, _, _, err := Attribute(`foo='`).split(); err == nil { | |
t.Errorf("should error") | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment