Skip to content

Commit

Permalink
define constants for option strings
Browse files Browse the repository at this point in the history
this prevents extra allocations in ParseOptions and cleans up the code a
bit, but doesn't actually improve performance in any meaningful way.
  • Loading branch information
willnorris committed Jan 25, 2015
1 parent c796337 commit 0980ea6
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 12 deletions.
35 changes: 23 additions & 12 deletions data.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ import (
"strings"
)

const (
optFit = "fit"
optFlipVertical = "fv"
optFlipHorizontal = "fh"
optRotatePrefix = "r"
optSizeDelimiter = "x"
)

// URLError reports a malformed URL error.
type URLError struct {
Message string
Expand Down Expand Up @@ -55,18 +63,18 @@ var emptyOptions = Options{}

func (o Options) String() string {
buf := new(bytes.Buffer)
fmt.Fprintf(buf, "%vx%v", o.Width, o.Height)
fmt.Fprintf(buf, "%v%s%v", o.Width, optSizeDelimiter, o.Height)
if o.Fit {
buf.WriteString(",fit")
fmt.Fprintf(buf, ",%s", optFit)
}
if o.Rotate != 0 {
fmt.Fprintf(buf, ",r%d", o.Rotate)
fmt.Fprintf(buf, ",%s%d", string(optRotatePrefix), o.Rotate)
}
if o.FlipVertical {
buf.WriteString(",fv")
fmt.Fprintf(buf, ",%s", optFlipVertical)
}
if o.FlipHorizontal {
buf.WriteString(",fh")
fmt.Fprintf(buf, ",%s", optFlipHorizontal)
}
return buf.String()
}
Expand Down Expand Up @@ -127,16 +135,19 @@ func ParseOptions(str string) Options {

for _, opt := range strings.Split(str, ",") {
switch {
case opt == "fit":
case len(opt) == 0:
break
case opt == optFit:
options.Fit = true
case opt == "fv":
case opt == optFlipVertical:
options.FlipVertical = true
case opt == "fh":
case opt == optFlipHorizontal:
options.FlipHorizontal = true
case len(opt) > 2 && opt[:1] == "r":
options.Rotate, _ = strconv.Atoi(opt[1:])
case strings.ContainsRune(opt, 'x'):
size := strings.SplitN(opt, "x", 2)
case strings.HasPrefix(opt, optRotatePrefix):
value := strings.TrimPrefix(opt, optRotatePrefix)
options.Rotate, _ = strconv.Atoi(value)
case strings.Contains(opt, optSizeDelimiter):
size := strings.SplitN(opt, optSizeDelimiter, 2)
if w := size[0]; w != "" {
options.Width, _ = strconv.ParseFloat(w, 64)
}
Expand Down
5 changes: 5 additions & 0 deletions data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ func TestOptions_String(t *testing.T) {
Options{1, 2, true, 90, true, true},
"1x2,fit,r90,fv,fh",
},
{
Options{0.15, 1.3, false, 45, false, false},
"0.15x1.3,r45",
},
}

for i, tt := range tests {
Expand All @@ -48,6 +52,7 @@ func TestParseOptions(t *testing.T) {
}{
{"", emptyOptions},
{"x", emptyOptions},
{"r", emptyOptions},
{"0", emptyOptions},
{",,,,", emptyOptions},

Expand Down

0 comments on commit 0980ea6

Please sign in to comment.