Skip to content

Commit

Permalink
Commit initial versions of percent_encode and percent_decode
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Scavo committed Dec 10, 2016
1 parent 63d29e9 commit e0391d7
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions lib/http_tools.sh
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,63 @@ get_header_value () {
return 0
}

#######################################################################
# This function percent-encodes all characters except the "Unreserved
# Characters" defined in section 2.3 of RFC 3986.
#
# See: https://gist.github.com/cdown/1163649
# https://en.wikipedia.org/wiki/Percent-encoding
#######################################################################
percent_encode () {
# percent_encode <string>

# make sure there is one (and only one) command-line argument
if [ $# -ne 1 ]; then
echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2
return 2
fi

# this implementation assumes a particular collating sequence
local LC_COLLATE=C

local length
local c

length="${#1}"
for (( i = 0; i < length; i++ )); do
c="${1:i:1}"
case "$c" in
[a-zA-Z0-9.~_-]) printf "$c" ;;
*) printf '%%%02X' "'$c"
esac
done
}

#######################################################################
# This function percent-decodes all percent-encoded characters.
#######################################################################
percent_decode () {
# percent_decode <string>

# make sure there is one (and only one) command-line argument
if [ $# -ne 1 ]; then
echo "ERROR: $FUNCNAME: incorrect number of arguments: $# (1 required)" >&2
return 2
fi

local encoded_string

# the percent_encode function doesn't convert spaces to
# plus signs (+) but the input string to the percent_decode
# function may have been encoded in some other manner so we
# first decode plus signs (+) into spaces
encoded_string="${1//+/ }"

printf '%b' "${encoded_string//%/\\x}"
}

# DEPRECATED: Use percent_encode and percent_decode instead.
#
# URL encoder/decoder
# see: https://gist.github.com/cdown/1163649
url_encode () {
Expand Down

0 comments on commit e0391d7

Please sign in to comment.