Skip to content

Instantly share code, notes, and snippets.

@karrick
Created March 31, 2020 20:17
Show Gist options
  • Save karrick/490dce13ab8ff8fb87645a383fb371ad to your computer and use it in GitHub Desktop.
Save karrick/490dce13ab8ff8fb87645a383fb371ad to your computer and use it in GitHub Desktop.
func escapeSingleQuote(slice []byte) []byte {
l := len(slice)
var shifts int
for index := l - 1; index >= 0; index-- {
if slice[index] == '\'' {
slice = append(slice, byte(0))
copy(slice[index+1:], slice[index:]) // move bytes to right
shifts++
}
}
return slice[:l+shifts]
}
func ensureBytes(t *testing.T, got, want []byte) {
t.Helper()
if !bytes.Equal(got, want) {
t.Errorf("GOT: %q; WANT: %q", got, want)
}
}
func TestEscapeSingleQuote(t *testing.T) {
t.Run("nil", func(t *testing.T) {
ensureBytes(t, escapeSingleQuote(nil), nil)
})
t.Run("single quote", func(t *testing.T) {
ensureBytes(t, escapeSingleQuote([]byte{'\''}), []byte{'\'', '\''})
})
t.Run("two single quotes", func(t *testing.T) {
ensureBytes(t, escapeSingleQuote([]byte{'\'', '\''}), []byte{'\'', '\'', '\'', '\''})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment