Skip to content

Commit d9f2d3b

Browse files
committed
Update example
1 parent 4980d2c commit d9f2d3b

File tree

2 files changed

+54
-22
lines changed

2 files changed

+54
-22
lines changed

examples/singleapp/utf8-byte-count/Taskfile.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@ version: '3'
55
tasks:
66
default:
77
cmds:
8-
- task: run
9-
run:
8+
- task: run-manual
9+
run-manual:
1010
cmds:
1111
- go run main.go
12+
run-userune:
13+
cmds:
14+
- go run main.go -u
Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,52 @@
11
package main
22

33
import (
4+
"flag"
45
"unicode/utf8"
56

67
"github.com/devlights/gomy/output"
78
)
89

910
func main() {
10-
if err := run(); err != nil {
11+
var (
12+
u = flag.Bool("u", false, "use rune")
13+
)
14+
15+
flag.Parse()
16+
if err := run(*u); err != nil {
1117
panic(err)
1218
}
1319
}
1420

15-
func run() error {
21+
func run(runeMode bool) error {
1622
var (
17-
s = "こんにちは コンニチハ コンニチワ hello"
23+
strs = []string{
24+
// 全角かな
25+
"こんにちは",
26+
// 全角カタカナ
27+
"コンニチハ",
28+
// 半角カタカナ
29+
"コンニチワ",
30+
// 英数字
31+
"golang->60l4n6",
32+
// ©¼½¾
33+
"\U000000A9\U000000BC\U000000BD\U000000BE",
34+
// 🍺🍻🍷🍜
35+
"\U0001F37A\U0001F37B\U0001F377\U0001F35C",
36+
}
37+
fn = manual
1838
)
1939

20-
manual(s)
21-
output.StdoutHr()
22-
userune(s)
40+
if runeMode {
41+
fn = userune
42+
output.Stdoutl("[MODE]", "Use Rune")
43+
}
44+
45+
for _, v := range strs {
46+
output.Stdoutf("", "[%s]", v)
47+
output.StdoutHr()
48+
fn(v)
49+
}
2350

2451
return nil
2552
}
@@ -28,41 +55,43 @@ func userune(s string) {
2855
//lint:ignore S1029 It's ok because this is just a example.
2956
//lint:ignore SA6003 It's ok because this is just a example.
3057
for _, r := range []rune(s) {
31-
l := utf8.RuneLen(r)
3258

3359
if r == rune(' ') {
3460
output.StderrHr()
35-
} else {
36-
output.Stdoutl("[userune][byte-count]", l)
61+
continue
3762
}
63+
64+
output.Stdoutl("[byte-count]", utf8.RuneLen(r))
3865
}
3966
}
4067

4168
func manual(s string) {
4269
for i := 0; i < len(s); {
43-
c := s[i]
44-
4570
//
4671
// UTF-8の先頭バイトを判定し、バイトサイズ算出
4772
//
48-
l := 0
73+
var (
74+
b = s[i]
75+
l = 0
76+
)
77+
4978
switch {
50-
case (c & 0x80) == 0:
79+
case (b & 0x80) == 0:
5180
l = 1
52-
case (c & 0xE0) == 0xC0:
81+
case (b & 0xE0) == 0xC0:
5382
l = 2
54-
case (c & 0xF0) == 0xE0:
83+
case (b & 0xF0) == 0xE0:
5584
l = 3
56-
case (c & 0xF8) == 0xF0:
85+
case (b & 0xF8) == 0xF0:
5786
l = 4
5887
}
5988

60-
if c == ' ' {
89+
i += l
90+
if b == ' ' {
6191
output.StdoutHr()
62-
} else {
63-
output.Stdoutl("[manual][byte-count]", l)
92+
continue
6493
}
6594

66-
i += l
95+
output.Stdoutl("[byte-count]", l)
6796
}
6897
}

0 commit comments

Comments
 (0)