Skip to content

Commit

Permalink
feat(count): Add bytes subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
Allaman committed May 20, 2024
1 parent 3cd5990 commit 8cb281c
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
16 changes: 14 additions & 2 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type CLI struct {
Decode decodeBase64Cmd `cmd:"" help:"Decode with base64"`
} `cmd:"" name:"base64" help:"Base64 Encoding and Decoding"`
Count struct {
Bytes countBytesCmd `cmd:"" help:"Count bytes"`
Chars countCharsCmd `cmd:"" help:"Count characters"`
Words countWordsCmd `cmd:"" help:"Count words"`
} `cmd:"" help:"Count various things"`
Expand Down Expand Up @@ -67,6 +68,8 @@ func (c *versionCmd) Run() error {
return nil
}

type countBytesCmd struct{}

type countCharsCmd struct {
Char string `optional:"" short:"c" help:"Count only a specific character"`
}
Expand All @@ -75,6 +78,15 @@ type countWordsCmd struct {
Word string `optional:"" short:"w" help:"Count only a specific word"`
}

func (c *countBytesCmd) Run(globals *Globals) error {
in, err := readFromSTDIN()
if err != nil {
return err
}
printOutput(countBytes(in), globals.Trim)
return nil
}

func (c *countCharsCmd) Run(globals *Globals) error {
in, err := readFromSTDIN()
if err != nil {
Expand All @@ -85,9 +97,9 @@ func (c *countCharsCmd) Run(globals *Globals) error {
if len(runes) > 1 {
return fmt.Errorf("provide only one character")
}
printOutput((countChars(in, rune(runes[0]))), globals.Trim)
printOutput(countChars(in, rune(runes[0])), globals.Trim)
} else {
printOutput((countChars(in)), globals.Trim)
printOutput(countChars(in), globals.Trim)
}
return nil
}
Expand Down
4 changes: 4 additions & 0 deletions count.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import (
"unicode/utf8"
)

func countBytes(s string) int {
return len(s)
}

func countChars(str string, chars ...rune) int {
if len(chars) > 0 {
char := chars[0]
Expand Down
22 changes: 22 additions & 0 deletions count_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,28 @@ import (
"testing"
)

func TestCountBytes(t *testing.T) {
tests := []struct {
input string
expected int
}{
{"Hello, World!", 13},
{"Hello, 世界", 13},
{"", 0},
{"abc", 3},
{"こんにちは", 15}, // 5 characters, 3 bytes each in UTF-8
}

for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result := countBytes(tt.input)
if result != tt.expected {
t.Errorf("countBytes(%q) = %d; want %d", tt.input, result, tt.expected)
}
})
}
}

func TestCountChars(t *testing.T) {
tests := []struct {
input string
Expand Down

0 comments on commit 8cb281c

Please sign in to comment.