|
| 1 | +package sqlcommenter |
| 2 | + |
| 3 | +// Code is adapted from standard library package net/url. |
| 4 | +// Copyright (c) 2009 The Go Authors. All rights reserved. |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | +) |
| 9 | + |
| 10 | +const upperhex = "0123456789ABCDEF" |
| 11 | + |
| 12 | +func writeQueryEscape(s string, b *bytes.Buffer) { |
| 13 | + writeEscape(s, true, b) |
| 14 | +} |
| 15 | + |
| 16 | +func writePathEscape(s string, b *bytes.Buffer) { |
| 17 | + writeEscape(s, false, b) |
| 18 | +} |
| 19 | + |
| 20 | +func writeEscape(s string, query bool, b *bytes.Buffer) { |
| 21 | + spaceCount, hexCount := 0, 0 |
| 22 | + for i := 0; i < len(s); i++ { |
| 23 | + c := s[i] |
| 24 | + if shouldEscape(c, query) { |
| 25 | + if c == ' ' && query { |
| 26 | + spaceCount++ |
| 27 | + } else { |
| 28 | + hexCount++ |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + if spaceCount == 0 && hexCount == 0 { |
| 34 | + b.WriteString(s) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + if hexCount == 0 { |
| 39 | + for i := 0; i < len(s); i++ { |
| 40 | + if s[i] == ' ' { |
| 41 | + b.WriteByte('+') |
| 42 | + } else { |
| 43 | + b.WriteByte(s[i]) |
| 44 | + } |
| 45 | + } |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + for i := 0; i < len(s); i++ { |
| 50 | + switch c := s[i]; { |
| 51 | + case c == ' ' && query: |
| 52 | + b.WriteByte('+') |
| 53 | + case shouldEscape(c, query): |
| 54 | + b.WriteByte('%') |
| 55 | + b.WriteByte(upperhex[c>>4]) |
| 56 | + b.WriteByte(upperhex[c&15]) |
| 57 | + default: |
| 58 | + b.WriteByte(c) |
| 59 | + } |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +func shouldEscape(c byte, query bool) bool { |
| 64 | + if 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' { |
| 65 | + return false |
| 66 | + } |
| 67 | + switch c { |
| 68 | + case '-', '_', '.', '~': |
| 69 | + return false |
| 70 | + case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': |
| 71 | + if query { |
| 72 | + return true |
| 73 | + } |
| 74 | + return c == '/' || c == ';' || c == ',' || c == '?' |
| 75 | + } |
| 76 | + return true |
| 77 | +} |
0 commit comments