Browse code

pkg/units: Refactor regexp.Compile to init()

No need to recompile a fixed regular expression each time the function
executes. Abstracting it to the `init()` method.

Docker-DCO-1.1-Signed-off-by: Francisco Carriedo <fcarriedo@gmail.com> (github: fcarriedo)

Francisco Carriedo authored on 2014/07/22 15:50:27
Showing 1 changed files
... ...
@@ -7,6 +7,15 @@ import (
7 7
 	"strings"
8 8
 )
9 9
 
10
+var sizeRegex *regexp.Regexp
11
+
12
+func init() {
13
+	var err error
14
+	if sizeRegex, err = regexp.Compile("^(\\d+)([kKmMgGtTpP])?[bB]?$"); err != nil {
15
+		panic("Failed to compile the 'size' regular expression")
16
+	}
17
+}
18
+
10 19
 // HumanSize returns a human-readable approximation of a size
11 20
 // using SI standard (eg. "44kB", "17MB")
12 21
 func HumanSize(size int64) string {
... ...
@@ -24,12 +33,7 @@ func HumanSize(size int64) string {
24 24
 // FromHumanSize returns an integer from a human-readable specification of a size
25 25
 // using SI standard (eg. "44kB", "17MB")
26 26
 func FromHumanSize(size string) (int64, error) {
27
-	re, err := regexp.Compile("^(\\d+)([kKmMgGtTpP])?[bB]?$")
28
-	if err != nil {
29
-		return -1, fmt.Errorf("%s does not specify not a size", size)
30
-	}
31
-
32
-	matches := re.FindStringSubmatch(size)
27
+	matches := sizeRegex.FindStringSubmatch(size)
33 28
 
34 29
 	if len(matches) != 3 {
35 30
 		return -1, fmt.Errorf("Invalid size: '%s'", size)
... ...
@@ -63,12 +67,7 @@ func FromHumanSize(size string) (int64, error) {
63 63
 // returns the number of bytes, or -1 if the string is unparseable.
64 64
 // Units are case-insensitive, and the 'b' suffix is optional.
65 65
 func RAMInBytes(size string) (int64, error) {
66
-	re, err := regexp.Compile("^(\\d+)([kKmMgGtTpP])?[bB]?$")
67
-	if err != nil {
68
-		return -1, err
69
-	}
70
-
71
-	matches := re.FindStringSubmatch(size)
66
+	matches := sizeRegex.FindStringSubmatch(size)
72 67
 
73 68
 	if len(matches) != 3 {
74 69
 		return -1, fmt.Errorf("Invalid size: '%s'", size)