Created
March 31, 2020 20:17
-
-
Save karrick/490dce13ab8ff8fb87645a383fb371ad to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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