Skip to content

Commit

Permalink
Some handling for invalid escape sequences
Browse files Browse the repository at this point in the history
Defined behavior is better that exploding, I guess.
  • Loading branch information
dustin committed Aug 14, 2016
1 parent 6e8eda4 commit ba0abea
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
16 changes: 13 additions & 3 deletions bytes.go
Expand Up @@ -23,25 +23,35 @@ func arreq(a, b []string) bool {
}

func unescape(s string) string {

n := strings.Count(s, "~")
if n == 0 {
return s
}

t := make([]byte, len(s)-n) // remove one char per ~
t := make([]byte, len(s)-n+1) // remove one char per ~
w := 0
start := 0
for i := 0; i < n; i++ {
j := start + strings.Index(s[start:], "~")
w += copy(t[w:], s[start:j])
switch s[j+1] {
if len(s) < j+2 {
t[w] = '~'
w++
break
}
c := s[j+1]
switch c {
case '0':
t[w] = '~'
w++
case '1':
t[w] = '/'
w++
default:
t[w] = '~'
w++
t[w] = c
w++
}
start = j + 2
}
Expand Down
29 changes: 28 additions & 1 deletion bytes_test.go
Expand Up @@ -428,6 +428,34 @@ func TestEscape(t *testing.T) {
t.Errorf("unescape(escape(%q) [%q]) = %q", test, esc, got)
}
}

tf := func(s chars) bool {
uns := unescape(string(s))
got := string(escape(uns, nil))
return got == string(s)
}
quick.Check(tf, nil)
}

func TestUnescape(t *testing.T) {
tests := []struct {
in, exp string
}{
{"", ""},
{"/", "/"},
{"/thing", "/thing"},
{"~0", "~"},
{"~1", "/"},
{"~2", "~2"},
{"~", "~"},
{"thing~", "thing~"},
}
for _, test := range tests {
got := string(unescape(test.in))
if got != test.exp {
t.Errorf("on %q, got %q, wanted %q", test.in, got, test.exp)
}
}
}

var codeJSON []byte
Expand Down Expand Up @@ -550,7 +578,6 @@ func oldunescape(s string) string {

func TestNewEscaper(t *testing.T) {
of := func(in chars) string {
t.Logf("Looking at %q", in)
return oldunescape(string(in))
}
nf := func(in chars) string {
Expand Down

0 comments on commit ba0abea

Please sign in to comment.