Created
October 30, 2013 18:43
-
-
Save benstiglitz/7237812 to your computer and use it in GitHub Desktop.
Today’s bad shell script idea: netstrings.
This file contains 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
#!/bin/bash | |
encode() { | |
local data | |
OLDIFS="${IFS}"; IFS="" | |
read -d "" data | |
IFS="${OLDIFS}" | |
echo -n $(echo -n "$data" | wc -c) | |
echo -n ":$data" | |
echo -n "," | |
} | |
decode() { | |
local data net_count terminator | |
read -d : net_count | |
OLDIFS="${IFS}"; IFS="" | |
if [ ! "${net_count}" == "0" ] ; then | |
read -d "" -n "${net_count}" data | |
fi | |
read -d "" -n 1 terminator | |
IFS="${OLDIFS}" | |
if [ ! "$terminator" == "," ] ; then | |
echo "Invalid netstring terminator ${terminator}" | |
exit 1 | |
fi | |
echo -n "${data}" | |
} | |
run_tests() { | |
( echo -n "Looks like this is:" | encode ; | |
echo -n "" | encode ; | |
echo -ne "\nworking.\n" | encode ) | | |
( decode ; decode; decode ) | |
} | |
if [ "$(basename $0)" == "netstring.sh" ] ; then | |
run_tests | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment