Skip to content

Instantly share code, notes, and snippets.

@thesues
Last active April 2, 2019 09:05
Show Gist options
  • Save thesues/a0b69980e301aacd5d8bea2d35be01a2 to your computer and use it in GitHub Desktop.
Save thesues/a0b69980e301aacd5d8bea2d35be01a2 to your computer and use it in GitHub Desktop.
colonescape.go
package util
import (
"bytes"
)
func EscapeColon(s string) string {
//Byte loop is OK for utf8
buf := new(bytes.Buffer)
l := len(s)
for i := 0; i < l; i++ {
if s[i] == '%' {
buf.WriteString("%%")
} else if s[i] == ':' {
buf.WriteString("%n")
} else {
buf.WriteByte(s[i])
}
}
return buf.String()
}
func UnescapeColon(s string) string {
buf := new(bytes.Buffer)
l := len(s)
for i := 0; i < l; i++ {
if s[i] == '%' {
i++
if i == l {
panic("never be here")
}
if s[i] == '%' {
buf.WriteString("%")
} else if s[i] == 'n' {
buf.WriteString(":")
} else {
panic("never be here")
}
} else {
buf.WriteByte(s[i])
}
}
return buf.String()
}
package util
import (
"fmt"
"github.com/stretchr/testify/assert"
"testing"
"strings"
)
var _ = fmt.Println
func TestEscapeColon(t *testing.T) {
s1 := "asdf:a sdf"
out := EscapeColon(s1)
assert.False(t, strings.Contains(out, ":"))
assert.Equal(t, "asdf%na sdf", out)
assert.Equal(t, s1, UnescapeColon(out))
s1 = ":%%:%"
out = EscapeColon(s1)
assert.Equal(t, s1, UnescapeColon(out))
assert.False(t, strings.Contains(out, ":"))
s1 = "nor_mal?!\\@ @!"
assert.Equal(t, s1, EscapeColon(s1))
assert.False(t, strings.Contains(out, ":"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment