1 if [ ! "$_STRINGS_SUBR" ]; then _STRINGS_SUBR=1
3 # Copyright (c) 2006-2013 Devin Teske
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
15 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 ############################################################ INCLUDES
31 BSDCFG_SHARE="/usr/share/bsdconfig"
32 . $BSDCFG_SHARE/common.subr || exit 1
34 ############################################################ GLOBALS
37 # A Literal newline (for use with f_replace_all(), or IFS, or whatever)
43 # Valid characters that can appear in an sh(1) variable name
45 # Please note that the character ranges A-Z and a-z should be avoided because
46 # these can include accent characters (which are not valid in a variable name).
47 # For example, A-Z matches any character that sorts after A but before Z,
48 # including A and Z. Although ASCII order would make more sense, that is not
51 VALID_VARNAME_CHARS="0-9ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_"
53 ############################################################ FUNCTIONS
55 # f_substr "$string" $start [$length]
57 # Simple wrapper to awk(1)'s `substr' function.
61 local string="$1" start="${2:-0}" len="${3:-0}"
62 echo "$string" | awk "{ print substr(\$0, $start, $len) }"
65 # f_snprintf $var_to_set $size $format [$arguments ...]
67 # Similar to snprintf(3), write at most $size number of bytes into $var_to_set
68 # using printf(1) syntax (`$format [$arguments ...]'). The value of $var_to_set
69 # is NULL unless at-least one byte is stored from the output.
73 local __var_to_set="$1" __size="$2"
74 shift 2 # var_to_set size
75 eval "$__var_to_set"=\$\( printf -- \"\$@\" \| \
76 awk -v max=\"\$__size\" \''
80 print substr($0,0,(max > 0 ? len : max + len))
86 # f_sprintf $var_to_set $format [$arguments ...]
88 # Similar to sprintf(3), write a string into $var_to_set using printf(1) syntax
89 # (`$format [$arguments ...]').
93 local __var_to_set="$1"
95 eval "$__var_to_set"=\$\( printf -- \"\$@\" \)
98 # f_vsnprintf $var_to_set $size $format $format_args
100 # Similar to vsnprintf(3), write at most $size number of bytes into $var_to_set
101 # using printf(1) syntax (`$format $format_args'). The value of $var_to_set is
102 # NULL unless at-least one byte is stored from the output.
106 # limit=7 format="%s"
107 # format_args="'abc 123'" # 3-spaces between abc and 123
108 # f_vsnprintf foo $limit "$format" "$format_args" # foo=[abc 1]
112 # limit=12 format="%s %s"
113 # format_args=" 'doghouse' 'foxhound' "
114 # # even more spaces added to illustrate escape-method
115 # f_vsnprintf foo $limit "$format" "$format_args" # foo=[doghouse fox]
119 # limit=13 format="%s %s"
120 # f_shell_escape arg1 'aaa"aaa' # arg1=[aaa"aaa] (no change)
121 # f_shell_escape arg2 "aaa'aaa" # arg2=[aaa'\''aaa] (escaped s-quote)
122 # format_args="'$arg1' '$arg2'" # use single-quotes to surround args
123 # f_vsnprintf foo $limit "$format" "$format_args" # foo=[aaa"aaa aaa'a]
125 # In all of the above examples, the call to f_vsnprintf() does not change. Only
126 # the contents of $limit, $format, and $format_args changes in each example.
130 eval f_snprintf \"\$1\" \"\$2\" \"\$3\" $4
133 # f_vsprintf $var_to_set $format $format_args
135 # Similar to vsprintf(3), write a string into $var_to_set using printf(1)
136 # syntax (`$format $format_args').
140 eval f_sprintf \"\$1\" \"\$2\" $3
143 # f_longest_line_length
145 # Simple wrapper to an awk(1) script to print the length of the longest line of
146 # input (read from stdin). Supports the newline escape-sequence `\n' for
147 # splitting a single line into multiple lines.
149 f_longest_line_length_awk='
150 BEGIN { longest = 0 }
152 if (split($0, lines, /\\n/) > 1)
156 len = length(lines[n])
157 longest = ( len > longest ? len : longest )
163 longest = ( len > longest ? len : longest )
166 END { print longest }
168 f_longest_line_length()
170 awk "$f_longest_line_length_awk"
175 # Simple wrapper to an awk(1) script to print the number of lines read from
176 # stdin. Supports newline escape-sequence `\n' for splitting a single line into
179 f_number_of_lines_awk='
180 BEGIN { num_lines = 0 }
182 num_lines += split(" "$0, unused, /\\n/)
184 END { print num_lines }
188 awk "$f_number_of_lines_awk"
193 # Returns true if argument is a positive/negative whole integer.
198 [ "${arg:-x}" = "${arg%[!0-9]*}" ]
201 # f_uriencode [$text]
203 # Encode $text for the purpose of embedding safely into a URL. Non-alphanumeric
204 # characters are converted to `%XX' sequence where XX represents the hexa-
205 # decimal ordinal of the non-alphanumeric character. If $text is missing, data
206 # is instead read from standard input.
211 for (n = 0; n < 256; n++) pack[sprintf("%c", n)] = sprintf("%%%02x", n)
216 for (n = 1; n <= slen; n++) {
217 char = substr($0, n, 1)
218 if ( char !~ /^[[:alnum:]_]$/ ) char = pack[char]
221 output = output ( output ? "%0a" : "" ) sline
227 if [ $# -gt 0 ]; then
228 echo "$1" | awk "$f_uriencode_awk"
230 awk "$f_uriencode_awk"
234 # f_uridecode [$text]
236 # Decode $text from a URI. Encoded characters are converted from their `%XX'
237 # sequence into original unencoded ASCII sequences. If $text is missing, data
238 # is instead read from standard input.
241 BEGIN { for (n = 0; n < 256; n++) chr[n] = sprintf("%c", n) }
245 for (n = 1; n <= slen; n++)
247 seq = substr($0, n, 3)
248 if ( seq ~ /^%[[:xdigit:]][[:xdigit:]]$/ ) {
249 hex = substr(seq, 2, 2)
250 sline = sline chr[sprintf("%u", "0x"hex)]
253 sline = sline substr(seq, 1, 1)
260 if [ $# -gt 0 ]; then
261 echo "$1" | awk "$f_uridecode_awk"
263 awk "$f_uridecode_awk"
267 # f_replaceall $string $find $replace [$var_to_set]
269 # Replace all occurrences of $find in $string with $replace. If $var_to_set is
270 # either missing or NULL, the variable name is produced on standard out for
271 # capturing in a sub-shell (which is less recommended due to performance
274 # To replace newlines or a sequence containing the newline character, use $NL
275 # as `\n' is not supported.
279 local __left="" __right="$1"
280 local __find="$2" __replace="$3" __var_to_set="$4"
282 case "$__right" in *$__find*)
283 __left="$__left${__right%%$__find*}$__replace"
284 __right="${__right#*$__find}"
289 __left="$__left${__right#*$__find}"
290 if [ "$__var_to_set" ]; then
291 setvar "$__var_to_set" "$__left"
297 # f_str2varname $string [$var_to_set]
299 # Convert a string into a suitable value to be used as a variable name
300 # by converting unsuitable characters into the underscrore [_]. If $var_to_set
301 # is either missing or NULL, the variable name is produced on standard out for
302 # capturing in a sub-shell (which is less recommended due to performance
307 local __string="$1" __var_to_set="$2"
308 f_replaceall "$__string" "[!$VALID_VARNAME_CHARS]" "_" "$__var_to_set"
311 # f_shell_escape $string [$var_to_set]
313 # Escape $string for shell eval statement(s) by replacing all single-quotes
314 # with a special sequence that creates a compound string when interpolated
315 # by eval with surrounding single-quotes.
320 # f_shell_escape "$foo" bar # bar=[abc'\''123]
321 # eval echo \'$bar\' # produces abc'123
323 # This is helpful when processing an argument list that has to retain its
324 # escaped structure for later evaluations.
326 # WARNING: Surrounding single-quotes are not added; this is the responsibility
327 # of the code passing the escaped values to eval (which also aids readability).
331 local __string="$1" __var_to_set="$2"
332 f_replaceall "$__string" "'" "'\\''" "$__var_to_set"
335 # f_shell_unescape $string [$var_to_set]
337 # The antithesis of f_shell_escape(), this function takes an escaped $string
343 # f_shell_escape "$foo" bar # bar=[abc'\''123]
344 # f_shell_unescape "$bar" # produces abc'123
348 local __string="$1" __var_to_set="$2"
349 f_replaceall "$__string" "'\\''" "'" "$__var_to_set"
352 # f_expand_number $string [$var_to_set]
354 # Unformat $string into a number, optionally to be stored in $var_to_set. This
355 # function follows the SI power of two convention.
359 # Prefix Description Multiplier
363 # T tera 1099511627776
364 # P peta 1125899906842624
365 # E exa 1152921504606846976
367 # NOTE: Prefixes are case-insensitive.
369 # Upon successful completion, success status is returned; otherwise the number
370 # -1 is produced ($var_to_set set to -1 or if $var_to_set is NULL or missing)
371 # on standard output. In the case of failure, the error status will be one of:
374 # 1 Given $string contains no digits
375 # 2 An unrecognized prefix was given
376 # 3 Result too large to calculate
380 local __string="$1" __var_to_set="$2"
381 local __cp __num __bshift __maxinput
383 # Remove any leading non-digits
384 __string="${__string#${__string%%[0-9]*}}"
386 # Store the numbers (no trailing suffix)
387 __num="${__string%%[!0-9]*}"
389 # Produce `-1' if string didn't contain any digits
390 if [ ! "$__num" ]; then
391 if [ "$__var_to_set" ]; then
392 setvar "$__var_to_set" -1
396 return 1 # 1 = "Given $string contains no digits"
399 # Remove all the leading numbers from the string to get at the prefix
400 __string="${__string#"$__num"}"
403 # Test for invalid prefix (and determine bitshift length)
406 ""|[[:space:]]*) # Shortcut
407 if [ "$__var_to_set" ]; then
408 setvar "$__var_to_set" $__num
413 [Kk]*) __bshift=10 ;;
414 [Mm]*) __bshift=20 ;;
415 [Gg]*) __bshift=30 ;;
416 [Tt]*) __bshift=40 ;;
417 [Pp]*) __bshift=50 ;;
418 [Ee]*) __bshift=60 ;;
421 if [ "$__var_to_set" ]; then
422 setvar "$__var_to_set" -1
426 return 2 # 2 = "An unrecognized prefix was given"
429 # Determine if the wheels fall off
430 __maxinput=$(( 0x7fffffffffffffff >> $__bshift ))
431 if [ $__num -gt $__maxinput ]; then
432 # Input (before expanding) would exceed 64-bit signed int
433 if [ "$__var_to_set" ]; then
434 setvar "$__var_to_set" -1
438 return 3 # 3 = "Result too large to calculate"
441 # Shift the number out and produce it
442 __num=$(( $__num << $__bshift ))
443 if [ "$__var_to_set" ]; then
444 setvar "$__var_to_set" $__num
450 ############################################################ MAIN
452 f_dprintf "%s: Successfully loaded." strings.subr
454 fi # ! $_STRINGS_SUBR