-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
padding.go
127 lines (116 loc) · 2.27 KB
/
padding.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package util
import (
"math"
"strings"
"unicode"
"unicode/utf8"
)
const (
// AlignLeft align left
AlignLeft = 0
// AlignCenter align center
AlignCenter = 1
// AlignRight align right
AlignRight = 2
)
// Pad give a pad
func Pad(s, pad string, width int, align int) string {
switch align {
case AlignCenter:
return PadCenter(s, pad, width)
case AlignRight:
return PadLeft(s, pad, width)
default:
return PadRight(s, pad, width)
}
}
// PadRight pas as right
func PadRight(s, pad string, width int) string {
gap := widthValue(s, width)
if gap > 0 {
return s + strings.Repeat(string(pad), gap)
}
return s
}
// PadLeft pad as left
func PadLeft(s, pad string, width int) string {
gap := widthValue(s, width)
if gap > 0 {
return strings.Repeat(string(pad), gap) + s
}
return s
}
// PadCenter pad as center
func PadCenter(s, pad string, width int) string {
gap := widthValue(s, width)
if gap > 0 {
gapLeft := int(math.Ceil(float64(gap / 2)))
gapRight := gap - gapLeft
return strings.Repeat(string(pad), gapLeft) + s + strings.Repeat(string(pad), gapRight)
}
return s
}
func isHan(s string) (isHan bool) {
wh := []rune(s)
for _, r := range wh {
if unicode.Is(unicode.Han, r) {
isHan = true
} else if unicode.Is(unicode.Hiragana, r) {
isHan = true
} else if unicode.Is(unicode.Katakana, r) {
isHan = true
} else if unicode.Is(unicode.Common, r) {
isHan = true
} else {
isHan = false
break
}
}
return
}
func countCN(s string) (count int) {
wh := []rune(s)
for _, r := range wh {
if unicode.Is(unicode.Han, r) {
count++
} else if unicode.Is(unicode.Hiragana, r) {
count++
} else if unicode.Is(unicode.Katakana, r) {
count++
} else if unicode.Is(unicode.Common, r) && len(string(r)) != 1 {
count++
}
}
return
}
func widthValue(s string, width int) (gap int) {
l := utf8.RuneCountInString(s)
ln := len(s)
isHan := isHan(s)
count := countCN(s)
if ln != l {
if isHan {
gap = width - (ln - l)
} else {
gap = width - (ln - count)
}
} else {
gap = width - l
}
return
}
// Lenf counts the number
func Lenf(han string) (l int) {
ln := len(han)
l = utf8.RuneCountInString(han)
isHan := isHan(han)
count := countCN(han)
if ln != l {
if isHan {
l = ln - l
} else {
l = ln - count
}
}
return
}