Run-Length Encoding Round Trip

Run-length encoding appends each run's count after its byte, and decoding rebuilds the original text only when every count was written back.

GoData Integrity

Code

gosnippet
59 lines
package main

import (
	"fmt"
	"strconv"
)

// run-length encoding: each run is written as the character plus its repeat count
func encode(s string) string {
	if s == "" {
		return ""
	}
	out := make([]byte, 0, len(s))
	count := 1
	for i := 1; i < len(s); i++ {
		if s[i] == s[i-1] {
			count++
			continue
		}
		out = append(out, s[i-1])
		out = append(out, strconv.Itoa(count)...)
		count = 1
	}
	out = append(out, s[len(s)-1])
	out = append(out, strconv.Itoa(count)...)
	return string(out)
}

// round trip: expands runs back to the original; safe only when the input has no digits
func decode(s string) (string, error) {
	var out []byte
	count := 0
	for i := 0; i < len(s); i++ {
		ch := s[i]
		if ch >= '0' && ch <= '9' {
			count = count*10 + int(ch-'0')
			continue
		}
		if count == 0 {
			return "", fmt.Errorf("missing count before %q", ch)
		}
		for j := 0; j < count; j++ {
			out = append(out, ch)
		}
		count = 0
	}
	if count != 0 {
		return "", fmt.Errorf("dangling count %d", count)
	}
	return string(out), nil
}

func main() {
	raw := "aaabbbccccd"
	packed := encode(raw)
	fmt.Println("encoded:", packed)
	back, err := decode(packed)
	fmt.Println("decoded:", back, "err:", err)
}

How the snippet works

Under the hood: the functions encode, decode and main.

Repetition is confined to for i := 1; i < len(s); i++ — the rest of the file is straight-line.

Points of care

  • Built-in APIs only — no supply chain needs to be vetted.

Using it

The primary signature, spelled out, is func encode(s string) string

The run prints labeled output — encoded:, decoded: — when the file runs.

main calls 2 helpers in sequence: encode and decode.

The key statements, annotated

return "", fmt.Errorf("missing count before %q", ch)
return "", fmt.Errorf("dangling count %d", count)
func main() {
	raw := "aaabbbccccd"
	packed := encode(raw)
	fmt.Println("encoded:", packed)
	back, err := decode(packed)
	fmt.Println("decoded:", back, "err:", err)
}

Interactive Tools for This Topic

FAQ

What does Run-Length Encoding Round Trip print when run?
Running the file directly is enough — expect labeled output lines such as `encoded:`, `decoded:`.