Created
January 8, 2015 13:52
-
-
Save kevinlebrun/3ee62e373ecd783ea2e4 to your computer and use it in GitHub Desktop.
Quickcheck, Reverse, and Runes in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"testing" | |
"testing/quick" | |
"unicode/utf8" | |
) | |
func reverseUsingBytes(a string) string { | |
b := make([]byte, len(a)) | |
// a for range loop would have used runes instead of bytes | |
for i := 0; i < len(a); i++ { | |
b[len(a)-i-1] = a[i] | |
} | |
return string(b) | |
} | |
func reverseUsingRunes(a string) string { | |
n := utf8.RuneCountInString(a) | |
b := make([]rune, n) | |
for i, r := range []rune(a) { | |
b[n-i-1] = r | |
} | |
return string(b) | |
} | |
var reverse = reverseUsingRunes | |
func TestDoubleReverse(t *testing.T) { | |
f := func(s string) bool { return reverse(reverse(s)) == s } | |
if err := quick.Check(f, nil); err != nil { | |
t.Error(err) | |
} | |
} | |
func TestReverseConcat(t *testing.T) { | |
f := func(x, y string) bool { | |
return reverse(x)+reverse(y) == reverse(y+x) | |
} | |
if err := quick.Check(f, nil); err != nil { | |
t.Error(err) | |
} | |
} | |
func TestValidUTF8(t *testing.T) { | |
f := func(s string) bool { | |
return utf8.ValidString(reverse(s)) | |
} | |
if err := quick.Check(f, nil); err != nil { | |
t.Error(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment