-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwidth.go
53 lines (43 loc) · 1.36 KB
/
width.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
// SPDX-FileCopyrightText: 2020-2024 caixw
//
// SPDX-License-Identifier: MIT
package localeutil
import (
"maps"
"golang.org/x/text/width"
)
var defaultWidthOptions = WidthOptions{
width.EastAsianFullwidth: 2,
width.EastAsianWide: 2,
width.EastAsianHalfwidth: 1,
width.EastAsianNarrow: 1,
width.Neutral: 1,
width.EastAsianAmbiguous: 1,
}
// WidthOptions 用于指定各类字符的宽度
//
// 拥有以下几个配置项:
// - [width.EastAsianFullwidth]: 2
// - [width.EastAsianWide]: 2
// - [width.EastAsianHalfwidth]: 1
// - [width.EastAsianNarrow]: 1
// - [width.Neutral]: 1
// - [width.EastAsianAmbiguous]: 1
//
// 对于 [width.EastAsianAmbiguous] 不同的字体可能有不同的设置。
type WidthOptions map[width.Kind]int
// DefaultWidthOptions 返回默认的配置项的副本
//
// 如果要基于默认值作修改,可以采用此方法。
func DefaultWidthOptions() WidthOptions { return maps.Clone(defaultWidthOptions) }
// Width 计算字符串的宽度
func (wo WidthOptions) Width(s string) (w int) {
for _, r := range s {
w += wo[width.LookupRune(r).Kind()]
}
return w
}
// Width 采用 [DefaultWidthOptions] 计算字符串的宽度
//
// 如果有特殊要求,可以使用 [WidthOptions] 自定义各类字符的宽度。
func Width(s string) int { return defaultWidthOptions.Width(s) }