quote implements a string quoting function. The string will be wrapped in double quotes, and all valid CEL escape sequences will be escaped to show up literally if printed. If the input contains any invalid UTF-8, the invalid runes will be replaced with utf8.RuneError.
(s string)
| 846 | // literally if printed. If the input contains any invalid UTF-8, the invalid runes |
| 847 | // will be replaced with utf8.RuneError. |
| 848 | func quote(s string) (string, error) { |
| 849 | var quotedStrBuilder strings.Builder |
| 850 | for _, c := range sanitize(s) { |
| 851 | switch c { |
| 852 | case '\a': |
| 853 | quotedStrBuilder.WriteString("\\a") |
| 854 | case '\b': |
| 855 | quotedStrBuilder.WriteString("\\b") |
| 856 | case '\f': |
| 857 | quotedStrBuilder.WriteString("\\f") |
| 858 | case '\n': |
| 859 | quotedStrBuilder.WriteString("\\n") |
| 860 | case '\r': |
| 861 | quotedStrBuilder.WriteString("\\r") |
| 862 | case '\t': |
| 863 | quotedStrBuilder.WriteString("\\t") |
| 864 | case '\v': |
| 865 | quotedStrBuilder.WriteString("\\v") |
| 866 | case '\\': |
| 867 | quotedStrBuilder.WriteString("\\\\") |
| 868 | case '"': |
| 869 | quotedStrBuilder.WriteString("\\\"") |
| 870 | default: |
| 871 | quotedStrBuilder.WriteRune(c) |
| 872 | } |
| 873 | } |
| 874 | escapedStr := quotedStrBuilder.String() |
| 875 | return "\"" + escapedStr + "\"", nil |
| 876 | } |
| 877 | |
| 878 | // sanitize replaces all invalid runes in the given string with utf8.RuneError. |
| 879 | func sanitize(s string) string { |