// Package encode implements run-length-encoding and decoding functions.
package encode
import (
"log"
"strconv"
"strings"
"unicode"
)
func RunLengthEncode(input string) string {
if input == "" {
return ""
}
var ret strings.Builder
prev := rune(input[0])
count := 0
for i, ch := range input {
if prev == ch {
count++
if i != len(input)-1 {
continue
}
}
if count > 1 {
ret.WriteString(strconv.Itoa(count))
count = 1
}
ret.WriteRune(prev)
if i == len(input)-1 && prev != ch {
ret.WriteRune(ch)
}
prev = ch
}
return ret.String()
}
func RunLengthDecode(input string) string {
var counter strings.Builder
var ret strings.Builder
for i, ch := range input {
if unicode.IsDigit(ch) {
counter.WriteRune(ch)
continue
}
if counter.String() != "" {
c, err := strconv.Atoi(counter.String())
if err != nil {
log.Printf("error converting %q: %s", counter.String(), err)
}
ret.Write([]byte(strings.Repeat(string(input[i]), c)))
counter.Reset()
continue
}
ret.WriteRune(ch)
}
return ret.String()
}