-
Notifications
You must be signed in to change notification settings - Fork 0
/
style_file.go
63 lines (51 loc) · 1.15 KB
/
style_file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package spritenik
import (
"errors"
"regexp"
"strconv"
"strings"
)
var (
InvalidSubFile = errors.New("invalid sub file")
)
// openapi:strfmt filename
type StyleFile struct {
Type string
Ext string
PixelRatio int
}
func (f *StyleFile) UnmarshalText(text []byte) error {
sf, err := ParseStyleFile(string(text))
if err != nil {
return err
}
*f = *sf
return nil
}
func (f StyleFile) MarshalText() (text []byte, err error) {
return []byte(f.String()), nil
}
func (f StyleFile) String() string {
if f.PixelRatio <= 1 {
return f.Type + f.Ext
}
return f.Type + "@" + strconv.FormatInt(int64(f.PixelRatio), 10) + "x" + f.Ext
}
var reSubFile = regexp.MustCompile(`([^@]+)(@([0-9]+)x)?(\.[A-Za-z0-9]+)$`)
func ParseStyleFile(s string) (*StyleFile, error) {
if !reSubFile.MatchString(s) {
return nil, InvalidSubFile
}
matched := reSubFile.FindAllStringSubmatch(s, -1)
m := &StyleFile{
Type: strings.ToLower(matched[0][1]),
Ext: strings.ToLower(matched[0][4]),
PixelRatio: 1,
}
if matched[0][3] != "" {
if i, err := strconv.ParseInt(matched[0][3], 10, 64); err == nil {
m.PixelRatio = int(i)
}
}
return m, nil
}