Created
November 17, 2021 14:48
-
-
Save stokito/43deddaa18ec309834bea175577101da to your computer and use it in GitHub Desktop.
Fast json text value encode: replace
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
// EncodeToJsonAsciiText Fast json text value encode: escape " with \" and \ with \\ | |
// Any non printable or Unicode chars will be removed. | |
// Please note that value is not enclosed into double quotes. | |
func EncodeToJsonAsciiText(plain string) string { | |
plainLen := len(plain) | |
newSize := plainLen | |
for i := 0; i < plainLen; i++ { | |
c := plain[i] | |
if c < 32 || c > 127 { // skip non printable and unicode | |
newSize-- | |
} | |
if c == '\\' || c == '"' { | |
newSize++ | |
} | |
} | |
if plainLen == newSize { | |
return plain | |
} | |
encoded := make([]byte, newSize) | |
encodedIdx := 0 | |
for i := 0; i < plainLen; i++ { | |
c := plain[i] | |
if c < 32 || c > 127 { // skip non printable and unicode | |
continue | |
} | |
if c == '\\' { | |
encoded[encodedIdx] = '\\' | |
encodedIdx++ | |
encoded[encodedIdx] = '\\' | |
} else if c == '"' { | |
encoded[encodedIdx] = '\\' | |
encodedIdx++ | |
encoded[encodedIdx] = '"' | |
} else { | |
encoded[encodedIdx] = c | |
} | |
encodedIdx++ | |
} | |
return string(encoded) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment