Skip to content

Commit eaa6692

Browse files
committed
Update example
1 parent d301516 commit eaa6692

File tree

1 file changed

+32
-28
lines changed
  • examples/singleapp/utf8_byte_count

1 file changed

+32
-28
lines changed

examples/singleapp/utf8_byte_count/main.go

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package main
22

33
import (
44
"flag"
5+
"fmt"
56
"unicode/utf8"
67

78
"github.com/devlights/gomy/output"
@@ -13,6 +14,7 @@ func main() {
1314
)
1415

1516
flag.Parse()
17+
1618
if err := run(*u); err != nil {
1719
panic(err)
1820
}
@@ -38,33 +40,23 @@ func run(runeMode bool) error {
3840
)
3941

4042
if runeMode {
41-
fn = userune
43+
fn = useRune
4244
}
4345

4446
for _, v := range strs {
4547
output.Stdoutf("", "[%s]", v)
4648
output.StdoutHr()
47-
fn(v)
49+
50+
if err := fn(v); err != nil {
51+
return err
52+
}
4853
}
4954

5055
return nil
5156
}
5257

53-
func userune(s string) {
54-
//lint:ignore S1029 It's ok because this is just a example.
55-
//lint:ignore SA6003 It's ok because this is just a example.
56-
for _, r := range []rune(s) {
57-
58-
if r == rune(' ') {
59-
output.StderrHr()
60-
continue
61-
}
62-
63-
output.Stdoutf("[byte-count]", "%c (%d)\n", r, utf8.RuneLen(r))
64-
}
65-
}
58+
func manual(s string) error {
6659

67-
func manual(s string) {
6860
for i := 0; i < len(s); {
6961
var (
7062
b = s[i]
@@ -84,10 +76,10 @@ func manual(s string) {
8476
//
8577
// 以下の case は上記を判定している.
8678
//
87-
// - (b & 0x80) == 0: 最上位ビットが0なら、この文字は1バイト
88-
// - (b & 0xE0) == 0xC0: 最上位2ビットが110なら、この文字は2バイト
89-
// - (b & 0xF0) == 0xE0: 最上位3ビットが1110なら、この文字は3バイト
90-
// - (b & 0xF8) == 0xF0: 最上位4ビットが11110なら、この文字は4バイト
79+
// - (b & 0x80) == 0 : 最上位1ビットが0 であるなら、この文字は1バイト
80+
// - (b & 0xE0) == 0xC0: 最上位2ビットが110 であるなら、この文字は2バイト
81+
// - (b & 0xF0) == 0xE0: 最上位3ビットが1110 であるなら、この文字は3バイト
82+
// - (b & 0xF8) == 0xF0: 最上位4ビットが11110であるなら、この文字は4バイト
9183
//
9284
// REFERENCES:
9385
// - https://ja.wikipedia.org/wiki/UTF-8
@@ -101,17 +93,29 @@ func manual(s string) {
10193
l = 3
10294
case (b & 0xF8) == 0xF0:
10395
l = 4
96+
default:
97+
return fmt.Errorf("invalid utf-8 char (%b)", b)
10498
}
10599

106-
func() {
107-
defer func() { i += l }()
100+
output.Stdoutf("[byte-count]", "%s (%d)\n", s[i:i+l], l)
108101

109-
if b == ' ' {
110-
output.StdoutHr()
111-
return
112-
}
102+
i += l
103+
}
104+
105+
return nil
106+
}
113107

114-
output.Stdoutf("[byte-count]", "%s (%d)\n", s[i:i+l], l)
115-
}()
108+
func useRune(s string) error {
109+
//lint:ignore S1029 It's ok because this is just a example.
110+
//lint:ignore SA6003 It's ok because this is just a example.
111+
for _, r := range []rune(s) {
112+
l := utf8.RuneLen(r)
113+
if l == -1 {
114+
return fmt.Errorf("invalid utf-8 char (%c)", r)
115+
}
116+
117+
output.Stdoutf("[byte-count]", "%c (%d)\n", r, l)
116118
}
119+
120+
return nil
117121
}

0 commit comments

Comments
 (0)