From 0980ea64a012b31c12f89ab1c226fc805bbabf70 Mon Sep 17 00:00:00 2001 From: Will Norris Date: Sun, 25 Jan 2015 00:30:15 -0800 Subject: [PATCH] define constants for option strings this prevents extra allocations in ParseOptions and cleans up the code a bit, but doesn't actually improve performance in any meaningful way. --- data.go | 35 +++++++++++++++++++++++------------ data_test.go | 5 +++++ 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/data.go b/data.go index 894a592..59121bf 100644 --- a/data.go +++ b/data.go @@ -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 @@ -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() } @@ -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) } diff --git a/data_test.go b/data_test.go index cedc41d..4e4b4b4 100644 --- a/data_test.go +++ b/data_test.go @@ -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 { @@ -48,6 +52,7 @@ func TestParseOptions(t *testing.T) { }{ {"", emptyOptions}, {"x", emptyOptions}, + {"r", emptyOptions}, {"0", emptyOptions}, {",,,,", emptyOptions},